Files
palemoon27/devtools/shared/DevToolsUtils.js
roytam1 b3d6afc844 import changes from `dev' branch of rmottola/Arctic-Fox:
- bits of Bug 571294 - Part 1: Implement selection events (8af4ef3f65)
- Bug 1208885 - Remove mozGenericWordUtils; r=smaug (b1a529f772)
- fix nsRefPtr/RefPtr (c56979e04d)
- Bug 1243657 spellchecker should check if IME composition works as deleting whole text r=ehsan (8b4d4825b9)
- Bug 1137544 - New scripts to upgrade en-US.dic to the latest upstream version; r=ehsan (47150b3549)
- Bug 1137544 - Upgrade en-US.dic dictionary to upstream version 2015.02.15; r=ehsan (057540f06b)
- Bug 1137544 - Generate 5-mozilla-added and 5-mozilla-removed to aid in submitting changes upstream; r=ehsan (f0d6332df3)
- Bug 1137544 - Update the en-US dictionary based on the SCOWL 2015.04.24 wordlist using the new scripts (e87b0a0285)
- minor test alignment (f3e976adf2)
- Bug 1162823 - Do not treat non-Latin words as misspelled; r=ekanan (c298db7251)
- Bug 1160730 - Add composited, compositing and compositeness to the en-US dictionary. r=ehsan (7d62babbdb)
- Bug 1167912 - Add eldritch to the en-US dictionary. r=ehsan (4d1e08e03b)
- Bug 1168802 - Update the en-US dictionary to SCOWL 2015.05.18 (3daa6d0831)
- Bug 1183765 - Add crappiness to our en-US dictionary. r=ehsan (54ccd28fa2)
- Bug 1192054 - Add subsumption to the en-US dictionary. r=ehsan (8c5aaa92bc)
- Bug 1199540 - Update the en-US dictionary to SCOWL 2015.08.24 (cb21d0092d)
- Bug 1200508 - Add dialogs to the en-US dictionary. r=ehsan (1e69b4d574)
- Bug 1202600 - Add Fukushima to the en-US dictionary. r=ehsan (6ffca1c47b)
- Bug 1213765 - Add preliminarily to the en-US dictionary. r=ehsan (cb12d4979b)
- Bug 1228174 - Add validator to the en-US dictionary. r=ehsan (b356d7f5cb)
- Bug 1199532 - Add disassembly, disassembler to the en-US dictionary. r=ehsan (979bb4f997)
- Bug 1235506 - Correct 353 entries in the en-US dictionary. r=ehsan (efb2f4a890)
- Bug 1238031 - Fix make-new-dict to use a custom en_US dictionary that adds common variants and accented words. r=ehsan (39464a234f)
- Bug 301712 - Remove uncommon proper names, remove unneeded words. r=ehsan (a6ece3925f)
- Bug 1240916 - Part 2: Update the en-US dictionary to SCOWL 2016.01.19 (bb059318e5)
- Bug 1250430 - Remove SrcDir loader support from devtools. r=jryans (0e77cbd85f)
- Bug 1209699 - Add a 'Push' button for service workers in about:debugging. r=jdescottes (a59c681ad1)
- Bug 1247203 - Remove useless call to main(). r=jryans (e89b21e72c)
- Bug 1247203 - Do not hardcode main module path in Loader.jsm. r=jryans (01d4ca73cc)
- Bug 1255266 - create sandbox with system principal. r=jryans,khuey. (0ac3a41816)
- Bug 1240804 - Use common instance of Promise.jsm for test harness promise rejection handling. r=ochameau (5f5383e721)
- Bug 1248603 - Factor out menu and shortcut creation to dedicated module. r=jryans (2e19c46dba)
- Bug 1248603 - Remove support of the appmenu from devtools. r=jryans (3f25c2b181)
- Bug 1248603 - Toggle developer toolbar via the menuitem in tests. r=jryans (01d9940116)
- bits of  Bug 1248603 - Toggle developer toolbar (e062489e6b)
- Bug 1248601 - Register the Developer Toolbar dynamically. r=jwalker (d5e63b9e4b)
- missing bit of 878412 - Use F12 to open the Toolbox (43c193a82a)
- Bug 1252479 - Adding the Developer Dynamically (Bug 1248601) doesn't work in SeaMonkey because it doesn't have a "browser-bottombox" r=ochameau (49fb6e1f17)
- Bug 1248601 - Fix focus race due to dynamic XUL insertion. r=jwalker (35831fd629)
- Bug 1257178 - Prevent "this._input is undefined" exception when developer toolbar is hidden early. r=jwalker (a8c308acd2)
- Bug 1250120 - Change name to Responsive Design Mode in Tools -> Web Developer menu r=jryans (3575acecb2)
- Bug 1239317 - Add a Service Workers entry to the Web Developer menu. r=jryans (ce975756b3)
- Bug 1219804 - Show last 5 recent bookmarks in the bookmarks menu. r=mak (cfad5e41b2)
- Bug 1259398 - Make devtools file-watcher module more generic to watch any directory. r=jlongster (4d37fbf76e)
- Bug 1236452 - Fix DOMHelpers.onceDOMReady against already loaded documents. r=jryans (7abfab41c0)
- Bug 1259241 - Update demangling library to 1.0.1 to fix a memory leak. r=fitzgen (77450e478c)
- Bug 1261092 - Simplify gcli initialization/destruction codepaths. r=jryans,jwalker (b8648df9f1)
- Bug 1258309 - Pull ViewHelpers.Prefs into its own module, r=jsantell (2fe2251e2a)
- Bug 1260711 - Fix error 'IndexSizeError: Index or size is negative or greater than the allowed amount' when using the animation inspector. r=pbro (4d2508de75)
- Bug 1235698 - Increase the timeout of browser_animation_timeline_shows_time_info.js (ae143a305e)
- Bug 1253493 - Part1: Show iterationStart to the tooltip. r=pbro (00d72ea7b0)
- Bug 1253493 - Part2: Show iterationStart to the GUI. r=pbro (1a5c1c4a93)
- Bug 1253494 part 1 - Implement endDelay representation in the animation inspector r=pbro (f5b08cd11d)
- Bug 1253494 part 2 - Add tests for endDelay representation r=pbro (d9acd667d8)
- Bug 1261561 - Part 1: Fix TimeScale.getAnimationDimensions() to handle multiple iterations. r=pbro (0a1e13cbc9)
- Bug 1261561 - Part 2: Add a xpcshell test for TimeScale.getAnimationDimensions(). r=pbro (71a832f3db)
- Bug 1168246 - part1: CSS autocomplete picks most popular prop;r=pbrosset (8c9989abd3)
- Bug 1168246 - part3: ES lint fixes for inplace-editor and autocomplete-popup;r=pbrosset (66d113f0e2)
- Bug 1151413 - Set async caller in DevToolsUtils.executeSoon r=ejpbruel (aa5ee4cbdb)
- Bug 1234600 - executeSoon async stacks only when DEBUG_JS_MODULES enabled. r=fitzgen (5e4f771a7a)
- Bug 1219028 - Remove use of non-standard Function.prototype.isGenerator from devtools/. r=fitzgen (34327590e6)
- Bug 1235458 - Move a bunch of utilities from DevToolsUtils to ThreadSafeDevToolsUtils. r=jsantell (333e190b17)
- Bug 1205095 - Unwrap getters in DevToolsUtils.hasSafeGetter. (r=fitzgen) (784e678e66)
- Bug 1260589 - Add the ThreadSafeDevToolsUtils.flatten utility; r=jimb a=kwierso (c82b27da22)
- Bug 1260938 - Add the ThreadSafeDevToolsUtils.isSet utility; r=jimb a=kwierso (9d5601a39e)
- Bug 1262225 - Add actorID to worker fake parent ThreadActor. r=ejpbruel (7e6f761dba)
- Bug 1239705 - Add a 'Start' button for service workers in about:debugging. r=ochameau (8bdea0c588)
- Bug 1196784 - imageset will use permissions.default.image. r=jdm (9a5669f71f)
- Bug 1182727 - Part 16: Fix a bug in build_tar_package (1d8f444eba)
- Bug 1182727 - Part 18: Fix building clang on OSX 10.8 and older (a02e1baca5)
- Bug 1182727 - Part 19: Fix another stupid mistake in build_tar_package() (87bb241693)
- Bug 1261264 - Apply GCC PR64905 to fix miscompilation with -fomit-frame-pointer. r=froydnj (d746a0c878)
- missing option, for safety (6fba93dff9)
- Bug 1260605 - Remove hack from bug 967556. r=nalexander (9513dbcd26)
- Bug 1239789 - Add secondary buffers to zxx_stream::StaticAllocator to handle reentrancy. r=glandium (74b60ffaad)
- Bug 1260351 - MozGlue: Build: Add mips support. r=glandium (8a463032f6)
- Bug 1249849: Ensure that we can always reach malloc_decl.h even when MOZ_REPLACE_ALLOC is not defined; r=glandium (1a8d0356ac)
- Bug 1248915 - TSan: data race on global 'mozilla::net::CacheObserver::sDiskCacheCapacity'. r=honzab.moz, n.nethercote. (86769cd893)
- Bug 1249157 - prefapi enums into class enums, explicit conversion, cleanup. r=bsmedberg (1843c09593)
- Bug 1251393: Remove a duplicated line. r=me (c2bca1a4f4)
2024-07-10 14:32:26 +08:00

665 lines
20 KiB
JavaScript

/* 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";
/* General utilities used throughout devtools. */
var { Ci, Cu, Cc, components } = require("chrome");
var Services = require("Services");
var promise = require("promise");
loader.lazyRequireGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm", true);
loader.lazyRequireGetter(this, "setTimeout", "Timer", true);
// Re-export the thread-safe utils.
const ThreadSafeDevToolsUtils = require("./ThreadSafeDevToolsUtils.js");
for (let key of Object.keys(ThreadSafeDevToolsUtils)) {
exports[key] = ThreadSafeDevToolsUtils[key];
}
/**
* Waits for the next tick in the event loop to execute a callback.
*/
exports.executeSoon = function executeSoon(aFn) {
if (isWorker) {
setImmediate(aFn);
} else {
let executor;
// Only enable async stack reporting when DEBUG_JS_MODULES is set
// (customized local builds) to avoid a performance penalty.
if (AppConstants.DEBUG_JS_MODULES || exports.testing) {
let stack = components.stack;
executor = () => {
Cu.callFunctionWithAsyncStack(aFn, stack, "DevToolsUtils.executeSoon");
};
} else {
executor = aFn;
}
Services.tm.mainThread.dispatch({
run: exports.makeInfallible(executor)
}, Ci.nsIThread.DISPATCH_NORMAL);
}
};
/**
* Waits for the next tick in the event loop.
*
* @return Promise
* A promise that is resolved after the next tick in the event loop.
*/
exports.waitForTick = function waitForTick() {
let deferred = promise.defer();
exports.executeSoon(deferred.resolve);
return deferred.promise;
};
/**
* Waits for the specified amount of time to pass.
*
* @param number aDelay
* The amount of time to wait, in milliseconds.
* @return Promise
* A promise that is resolved after the specified amount of time passes.
*/
exports.waitForTime = function waitForTime(aDelay) {
let deferred = promise.defer();
setTimeout(deferred.resolve, aDelay);
return deferred.promise;
};
/**
* Like Array.prototype.forEach, but doesn't cause jankiness when iterating over
* very large arrays by yielding to the browser and continuing execution on the
* next tick.
*
* @param Array aArray
* The array being iterated over.
* @param Function aFn
* The function called on each item in the array. If a promise is
* returned by this function, iterating over the array will be paused
* until the respective promise is resolved.
* @returns Promise
* A promise that is resolved once the whole array has been iterated
* over, and all promises returned by the aFn callback are resolved.
*/
exports.yieldingEach = function yieldingEach(aArray, aFn) {
const deferred = promise.defer();
let i = 0;
let len = aArray.length;
let outstanding = [deferred.promise];
(function loop() {
const start = Date.now();
while (i < len) {
// Don't block the main thread for longer than 16 ms at a time. To
// maintain 60fps, you have to render every frame in at least 16ms; we
// aren't including time spent in non-JS here, but this is Good
// Enough(tm).
if (Date.now() - start > 16) {
exports.executeSoon(loop);
return;
}
try {
outstanding.push(aFn(aArray[i], i++));
} catch (e) {
deferred.reject(e);
return;
}
}
deferred.resolve();
}());
return promise.all(outstanding);
};
/**
* Like XPCOMUtils.defineLazyGetter, but with a |this| sensitive getter that
* allows the lazy getter to be defined on a prototype and work correctly with
* instances.
*
* @param Object aObject
* The prototype object to define the lazy getter on.
* @param String aKey
* The key to define the lazy getter on.
* @param Function aCallback
* The callback that will be called to determine the value. Will be
* called with the |this| value of the current instance.
*/
exports.defineLazyPrototypeGetter =
function defineLazyPrototypeGetter(aObject, aKey, aCallback) {
Object.defineProperty(aObject, aKey, {
configurable: true,
get: function() {
const value = aCallback.call(this);
Object.defineProperty(this, aKey, {
configurable: true,
writable: true,
value: value
});
return value;
}
});
}
/**
* Safely get the property value from a Debugger.Object for a given key. Walks
* the prototype chain until the property is found.
*
* @param Debugger.Object aObject
* The Debugger.Object to get the value from.
* @param String aKey
* The key to look for.
* @return Any
*/
exports.getProperty = function getProperty(aObj, aKey) {
let root = aObj;
try {
do {
const desc = aObj.getOwnPropertyDescriptor(aKey);
if (desc) {
if ("value" in desc) {
return desc.value;
}
// Call the getter if it's safe.
return exports.hasSafeGetter(desc) ? desc.get.call(root).return : undefined;
}
aObj = aObj.proto;
} while (aObj);
} catch (e) {
// If anything goes wrong report the error and return undefined.
exports.reportException("getProperty", e);
}
return undefined;
};
/**
* Determines if a descriptor has a getter which doesn't call into JavaScript.
*
* @param Object aDesc
* The descriptor to check for a safe getter.
* @return Boolean
* Whether a safe getter was found.
*/
exports.hasSafeGetter = function hasSafeGetter(aDesc) {
// Scripted functions that are CCWs will not appear scripted until after
// unwrapping.
try {
let fn = aDesc.get.unwrap();
return fn && fn.callable && fn.class == "Function" && fn.script === undefined;
} catch(e) {
// Avoid exception 'Object in compartment marked as invisible to Debugger'
return false;
}
};
/**
* Check if it is safe to read properties and execute methods from the given JS
* object. Safety is defined as being protected from unintended code execution
* from content scripts (or cross-compartment code).
*
* See bugs 945920 and 946752 for discussion.
*
* @type Object aObj
* The object to check.
* @return Boolean
* True if it is safe to read properties from aObj, or false otherwise.
*/
exports.isSafeJSObject = function isSafeJSObject(aObj) {
// If we are running on a worker thread, Cu is not available. In this case,
// we always return false, just to be on the safe side.
if (isWorker) {
return false;
}
if (Cu.getGlobalForObject(aObj) ==
Cu.getGlobalForObject(exports.isSafeJSObject)) {
return true; // aObj is not a cross-compartment wrapper.
}
let principal = Cu.getObjectPrincipal(aObj);
if (Services.scriptSecurityManager.isSystemPrincipal(principal)) {
return true; // allow chrome objects
}
return Cu.isXrayWrapper(aObj);
};
exports.dumpn = function dumpn(str) {
if (exports.dumpn.wantLogging) {
dump("DBG-SERVER: " + str + "\n");
}
};
// We want wantLogging to be writable. The exports object is frozen by the
// loader, so define it on dumpn instead.
exports.dumpn.wantLogging = false;
/**
* A verbose logger for low-level tracing.
*/
exports.dumpv = function(msg) {
if (exports.dumpv.wantVerbose) {
exports.dumpn(msg);
}
};
// We want wantLogging to be writable. The exports object is frozen by the
// loader, so define it on dumpn instead.
exports.dumpv.wantVerbose = false;
/**
* Defines a getter on a specified object that will be created upon first use.
*
* @param aObject
* The object to define the lazy getter on.
* @param aName
* The name of the getter to define on aObject.
* @param aLambda
* A function that returns what the getter should return. This will
* only ever be called once.
*/
exports.defineLazyGetter = function defineLazyGetter(aObject, aName, aLambda) {
Object.defineProperty(aObject, aName, {
get: function () {
delete aObject[aName];
return aObject[aName] = aLambda.apply(aObject);
},
configurable: true,
enumerable: true
});
};
exports.defineLazyGetter(this, "AppConstants", () => {
if (isWorker) {
return {};
}
const scope = {};
Cu.import("resource://gre/modules/AppConstants.jsm", scope);
return scope.AppConstants;
});
/**
* No operation. The empty function.
*/
exports.noop = function () { };
let assertionFailureCount = 0;
Object.defineProperty(exports, "assertionFailureCount", {
get() {
return assertionFailureCount;
}
});
function reallyAssert(condition, message) {
if (!condition) {
assertionFailureCount++;
const err = new Error("Assertion failure: " + message);
exports.reportException("DevToolsUtils.assert", err);
throw err;
}
}
/**
* DevToolsUtils.assert(condition, message)
*
* @param Boolean condition
* @param String message
*
* Assertions are enabled when any of the following are true:
* - This is a DEBUG_JS_MODULES build
* - This is a DEBUG build
* - DevToolsUtils.testing is set to true
*
* If assertions are enabled, then `condition` is checked and if false-y, the
* assertion failure is logged and then an error is thrown.
*
* If assertions are not enabled, then this function is a no-op.
*/
Object.defineProperty(exports, "assert", {
get: () => (AppConstants.DEBUG || AppConstants.DEBUG_JS_MODULES || this.testing)
? reallyAssert
: exports.noop,
});
/**
* Defines a getter on a specified object for a module. The module will not
* be imported until first use.
*
* @param aObject
* The object to define the lazy getter on.
* @param aName
* The name of the getter to define on aObject for the module.
* @param aResource
* The URL used to obtain the module.
* @param aSymbol
* The name of the symbol exported by the module.
* This parameter is optional and defaults to aName.
*/
exports.defineLazyModuleGetter = function defineLazyModuleGetter(aObject, aName,
aResource,
aSymbol)
{
this.defineLazyGetter(aObject, aName, function XPCU_moduleLambda() {
var temp = {};
Cu.import(aResource, temp);
return temp[aSymbol || aName];
});
};
exports.defineLazyGetter(this, "NetUtil", () => {
return Cu.import("resource://gre/modules/NetUtil.jsm", {}).NetUtil;
});
exports.defineLazyGetter(this, "OS", () => {
return Cu.import("resource://gre/modules/osfile.jsm", {}).OS;
});
exports.defineLazyGetter(this, "TextDecoder", () => {
return Cu.import("resource://gre/modules/osfile.jsm", {}).TextDecoder;
});
exports.defineLazyGetter(this, "NetworkHelper", () => {
return require("devtools/shared/webconsole/network-helper");
});
/**
* Performs a request to load the desired URL and returns a promise.
*
* @param aURL String
* The URL we will request.
* @param aOptions Object
* An object with the following optional properties:
* - loadFromCache: if false, will bypass the cache and
* always load fresh from the network (default: true)
* - policy: the nsIContentPolicy type to apply when fetching the URL
* - window: the window to get the loadGroup from
* - charset: the charset to use if the channel doesn't provide one
* @returns Promise that resolves with an object with the following members on
* success:
* - content: the document at that URL, as a string,
* - contentType: the content type of the document
*
* If an error occurs, the promise is rejected with that error.
*
* XXX: It may be better to use nsITraceableChannel to get to the sources
* without relying on caching when we can (not for eval, etc.):
* http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/
*/
function mainThreadFetch(aURL, aOptions={ loadFromCache: true,
policy: Ci.nsIContentPolicy.TYPE_OTHER,
window: null,
charset: null }) {
// Create a channel.
let url = aURL.split(" -> ").pop();
let channel;
try {
channel = newChannelForURL(url, aOptions);
} catch (ex) {
return promise.reject(ex);
}
// Set the channel options.
channel.loadFlags = aOptions.loadFromCache
? channel.LOAD_FROM_CACHE
: channel.LOAD_BYPASS_CACHE;
if (aOptions.window) {
// Respect private browsing.
channel.loadGroup = aOptions.window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocumentLoader)
.loadGroup;
}
let deferred = promise.defer();
let onResponse = (stream, status, request) => {
if (!components.isSuccessCode(status)) {
deferred.reject(new Error(`Failed to fetch ${url}. Code ${status}.`));
return;
}
try {
// We cannot use NetUtil to do the charset conversion as if charset
// information is not available and our default guess is wrong the method
// might fail and we lose the stream data. This means we can't fall back
// to using the locale default encoding (bug 1181345).
// Read and decode the data according to the locale default encoding.
let available = stream.available();
let source = NetUtil.readInputStreamToString(stream, available);
stream.close();
// If the channel or the caller has correct charset information, the
// content will be decoded correctly. If we have to fall back to UTF-8 and
// the guess is wrong, the conversion fails and convertToUnicode returns
// the input unmodified. Essentially we try to decode the data as UTF-8
// and if that fails, we use the locale specific default encoding. This is
// the best we can do if the source does not provide charset info.
let charset = channel.contentCharset || aOptions.charset || "UTF-8";
let unicodeSource = NetworkHelper.convertToUnicode(source, charset);
deferred.resolve({
content: unicodeSource,
contentType: request.contentType
});
} catch (ex) {
let uri = request.originalURI;
if (ex.name === "NS_BASE_STREAM_CLOSED" && uri instanceof Ci.nsIFileURL) {
// Empty files cause NS_BASE_STREAM_CLOSED exception. Use OS.File to
// differentiate between empty files and other errors (bug 1170864).
// This can be removed when bug 982654 is fixed.
uri.QueryInterface(Ci.nsIFileURL);
let result = OS.File.read(uri.file.path).then(bytes => {
// Convert the bytearray to a String.
let decoder = new TextDecoder();
let content = decoder.decode(bytes);
// We can't detect the contentType without opening a channel
// and that failed already. This is the best we can do here.
return {
content,
contentType: "text/plain"
};
});
deferred.resolve(result);
} else {
deferred.reject(ex);
}
}
};
// Open the channel
try {
NetUtil.asyncFetch(channel, onResponse);
} catch (ex) {
return promise.reject(ex);
}
return deferred.promise;
}
/**
* Opens a channel for given URL. Tries a bit harder than NetUtil.newChannel.
*
* @param {String} url - The URL to open a channel for.
* @param {Object} options - The options object passed to @method fetch.
* @return {nsIChannel} - The newly created channel. Throws on failure.
*/
function newChannelForURL(url, { policy, window }) {
var securityFlags = Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL;
if (window) {
// Respect private browsing.
var req = window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocumentLoader)
.loadGroup;
if (req) {
var nc = req.notificationCallbacks;
if (nc) {
try {
var lc = nc.getInterface(Ci.nsILoadContext);
if (lc) {
if (lc.usePrivateBrowsing) {
securityFlags |= Ci.nsILoadInfo.SEC_FORCE_PRIVATE_BROWSING;
}
}
} catch(ex) {}
}
}
}
let channelOptions = {
contentPolicyType: policy,
loadUsingSystemPrincipal: true,
securityFlags: securityFlags,
uri: url
};
try {
return NetUtil.newChannel(channelOptions);
} catch (e) {
// In the xpcshell tests, the script url is the absolute path of the test
// file, which will make a malformed URI error be thrown. Add the file
// scheme to see if it helps.
channelOptions.uri = "file://" + url;
return NetUtil.newChannel(channelOptions);
}
}
// Fetch is defined differently depending on whether we are on the main thread
// or a worker thread.
if (!this.isWorker) {
exports.fetch = mainThreadFetch;
} else {
// Services is not available in worker threads, nor is there any other way
// to fetch a URL. We need to enlist the help from the main thread here, by
// issuing an rpc request, to fetch the URL on our behalf.
exports.fetch = function (url, options) {
return rpc("fetch", url, options);
};
}
/**
* Returns a promise that is resolved or rejected when all promises have settled
* (resolved or rejected).
*
* This differs from Promise.all, which will reject immediately after the first
* rejection, instead of waiting for the remaining promises to settle.
*
* @param values
* Iterable of promises that may be pending, resolved, or rejected. When
* when all promises have settled (resolved or rejected), the returned
* promise will be resolved or rejected as well.
*
* @return A new promise that is fulfilled when all values have settled
* (resolved or rejected). Its resolution value will be an array of all
* resolved values in the given order, or undefined if values is an
* empty array. The reject reason will be forwarded from the first
* promise in the list of given promises to be rejected.
*/
exports.settleAll = values => {
if (values === null || typeof(values[Symbol.iterator]) != "function") {
throw new Error("settleAll() expects an iterable.");
}
let deferred = promise.defer();
values = Array.isArray(values) ? values : [...values];
let countdown = values.length;
let resolutionValues = new Array(countdown);
let rejectionValue;
let rejectionOccurred = false;
if (!countdown) {
deferred.resolve(resolutionValues);
return deferred.promise;
}
function checkForCompletion() {
if (--countdown > 0) {
return;
}
if (!rejectionOccurred) {
deferred.resolve(resolutionValues);
} else {
deferred.reject(rejectionValue);
}
}
for (let i = 0; i < values.length; i++) {
let index = i;
let value = values[i];
let resolver = result => {
resolutionValues[index] = result;
checkForCompletion();
};
let rejecter = error => {
if (!rejectionOccurred) {
rejectionValue = error;
rejectionOccurred = true;
}
checkForCompletion();
};
if (value && typeof(value.then) == "function") {
value.then(resolver, rejecter);
} else {
// Given value is not a promise, forward it as a resolution value.
resolver(value);
}
}
return deferred.promise;
};
/**
* When the testing flag is set, various behaviors may be altered from
* production mode, typically to enable easier testing or enhanced debugging.
*/
var testing = false;
Object.defineProperty(exports, "testing", {
get: function() {
return testing;
},
set: function(state) {
testing = state;
}
});
/**
* Open the file at the given path for reading.
*
* @param {String} filePath
*
* @returns Promise<nsIInputStream>
*/
exports.openFileStream = function (filePath) {
return new Promise((resolve, reject) => {
const uri = NetUtil.newURI(new FileUtils.File(filePath));
NetUtil.asyncFetch(
{ uri, loadUsingSystemPrincipal: true },
(stream, result) => {
if (!components.isSuccessCode(result)) {
reject(new Error(`Could not open "${filePath}": result = ${result}`));
return;
}
resolve(stream);
}
);
});
};