Bug 1772101 - Part 39: Use plain object for lazy getter in toolkit/components/search/. r=daleharvey

Differential Revision: https://phabricator.services.mozilla.com/D147980
This commit is contained in:
Tooru Fujisawa
2022-06-08 20:45:19 +00:00
parent 2a8d306e81
commit 15c382f542
9 changed files with 397 additions and 312 deletions

View File

@@ -9,16 +9,18 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
EngineURL: "resource://gre/modules/SearchEngine.jsm",
SearchEngine: "resource://gre/modules/SearchEngine.jsm",
SearchUtils: "resource://gre/modules/SearchUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logConsole", () => {
XPCOMUtils.defineLazyGetter(lazy, "logConsole", () => {
return console.createInstance({
prefix: "OpenSearchEngine",
maxLogLevel: SearchUtils.loggingEnabled ? "Debug" : "Warn",
maxLogLevel: lazy.SearchUtils.loggingEnabled ? "Debug" : "Warn",
});
});
@@ -61,7 +63,7 @@ function ENSURE_WARN(assertion, message, resultCode) {
/**
* OpenSearchEngine represents an OpenSearch base search engine.
*/
class OpenSearchEngine extends SearchEngine {
class OpenSearchEngine extends lazy.SearchEngine {
// The data describing the engine, in the form of an XML document element.
_data = null;
@@ -83,7 +85,8 @@ class OpenSearchEngine extends SearchEngine {
* A callback to receive any details of errors.
*/
_install(uri, callback) {
let loadURI = uri instanceof Ci.nsIURI ? uri : SearchUtils.makeURI(uri);
let loadURI =
uri instanceof Ci.nsIURI ? uri : lazy.SearchUtils.makeURI(uri);
if (!loadURI) {
throw Components.Exception(
loadURI,
@@ -98,9 +101,9 @@ class OpenSearchEngine extends SearchEngine {
);
}
logConsole.debug("_install: Downloading engine from:", loadURI.spec);
lazy.logConsole.debug("_install: Downloading engine from:", loadURI.spec);
var chan = SearchUtils.makeChannel(loadURI);
var chan = lazy.SearchUtils.makeChannel(loadURI);
if (this._engineToUpdate && chan instanceof Ci.nsIHttpChannel) {
var lastModified = this._engineToUpdate.getAttr("updatelastmodified");
@@ -110,7 +113,7 @@ class OpenSearchEngine extends SearchEngine {
}
this._uri = loadURI;
var listener = new SearchUtils.LoadListener(
var listener = new lazy.SearchUtils.LoadListener(
chan,
/(^text\/|xml$)/,
this._onLoad.bind(this, callback)
@@ -132,7 +135,7 @@ class OpenSearchEngine extends SearchEngine {
_onLoad(callback, bytes) {
let onError = errorCode => {
if (this._engineToUpdate) {
logConsole.warn("Failed to update", this._engineToUpdate.name);
lazy.logConsole.warn("Failed to update", this._engineToUpdate.name);
}
callback?.(errorCode);
};
@@ -149,7 +152,7 @@ class OpenSearchEngine extends SearchEngine {
try {
this._initFromData();
} catch (ex) {
logConsole.error("_onLoad: Failed to init engine!", ex);
lazy.logConsole.error("_onLoad: Failed to init engine!", ex);
if (ex.result == Cr.NS_ERROR_FILE_CORRUPTED) {
onError(Ci.nsISearchService.ERROR_ENGINE_CORRUPTED);
@@ -181,12 +184,12 @@ class OpenSearchEngine extends SearchEngine {
// existing one), a duplicate engine does not already exist.
if (Services.search.getEngineByName(this.name)) {
onError(Ci.nsISearchService.ERROR_DUPLICATE_ENGINE);
logConsole.debug("_onLoad: duplicate engine found, bailing");
lazy.logConsole.debug("_onLoad: duplicate engine found, bailing");
return;
}
this._loadPath = OpenSearchEngine.getAnonymizedLoadPath(
SearchUtils.sanitizeName(this.name),
lazy.SearchUtils.sanitizeName(this.name),
this._uri
);
if (this._extensionID) {
@@ -194,13 +197,13 @@ class OpenSearchEngine extends SearchEngine {
}
this.setAttr(
"loadPathHash",
SearchUtils.getVerificationHash(this._loadPath)
lazy.SearchUtils.getVerificationHash(this._loadPath)
);
}
// Notify the search service of the successful load. It will deal with
// updates by checking this._engineToUpdate.
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.LOADED);
lazy.SearchUtils.notifyAction(this, lazy.SearchUtils.MODIFIED_TYPE.LOADED);
callback?.();
}
@@ -223,7 +226,7 @@ class OpenSearchEngine extends SearchEngine {
(element.localName == OPENSEARCH_LOCALNAME &&
OPENSEARCH_NAMESPACES.includes(element.namespaceURI))
) {
logConsole.debug("Initing search plugin from", this._location);
lazy.logConsole.debug("Initing search plugin from", this._location);
this._parse();
} else {
@@ -266,11 +269,11 @@ class OpenSearchEngine extends SearchEngine {
// Support an alternate suggestion type, see bug 1425827 for details.
if (type == "application/json" && rels.includes("suggestions")) {
type = SearchUtils.URL_TYPE.SUGGEST_JSON;
type = lazy.SearchUtils.URL_TYPE.SUGGEST_JSON;
}
try {
var url = new EngineURL(type, method, template);
var url = new lazy.EngineURL(type, method, template);
} catch (ex) {
throw Components.Exception(
"_parseURL: failed to add " + template + " as a URL",
@@ -289,7 +292,7 @@ class OpenSearchEngine extends SearchEngine {
url.addParam(param.getAttribute("name"), param.getAttribute("value"));
} catch (ex) {
// Ignore failure
logConsole.error("_parseURL: Url element has an invalid param");
lazy.logConsole.error("_parseURL: Url element has an invalid param");
}
}
// Note: MozParams are not supported for OpenSearch engines as they
@@ -312,7 +315,7 @@ class OpenSearchEngine extends SearchEngine {
let isPrefered = width == 16 && height == 16;
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0) {
logConsole.warn(
lazy.logConsole.warn(
"OpenSearch image element must have positive width and height."
);
return;
@@ -342,7 +345,7 @@ class OpenSearchEngine extends SearchEngine {
this._parseURL(child);
} catch (ex) {
// Parsing of the element failed, just skip it.
logConsole.error("Failed to parse URL child:", ex);
lazy.logConsole.error("Failed to parse URL child:", ex);
}
break;
case "Image":
@@ -379,7 +382,7 @@ class OpenSearchEngine extends SearchEngine {
Cr.NS_ERROR_FAILURE
);
}
if (!this.supportsResponseType(SearchUtils.URL_TYPE.SEARCH)) {
if (!this.supportsResponseType(lazy.SearchUtils.URL_TYPE.SEARCH)) {
throw Components.Exception(
"_parse: No text/html result type!",
Cr.NS_ERROR_FAILURE
@@ -389,7 +392,10 @@ class OpenSearchEngine extends SearchEngine {
get _hasUpdates() {
// Whether or not the engine has an update URL
let selfURL = this._getURLOfType(SearchUtils.URL_TYPE.OPENSEARCH, "self");
let selfURL = this._getURLOfType(
lazy.SearchUtils.URL_TYPE.OPENSEARCH,
"self"
);
return !!(this._updateURL || this._iconUpdateURL || selfURL);
}

View File

@@ -12,7 +12,9 @@ const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ExtensionParent: "resource://gre/modules/ExtensionParent.jsm",
Region: "resource://gre/modules/Region.jsm",
SearchUtils: "resource://gre/modules/SearchUtils.jsm",
@@ -25,10 +27,10 @@ const BinaryInputStream = Components.Constructor(
"setInputStream"
);
XPCOMUtils.defineLazyGetter(this, "logConsole", () => {
XPCOMUtils.defineLazyGetter(lazy, "logConsole", () => {
return console.createInstance({
prefix: "SearchEngine",
maxLogLevel: SearchUtils.loggingEnabled ? "Debug" : "Warn",
maxLogLevel: lazy.SearchUtils.loggingEnabled ? "Debug" : "Warn",
});
});
@@ -107,7 +109,7 @@ function rescaleIcon(byteArray, contentType, size = 32) {
let container = imgTools.decodeImageFromArrayBuffer(arrayBuffer, contentType);
let stream = imgTools.encodeScaledImage(container, "image/png", size, size);
let streamSize = stream.available();
if (streamSize > SearchUtils.MAX_ICON_SIZE) {
if (streamSize > lazy.SearchUtils.MAX_ICON_SIZE) {
throw new Error("Icon is too big");
}
let bis = new BinaryInputStream(stream);
@@ -126,7 +128,7 @@ const ParamPreferenceCache = {
initCache() {
this.branch = Services.prefs.getDefaultBranch(
SearchUtils.BROWSER_SEARCH_PREF + "param."
lazy.SearchUtils.BROWSER_SEARCH_PREF + "param."
);
this.cache = new Map();
this.nimbusCache = new Map();
@@ -137,8 +139,8 @@ const ParamPreferenceCache = {
this.onNimbusUpdate = this.onNimbusUpdate.bind(this);
this.onNimbusUpdate();
NimbusFeatures.search.onUpdate(this.onNimbusUpdate);
NimbusFeatures.search.ready().then(this.onNimbusUpdate);
lazy.NimbusFeatures.search.onUpdate(this.onNimbusUpdate);
lazy.NimbusFeatures.search.ready().then(this.onNimbusUpdate);
},
observe(subject, topic, data) {
@@ -146,7 +148,8 @@ const ParamPreferenceCache = {
},
onNimbusUpdate() {
let extraParams = NimbusFeatures.search.getVariable("extraParams") || [];
let extraParams =
lazy.NimbusFeatures.search.getVariable("extraParams") || [];
for (const { key, value } of extraParams) {
this.nimbusCache.set(key, value);
}
@@ -283,12 +286,12 @@ function ParamSubstitution(paramValue, searchTerms, engine) {
// moz: parameters are only available for default search engines.
if (name.startsWith("moz:") && engine.isAppProvided) {
// {moz:locale} is common.
if (name == SearchUtils.MOZ_PARAM.LOCALE) {
if (name == lazy.SearchUtils.MOZ_PARAM.LOCALE) {
return Services.locale.requestedLocale;
}
// {moz:date}
if (name == SearchUtils.MOZ_PARAM.DATE) {
if (name == lazy.SearchUtils.MOZ_PARAM.DATE) {
let date = new Date();
let pad = number => number.toString().padStart(2, "0");
return (
@@ -369,9 +372,9 @@ class EngineURL {
this.type = type;
this.method = method;
this._queryCharset = SearchUtils.DEFAULT_QUERY_CHARSET;
this._queryCharset = lazy.SearchUtils.DEFAULT_QUERY_CHARSET;
var templateURI = SearchUtils.makeURI(template);
var templateURI = lazy.SearchUtils.makeURI(template);
if (!templateURI) {
throw Components.Exception(
"new EngineURL: template is not a valid URI!",
@@ -457,8 +460,8 @@ class EngineURL {
let paramValue = param.value;
// Override the parameter value if the engine has a region
// override defined for our current region.
if (engine._regionParams?.[Region.current]) {
let override = engine._regionParams[Region.current].find(
if (engine._regionParams?.[lazy.Region.current]) {
let override = engine._regionParams[lazy.Region.current].find(
p => p.name == param.name
);
if (override) {
@@ -543,7 +546,7 @@ class EngineURL {
template: this.template,
};
if (this.type != SearchUtils.URL_TYPE.SEARCH) {
if (this.type != lazy.SearchUtils.URL_TYPE.SEARCH) {
json.type = this.type;
}
if (this.method != "GET") {
@@ -643,7 +646,7 @@ class SearchEngine {
if (/^https?:/i.test(value)) {
this.__searchForm = value;
} else {
logConsole.debug(
lazy.logConsole.debug(
"_searchForm: Invalid URL dropped for",
this._name || "the current engine"
);
@@ -733,14 +736,14 @@ class SearchEngine {
* Height of the icon.
*/
_setIcon(iconURL, isPreferred, width, height) {
var uri = SearchUtils.makeURI(iconURL);
var uri = lazy.SearchUtils.makeURI(iconURL);
// Ignore bad URIs
if (!uri) {
return;
}
logConsole.debug(
lazy.logConsole.debug(
"_setIcon: Setting icon url for",
this.name,
"to",
@@ -772,16 +775,19 @@ class SearchEngine {
}
if (!byteArray) {
logConsole.warn("iconLoadCallback: load failed");
lazy.logConsole.warn("iconLoadCallback: load failed");
return;
}
if (byteArray.length > SearchUtils.MAX_ICON_SIZE) {
if (byteArray.length > lazy.SearchUtils.MAX_ICON_SIZE) {
try {
logConsole.debug("iconLoadCallback: rescaling icon");
lazy.logConsole.debug("iconLoadCallback: rescaling icon");
[byteArray, contentType] = rescaleIcon(byteArray, contentType);
} catch (ex) {
logConsole.error("Unable to set icon for the search engine:", ex);
lazy.logConsole.error(
"Unable to set icon for the search engine:",
ex
);
return;
}
}
@@ -792,20 +798,23 @@ class SearchEngine {
";base64," +
btoa(String.fromCharCode.apply(null, byteArray));
this._iconURI = SearchUtils.makeURI(dataURL);
this._iconURI = lazy.SearchUtils.makeURI(dataURL);
if (width && height) {
this._addIconToMap(width, height, dataURL);
}
if (this._engineAddedToStore) {
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.CHANGED);
lazy.SearchUtils.notifyAction(
this,
lazy.SearchUtils.MODIFIED_TYPE.CHANGED
);
}
this._hasPreferredIcon = isPreferred;
};
let chan = SearchUtils.makeChannel(uri);
let listener = new SearchUtils.LoadListener(
let chan = lazy.SearchUtils.makeChannel(uri);
let listener = new lazy.SearchUtils.LoadListener(
chan,
/^image\//,
// If we're currently acting as an "update engine", then the callback
@@ -903,7 +912,7 @@ class SearchEngine {
locale,
configuration = {}
) {
let { IconDetails } = ExtensionParent;
let { IconDetails } = lazy.ExtensionParent;
let searchProvider = manifest.chrome_settings_overrides.search_provider;
@@ -935,7 +944,7 @@ class SearchEngine {
this._telemetryId = configuration.telemetryId;
} else {
let telemetryId = extensionID.split("@")[0];
if (locale != SearchUtils.DEFAULT_TAG) {
if (locale != lazy.SearchUtils.DEFAULT_TAG) {
telemetryId += "-" + locale;
}
this._telemetryId = telemetryId;
@@ -995,7 +1004,7 @@ class SearchEngine {
configuration.params?.searchUrlPostParams ||
searchProvider.search_url_post_params ||
"";
let url = this._getEngineURLFromMetaData(SearchUtils.URL_TYPE.SEARCH, {
let url = this._getEngineURLFromMetaData(lazy.SearchUtils.URL_TYPE.SEARCH, {
method: (postParams && "POST") || "GET",
// AddonManager will sometimes encode the URL via `new URL()`. We want
// to ensure we're always dealing with decoded urls.
@@ -1015,16 +1024,19 @@ class SearchEngine {
configuration.params?.suggestUrlPostParams ||
searchProvider.suggest_url_post_params ||
"";
url = this._getEngineURLFromMetaData(SearchUtils.URL_TYPE.SUGGEST_JSON, {
method: (suggestPostParams && "POST") || "GET",
// suggest_url doesn't currently get encoded.
template: searchProvider.suggest_url,
getParams:
configuration.params?.suggestUrlGetParams ||
searchProvider.suggest_url_get_params ||
"",
postParams: suggestPostParams,
});
url = this._getEngineURLFromMetaData(
lazy.SearchUtils.URL_TYPE.SUGGEST_JSON,
{
method: (suggestPostParams && "POST") || "GET",
// suggest_url doesn't currently get encoded.
template: searchProvider.suggest_url,
getParams:
configuration.params?.suggestUrlGetParams ||
searchProvider.suggest_url_get_params ||
"",
postParams: suggestPostParams,
}
);
this._urls.push(url);
}
@@ -1036,16 +1048,19 @@ class SearchEngine {
}
checkSearchUrlMatchesManifest(searchProvider) {
let existingUrl = this._getURLOfType(SearchUtils.URL_TYPE.SEARCH);
let existingUrl = this._getURLOfType(lazy.SearchUtils.URL_TYPE.SEARCH);
let newUrl = this._getEngineURLFromMetaData(SearchUtils.URL_TYPE.SEARCH, {
method: (searchProvider.search_url_post_params && "POST") || "GET",
// AddonManager will sometimes encode the URL via `new URL()`. We want
// to ensure we're always dealing with decoded urls.
template: decodeURI(searchProvider.search_url),
getParams: searchProvider.search_url_get_params || "",
postParams: searchProvider.search_url_post_params || "",
});
let newUrl = this._getEngineURLFromMetaData(
lazy.SearchUtils.URL_TYPE.SEARCH,
{
method: (searchProvider.search_url_post_params && "POST") || "GET",
// AddonManager will sometimes encode the URL via `new URL()`. We want
// to ensure we're always dealing with decoded urls.
template: decodeURI(searchProvider.search_url),
getParams: searchProvider.search_url_get_params || "",
postParams: searchProvider.search_url_post_params || "",
}
);
let existingSubmission = existingUrl.getSubmission("", this);
let newSubmission = newUrl.getSubmission("", this);
@@ -1088,7 +1103,7 @@ class SearchEngine {
locale,
configuration
);
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.CHANGED);
lazy.SearchUtils.notifyAction(this, lazy.SearchUtils.MODIFIED_TYPE.CHANGED);
}
/**
@@ -1112,7 +1127,7 @@ class SearchEngine {
this._urls = [];
this.setAttr("overriddenBy", extensionID);
this._setUrls(manifest.chrome_settings_overrides.search_provider);
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.CHANGED);
lazy.SearchUtils.notifyAction(this, lazy.SearchUtils.MODIFIED_TYPE.CHANGED);
}
/**
@@ -1128,12 +1143,15 @@ class SearchEngine {
this.__searchForm = this._overriddenData.searchForm;
delete this._overriddenData;
} else {
logConsole.error(
lazy.logConsole.error(
`${this._name} had overriddenBy set, but no _overriddenData`
);
}
this.clearAttr("overriddenBy");
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.CHANGED);
lazy.SearchUtils.notifyAction(
this,
lazy.SearchUtils.MODIFIED_TYPE.CHANGED
);
}
}
@@ -1147,12 +1165,13 @@ class SearchEngine {
this._name = json._name;
this._description = json.description;
this._hasPreferredIcon = json._hasPreferredIcon == undefined;
this._queryCharset = json.queryCharset || SearchUtils.DEFAULT_QUERY_CHARSET;
this._queryCharset =
json.queryCharset || lazy.SearchUtils.DEFAULT_QUERY_CHARSET;
this.__searchForm = json.__searchForm;
this._updateInterval = json._updateInterval || null;
this._updateURL = json._updateURL || null;
this._iconUpdateURL = json._iconUpdateURL || null;
this._iconURI = SearchUtils.makeURI(json._iconURL);
this._iconURI = lazy.SearchUtils.makeURI(json._iconURL);
this._iconMapObj = json._iconMapObj;
this._metaData = json._metaData || {};
this._orderHint = json._orderHint || null;
@@ -1169,7 +1188,7 @@ class SearchEngine {
for (let i = 0; i < json._urls.length; ++i) {
let url = json._urls[i];
let engineURL = new EngineURL(
url.type || SearchUtils.URL_TYPE.SEARCH,
url.type || lazy.SearchUtils.URL_TYPE.SEARCH,
url.method || "GET",
url.template
);
@@ -1225,7 +1244,7 @@ class SearchEngine {
if (!this._hasPreferredIcon) {
json._hasPreferredIcon = this._hasPreferredIcon;
}
if (this.queryCharset != SearchUtils.DEFAULT_QUERY_CHARSET) {
if (this.queryCharset != lazy.SearchUtils.DEFAULT_QUERY_CHARSET) {
json.queryCharset = this.queryCharset;
}
@@ -1264,7 +1283,10 @@ class SearchEngine {
var value = val ? val.trim() : "";
if (value != this.alias) {
this.setAttr("alias", value);
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.CHANGED);
lazy.SearchUtils.notifyAction(
this,
lazy.SearchUtils.MODIFIED_TYPE.CHANGED
);
}
}
@@ -1322,7 +1344,10 @@ class SearchEngine {
var value = !!val;
if (value != this.hidden) {
this.setAttr("hidden", value);
SearchUtils.notifyAction(this, SearchUtils.MODIFIED_TYPE.CHANGED);
lazy.SearchUtils.notifyAction(
this,
lazy.SearchUtils.MODIFIED_TYPE.CHANGED
);
}
}
@@ -1358,7 +1383,7 @@ class SearchEngine {
get isGeneralPurposeEngine() {
return !!(
this._extensionID &&
SearchUtils.GENERAL_SEARCH_ENGINE_IDS.has(this._extensionID)
lazy.SearchUtils.GENERAL_SEARCH_ENGINE_IDS.has(this._extensionID)
);
}
@@ -1381,7 +1406,7 @@ class SearchEngine {
_getSearchFormWithPurpose(purpose) {
// First look for a <Url rel="searchform">
var searchFormURL = this._getURLOfType(
SearchUtils.URL_TYPE.SEARCH,
lazy.SearchUtils.URL_TYPE.SEARCH,
"searchform"
);
if (searchFormURL) {
@@ -1397,25 +1422,25 @@ class SearchEngine {
if (!this._searchForm) {
// No SearchForm specified in the engine definition file, use the prePath
// (e.g. https://foo.com for https://foo.com/search.php?q=bar).
var htmlUrl = this._getURLOfType(SearchUtils.URL_TYPE.SEARCH);
var htmlUrl = this._getURLOfType(lazy.SearchUtils.URL_TYPE.SEARCH);
if (!htmlUrl) {
throw Components.Exception(
"Engine has no HTML URL!",
Cr.NS_ERROR_UNEXPECTED
);
}
this._searchForm = SearchUtils.makeURI(htmlUrl.template).prePath;
this._searchForm = lazy.SearchUtils.makeURI(htmlUrl.template).prePath;
}
return ParamSubstitution(this._searchForm, "", this);
}
get queryCharset() {
return this._queryCharset || SearchUtils.DEFAULT_QUERY_CHARSET;
return this._queryCharset || lazy.SearchUtils.DEFAULT_QUERY_CHARSET;
}
get _defaultMobileResponseType() {
let type = SearchUtils.URL_TYPE.SEARCH;
let type = lazy.SearchUtils.URL_TYPE.SEARCH;
let isTablet = Services.sysinfo.get("tablet");
if (
@@ -1446,7 +1471,7 @@ class SearchEngine {
responseType =
AppConstants.platform == "android"
? this._defaultMobileResponseType
: SearchUtils.URL_TYPE.SEARCH;
: lazy.SearchUtils.URL_TYPE.SEARCH;
}
var url = this._getURLOfType(responseType);
@@ -1458,7 +1483,7 @@ class SearchEngine {
if (!data) {
// Return a dummy submission object with our searchForm attribute
return new Submission(
SearchUtils.makeURI(this._getSearchFormWithPurpose(purpose))
lazy.SearchUtils.makeURI(this._getSearchFormWithPurpose(purpose))
);
}
@@ -1469,9 +1494,11 @@ class SearchEngine {
data
);
} catch (ex) {
logConsole.warn("getSubmission: Falling back to default queryCharset!");
lazy.logConsole.warn(
"getSubmission: Falling back to default queryCharset!"
);
submissionData = Services.textToSubURI.ConvertAndEscape(
SearchUtils.DEFAULT_QUERY_CHARSET,
lazy.SearchUtils.DEFAULT_QUERY_CHARSET,
data
);
}
@@ -1485,7 +1512,7 @@ class SearchEngine {
let submission = this.getSubmission(
"{searchTerms}",
SearchUtils.URL_TYPE.SEARCH
lazy.SearchUtils.URL_TYPE.SEARCH
);
if (submission.postData) {
@@ -1510,7 +1537,7 @@ class SearchEngine {
}
let submission = this.getSubmission(
"{searchTerms}",
SearchUtils.URL_TYPE.SEARCH
lazy.SearchUtils.URL_TYPE.SEARCH
);
let searchURLPublicSuffix = Services.eTLD.getKnownPublicSuffix(
submission.uri
@@ -1529,7 +1556,7 @@ class SearchEngine {
responseType =
AppConstants.platform == "android"
? this._defaultMobileResponseType
: SearchUtils.URL_TYPE.SEARCH;
: lazy.SearchUtils.URL_TYPE.SEARCH;
}
let url = this._getURLOfType(responseType);
@@ -1547,7 +1574,7 @@ class SearchEngine {
let responseType =
AppConstants.platform == "android"
? this._defaultMobileResponseType
: SearchUtils.URL_TYPE.SEARCH;
: lazy.SearchUtils.URL_TYPE.SEARCH;
let url = this._getURLOfType(responseType);
if (!url || url.method != "GET") {
@@ -1676,10 +1703,10 @@ class SearchEngine {
Cu.reportError(e);
}
if (this.supportsResponseType(SearchUtils.URL_TYPE.SUGGEST_JSON)) {
if (this.supportsResponseType(lazy.SearchUtils.URL_TYPE.SUGGEST_JSON)) {
let suggestURI = this.getSubmission(
"dummy",
SearchUtils.URL_TYPE.SUGGEST_JSON
lazy.SearchUtils.URL_TYPE.SUGGEST_JSON
).uri;
if (suggestURI.prePath != searchURI.prePath) {
try {

View File

@@ -11,7 +11,9 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
RemoteSettings: "resource://services-settings/remote-settings.js",
SearchUtils: "resource://gre/modules/SearchUtils.jsm",
});
@@ -19,10 +21,10 @@ XPCOMUtils.defineLazyModuleGetters(this, {
const USER_LOCALE = "$USER_LOCALE";
const USER_REGION = "$USER_REGION";
XPCOMUtils.defineLazyGetter(this, "logConsole", () => {
XPCOMUtils.defineLazyGetter(lazy, "logConsole", () => {
return console.createInstance({
prefix: "SearchEngineSelector",
maxLogLevel: SearchUtils.loggingEnabled ? "Debug" : "Warn",
maxLogLevel: lazy.SearchUtils.loggingEnabled ? "Debug" : "Warn",
});
});
@@ -88,7 +90,7 @@ class SearchEngineSelector {
*/
constructor(listener) {
this.QueryInterface = ChromeUtils.generateQI(["nsIObserver"]);
this._remoteConfig = RemoteSettings(SearchUtils.SETTINGS_KEY);
this._remoteConfig = lazy.RemoteSettings(lazy.SearchUtils.SETTINGS_KEY);
this._listenerAdded = false;
this._onConfigurationUpdated = this._onConfigurationUpdated.bind(this);
this._changeListener = listener;
@@ -144,11 +146,11 @@ class SearchEngineSelector {
order: "id",
});
} catch (ex) {
logConsole.error(ex);
lazy.logConsole.error(ex);
failed = true;
}
if (!result.length) {
logConsole.error("Received empty search configuration!");
lazy.logConsole.error("Received empty search configuration!");
failed = true;
}
// If we failed, or the result is empty, try loading from the local dump.
@@ -166,7 +168,7 @@ class SearchEngineSelector {
*/
_onConfigurationUpdated({ data: { current } }) {
this._configuration = current;
logConsole.debug("Search configuration updated remotely");
lazy.logConsole.debug("Search configuration updated remotely");
if (this._changeListener) {
this._changeListener();
}
@@ -201,7 +203,7 @@ class SearchEngineSelector {
}
let name = getAppInfo("name");
let version = getAppInfo("version");
logConsole.debug(
lazy.logConsole.debug(
`fetchEngineConfiguration ${locale}:${region}:${channel}:${distroID}:${experiment}:${name}:${version}`
);
let engines = [];
@@ -282,7 +284,7 @@ class SearchEngineSelector {
} else {
const engine = { ...baseConfig };
(engine.webExtension = engine.webExtension || {}).locale =
SearchUtils.DEFAULT_TAG;
lazy.SearchUtils.DEFAULT_TAG;
engines.push(engine);
}
}
@@ -335,8 +337,8 @@ class SearchEngineSelector {
result.privateDefault = privateEngine;
}
if (SearchUtils.loggingEnabled) {
logConsole.debug(
if (lazy.SearchUtils.loggingEnabled) {
lazy.logConsole.debug(
"fetchEngineConfiguration: " +
result.engines.map(e => e.webExtension.id)
);

File diff suppressed because it is too large Load Diff

View File

@@ -9,15 +9,17 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
DeferredTask: "resource://gre/modules/DeferredTask.jsm",
SearchUtils: "resource://gre/modules/SearchUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logConsole", () => {
XPCOMUtils.defineLazyGetter(lazy, "logConsole", () => {
return console.createInstance({
prefix: "SearchSettings",
maxLogLevel: SearchUtils.loggingEnabled ? "Debug" : "Warn",
maxLogLevel: lazy.SearchUtils.loggingEnabled ? "Debug" : "Warn",
});
});
@@ -70,16 +72,16 @@ class SearchSettings {
_currentSettings = null;
addObservers() {
Services.obs.addObserver(this, SearchUtils.TOPIC_ENGINE_MODIFIED);
Services.obs.addObserver(this, SearchUtils.TOPIC_SEARCH_SERVICE);
Services.obs.addObserver(this, lazy.SearchUtils.TOPIC_ENGINE_MODIFIED);
Services.obs.addObserver(this, lazy.SearchUtils.TOPIC_SEARCH_SERVICE);
}
/**
* Cleans up, removing observers.
*/
removeObservers() {
Services.obs.removeObserver(this, SearchUtils.TOPIC_ENGINE_MODIFIED);
Services.obs.removeObserver(this, SearchUtils.TOPIC_SEARCH_SERVICE);
Services.obs.removeObserver(this, lazy.SearchUtils.TOPIC_ENGINE_MODIFIED);
Services.obs.removeObserver(this, lazy.SearchUtils.TOPIC_SEARCH_SERVICE);
}
/**
@@ -105,7 +107,7 @@ class SearchSettings {
throw new Error("no engine in the file");
}
} catch (ex) {
logConsole.warn("get: No settings file exists, new profile?", ex);
lazy.logConsole.warn("get: No settings file exists, new profile?", ex);
json = {};
}
if (json.metaData) {
@@ -114,7 +116,7 @@ class SearchSettings {
// Versions of gecko older than 82 stored the order flag as a preference.
// This was changed in version 6 of the settings file.
if (json.version < 6 || !("useSavedOrder" in this._metaData)) {
const prefName = SearchUtils.BROWSER_SEARCH_PREF + "useDBForOrder";
const prefName = lazy.SearchUtils.BROWSER_SEARCH_PREF + "useDBForOrder";
let useSavedOrder = Services.prefs.getBoolPref(prefName, false);
this.setAttribute("useSavedOrder", useSavedOrder);
@@ -145,10 +147,10 @@ class SearchSettings {
this._batchTask.arm();
return;
}
logConsole.debug("batchTask: Invalidating engine settings");
lazy.logConsole.debug("batchTask: Invalidating engine settings");
await this._write();
};
this._batchTask = new DeferredTask(
this._batchTask = new lazy.DeferredTask(
task,
SearchSettings.SETTINGS_INVALIDATION_DELAY
);
@@ -169,7 +171,7 @@ class SearchSettings {
if (!this._batchTask) {
return;
}
logConsole.debug("finalizing batch task");
lazy.logConsole.debug("finalizing batch task");
let task = this._batchTask;
this._batchTask = null;
// Tests manipulate the settings directly, so let's not double-write with
@@ -192,7 +194,7 @@ class SearchSettings {
let settings = {};
// Allows us to force a settings refresh should the settings format change.
settings.version = SearchUtils.SETTINGS_VERSION;
settings.version = lazy.SearchUtils.SETTINGS_VERSION;
settings.engines = [...this._searchService._engines.values()];
settings.metaData = this._metaData;
@@ -216,20 +218,20 @@ class SearchSettings {
throw new Error("cannot write without any engine.");
}
logConsole.debug("_write: Writing to settings file.");
lazy.logConsole.debug("_write: Writing to settings file.");
let path = PathUtils.join(PathUtils.profileDir, SETTINGS_FILENAME);
await IOUtils.writeJSON(path, settings, {
compress: true,
tmpPath: path + ".tmp",
});
logConsole.debug("_write: settings file written to disk.");
lazy.logConsole.debug("_write: settings file written to disk.");
Services.obs.notifyObservers(
null,
SearchUtils.TOPIC_SEARCH_SERVICE,
lazy.SearchUtils.TOPIC_SEARCH_SERVICE,
"write-settings-to-disk-complete"
);
} catch (ex) {
logConsole.error("_write: Could not write to settings file:", ex);
lazy.logConsole.error("_write: Could not write to settings file:", ex);
}
}
@@ -257,9 +259,9 @@ class SearchSettings {
*/
setVerifiedAttribute(name, val) {
this._metaData[name] = val;
this._metaData[this.getHashName(name)] = SearchUtils.getVerificationHash(
val
);
this._metaData[
this.getHashName(name)
] = lazy.SearchUtils.getVerificationHash(val);
this._delayedWrite();
}
@@ -289,9 +291,9 @@ class SearchSettings {
if (
val &&
this.getAttribute(this.getHashName(name)) !=
SearchUtils.getVerificationHash(val)
lazy.SearchUtils.getVerificationHash(val)
) {
logConsole.warn("getVerifiedGlobalAttr, invalid hash for", name);
lazy.logConsole.warn("getVerifiedGlobalAttr, invalid hash for", name);
return undefined;
}
return val;
@@ -342,16 +344,16 @@ class SearchSettings {
// nsIObserver
observe(engine, topic, verb) {
switch (topic) {
case SearchUtils.TOPIC_ENGINE_MODIFIED:
case lazy.SearchUtils.TOPIC_ENGINE_MODIFIED:
switch (verb) {
case SearchUtils.MODIFIED_TYPE.ADDED:
case SearchUtils.MODIFIED_TYPE.CHANGED:
case SearchUtils.MODIFIED_TYPE.REMOVED:
case lazy.SearchUtils.MODIFIED_TYPE.ADDED:
case lazy.SearchUtils.MODIFIED_TYPE.CHANGED:
case lazy.SearchUtils.MODIFIED_TYPE.REMOVED:
this._delayedWrite();
break;
}
break;
case SearchUtils.TOPIC_SEARCH_SERVICE:
case lazy.SearchUtils.TOPIC_SEARCH_SERVICE:
switch (verb) {
case "init-complete":
case "engines-reloaded":

View File

@@ -10,7 +10,8 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
SearchUtils: "resource://gre/modules/SearchUtils.jsm",
});
@@ -249,7 +250,7 @@ SearchSuggestionController.prototype = {
this.suggestionsEnabled &&
(!privateMode || this.suggestionsInPrivateBrowsingEnabled) &&
this.maxRemoteResults &&
engine.supportsResponseType(SearchUtils.URL_TYPE.SUGGEST_JSON)
engine.supportsResponseType(lazy.SearchUtils.URL_TYPE.SUGGEST_JSON)
) {
this._deferredRemoteResult = this._fetchRemote(
searchTerm,
@@ -442,11 +443,11 @@ SearchSuggestionController.prototype = {
* rejected if there is an error.
*/
_fetchRemote(searchTerm, engine, privateMode, userContextId) {
let deferredResponse = PromiseUtils.defer();
let deferredResponse = lazy.PromiseUtils.defer();
this._request = new XMLHttpRequest();
let submission = engine.getSubmission(
searchTerm,
SearchUtils.URL_TYPE.SUGGEST_JSON
lazy.SearchUtils.URL_TYPE.SUGGEST_JSON
);
let method = submission.postData ? "POST" : "GET";
this._request.open(method, submission.uri.spec, true);
@@ -776,7 +777,7 @@ SearchSuggestionController.prototype = {
* @returns {boolean} True if the engine offers suggestions and false otherwise.
*/
SearchSuggestionController.engineOffersSuggestions = function(engine) {
return engine.supportsResponseType(SearchUtils.URL_TYPE.SUGGEST_JSON);
return engine.supportsResponseType(lazy.SearchUtils.URL_TYPE.SUGGEST_JSON);
};
/**

View File

@@ -6,8 +6,9 @@ const { FormAutoCompleteResult } = ChromeUtils.import(
"resource://gre/modules/nsFormAutoCompleteResult.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const lazy = {};
ChromeUtils.defineModuleGetter(
this,
lazy,
"SearchSuggestionController",
"resource://gre/modules/SearchSuggestionController.jsm"
);
@@ -25,7 +26,7 @@ function SuggestAutoComplete() {
}
SuggestAutoComplete.prototype = {
_init() {
this._suggestionController = new SearchSuggestionController(obj =>
this._suggestionController = new lazy.SearchSuggestionController(obj =>
this.onResultsReturned(obj)
);
this._suggestionController.maxLocalResults = this._historyLimit;

View File

@@ -13,7 +13,9 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyGetter(this, "logConsole", () => {
const lazy = {};
XPCOMUtils.defineLazyGetter(lazy, "logConsole", () => {
return console.createInstance({
prefix: "SearchUtils",
maxLogLevel: SearchUtils.loggingEnabled ? "Debug" : "Warn",
@@ -60,14 +62,14 @@ class LoadListener {
// nsIRequestObserver
onStartRequest(request) {
logConsole.debug("loadListener: Starting request:", request.name);
lazy.logConsole.debug("loadListener: Starting request:", request.name);
this._stream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(
Ci.nsIBinaryInputStream
);
}
onStopRequest(request, statusCode) {
logConsole.debug("loadListener: Stopping request:", request.name);
lazy.logConsole.debug("loadListener: Stopping request:", request.name);
var requestFailed = !Components.isSuccessCode(statusCode);
if (!requestFailed && request instanceof Ci.nsIHttpChannel) {
@@ -75,11 +77,11 @@ class LoadListener {
}
if (requestFailed || this._countRead == 0) {
logConsole.warn("loadListener: request failed!");
lazy.logConsole.warn("loadListener: request failed!");
// send null so the callback can deal with the failure
this._bytes = null;
} else if (!this._expectedContentType.test(this._channel.contentType)) {
logConsole.warn(
lazy.logConsole.warn(
"loadListener: Content type does not match expected",
this._channel.contentType
);
@@ -215,7 +217,7 @@ var SearchUtils = {
*/
notifyAction(engine, verb) {
if (Services.search.isInitialized) {
logConsole.debug("NOTIFY: Engine:", engine.name, "Verb:", verb);
lazy.logConsole.debug("NOTIFY: Engine:", engine.name, "Verb:", verb);
Services.obs.notifyObservers(engine, this.TOPIC_ENGINE_MODIFIED, verb);
}
},

View File

@@ -9,7 +9,9 @@ const { MockRegistrar } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AddonManager: "resource://gre/modules/AddonManager.jsm",
AddonTestUtils: "resource://testing-common/AddonTestUtils.jsm",
ExtensionTestUtils: "resource://testing-common/ExtensionXPCShellUtils.jsm",
@@ -33,11 +35,11 @@ var SearchTestUtils = {
this._isMochitest = !env.exists("XPCSHELL_TEST_PROFILE_DIR");
if (this._isMochitest) {
this._isMochitest = true;
AddonTestUtils.initMochitest(testScope);
lazy.AddonTestUtils.initMochitest(testScope);
} else {
this._isMochitest = false;
// This handles xpcshell-tests.
gTestScope.ExtensionTestUtils = ExtensionTestUtils;
gTestScope.ExtensionTestUtils = lazy.ExtensionTestUtils;
this.initXPCShellAddonManager(testScope);
}
},
@@ -115,14 +117,14 @@ var SearchTestUtils = {
.QueryInterface(Ci.nsIResProtocolHandler);
resProt.setSubstitution("search-extensions", Services.io.newURI(url));
const settings = await RemoteSettings(SearchUtils.SETTINGS_KEY);
const settings = await lazy.RemoteSettings(lazy.SearchUtils.SETTINGS_KEY);
if (config) {
return sinon.stub(settings, "get").returns(config);
return lazy.sinon.stub(settings, "get").returns(config);
}
let response = await fetch(`resource://search-extensions/engines.json`);
let json = await response.json();
return sinon.stub(settings, "get").returns(json.data);
return lazy.sinon.stub(settings, "get").returns(json.data);
},
async useMochitestEngines(testDir) {
@@ -167,7 +169,8 @@ var SearchTestUtils = {
* How to sign created addons.
*/
initXPCShellAddonManager(scope, usePrivilegedSignatures = false) {
let scopes = AddonManager.SCOPE_PROFILE | AddonManager.SCOPE_APPLICATION;
let scopes =
lazy.AddonManager.SCOPE_PROFILE | lazy.AddonManager.SCOPE_APPLICATION;
Services.prefs.setIntPref("extensions.enabledScopes", scopes);
// Only do this once.
try {
@@ -178,8 +181,8 @@ var SearchTestUtils = {
throw ex;
}
}
AddonTestUtils.usePrivilegedSignatures = usePrivilegedSignatures;
AddonTestUtils.overrideCertDB();
lazy.AddonTestUtils.usePrivilegedSignatures = usePrivilegedSignatures;
lazy.AddonTestUtils.overrideCertDB();
},
/**
@@ -219,7 +222,7 @@ var SearchTestUtils = {
extension = gTestScope.ExtensionTestUtils.loadExtension(extensionInfo);
await extension.startup();
if (!options.skipWaitForSearchEngine) {
await AddonTestUtils.waitForSearchProviderStartup(extension);
await lazy.AddonTestUtils.waitForSearchProviderStartup(extension);
}
// For xpcshell-tests we must register the unload after adding the extension.
@@ -242,7 +245,7 @@ var SearchTestUtils = {
*/
async installSystemSearchExtension(options = {}) {
options.id = (options.id ?? "example") + "@search.mozilla.org";
let xpi = await AddonTestUtils.createTempWebExtensionFile({
let xpi = await lazy.AddonTestUtils.createTempWebExtensionFile({
manifest: this.createEngineManifest(options),
background() {
// eslint-disable-next-line no-undef
@@ -251,9 +254,12 @@ var SearchTestUtils = {
});
let wrapper = gTestScope.ExtensionTestUtils.expectExtension(options.id);
const install = await AddonManager.getInstallForURL(`file://${xpi.path}`, {
useSystemLocation: true,
});
const install = await lazy.AddonManager.getInstallForURL(
`file://${xpi.path}`,
{
useSystemLocation: true,
}
);
install.install();
@@ -409,13 +415,13 @@ var SearchTestUtils = {
*/
async updateRemoteSettingsConfig(config) {
if (!config) {
let settings = RemoteSettings(SearchUtils.SETTINGS_KEY);
let settings = lazy.RemoteSettings(lazy.SearchUtils.SETTINGS_KEY);
config = await settings.get();
}
const reloadObserved = SearchTestUtils.promiseSearchNotification(
"engines-reloaded"
);
await RemoteSettings(SearchUtils.SETTINGS_KEY).emit("sync", {
await lazy.RemoteSettings(lazy.SearchUtils.SETTINGS_KEY).emit("sync", {
data: { current: config },
});