# lib/webdriver/promise.js

    1// Copyright 2011 Software Freedom Conservancy. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415/**16 * @license Portions of this code are from the Dojo toolkit, received under the17 * BSD License:18 * Redistribution and use in source and binary forms, with or without19 * modification, are permitted provided that the following conditions are met:20 *21 *   * Redistributions of source code must retain the above copyright notice,22 *     this list of conditions and the following disclaimer.23 *   * Redistributions in binary form must reproduce the above copyright notice,24 *     this list of conditions and the following disclaimer in the documentation25 *     and/or other materials provided with the distribution.26 *   * Neither the name of the Dojo Foundation nor the names of its contributors27 *     may be used to endorse or promote products derived from this software28 *     without specific prior written permission.29 *30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"31 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE33 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE34 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE40 * POSSIBILITY OF SUCH DAMAGE.41 */4243/**44 * @fileoverview A promise implementation based on the CommonJS promise/A and45 * promise/B proposals. For more information, see46 * http://wiki.commonjs.org/wiki/Promises.47 */4849goog.provide('webdriver.promise');50goog.provide('webdriver.promise.ControlFlow');51goog.provide('webdriver.promise.ControlFlow.Timer');52goog.provide('webdriver.promise.Deferred');53goog.provide('webdriver.promise.Promise');54goog.provide('webdriver.promise.Thenable');5556goog.require('goog.array');57goog.require('goog.debug.Error');58goog.require('goog.object');59goog.require('webdriver.EventEmitter');60goog.require('webdriver.stacktrace.Snapshot');61626364/**65 * Thenable is a promise-like object with a {@code then} method which may be66 * used to schedule callbacks on a promised value.67 *68 * @interface69 * @template T70 */71webdriver.promise.Thenable = function() {};727374/**75 * Cancels the computation of this promise's value, rejecting the promise in the76 * process. This method is a no-op if the promise has alreayd been resolved.77 *78 * @param {*=} opt_reason The reason this promise is being cancelled. If not an79 *     {@code Error}, one will be created using the value's string80 *     representation.81 */82webdriver.promise.Thenable.prototype.cancel = function(opt_reason) {};838485/** @return {boolean} Whether this promise's value is still being computed. */86webdriver.promise.Thenable.prototype.isPending = function() {};878889/**90 * Registers listeners for when this instance is resolved.91 *92 * @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback The93 *     function to call if this promise is successfully resolved. The function94 *     should expect a single argument: the promise's resolved value.95 * @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback The96 *     function to call if this promise is rejected. The function should expect97 *     a single argument: the rejection reason.98 * @return {!webdriver.promise.Promise.<R>} A new promise which will be99 *     resolved with the result of the invoked callback.100 * @template R101 */102webdriver.promise.Thenable.prototype.then = function(103    opt_callback, opt_errback) {};104105106/**107 * Registers a listener for when this promise is rejected. This is synonymous108 * with the {@code catch} clause in a synchronous API:109 * <pre><code>110 *   // Synchronous API:111 *   try {112 *     doSynchronousWork();113 *   } catch (ex) {114 *     console.error(ex);115 *   }116 *117 *   // Asynchronous promise API:118 *   doAsynchronousWork().thenCatch(function(ex) {119 *     console.error(ex);120 *   });121 * </code></pre>122 *123 * @param {function(*): (R|webdriver.promise.Promise.<R>)} errback The function124 *     to call if this promise is rejected. The function should expect a single125 *     argument: the rejection reason.126 * @return {!webdriver.promise.Promise.<R>} A new promise which will be127 *     resolved with the result of the invoked callback.128 * @template R129 */130webdriver.promise.Thenable.prototype.thenCatch = function(errback) {};131132133/**134 * Registers a listener to invoke when this promise is resolved, regardless135 * of whether the promise's value was successfully computed. This function136 * is synonymous with the {@code finally} clause in a synchronous API:137 * <pre><code>138 *   // Synchronous API:139 *   try {140 *     doSynchronousWork();141 *   } finally {142 *     cleanUp();143 *   }144 *145 *   // Asynchronous promise API:146 *   doAsynchronousWork().thenFinally(cleanUp);147 * </code></pre>148 *149 * <b>Note:</b> similar to the {@code finally} clause, if the registered150 * callback returns a rejected promise or throws an error, it will silently151 * replace the rejection error (if any) from this promise:152 * <pre><code>153 *   try {154 *     throw Error('one');155 *   } finally {156 *     throw Error('two');  // Hides Error: one157 *   }158 *159 *   webdriver.promise.rejected(Error('one'))160 *       .thenFinally(function() {161 *         throw Error('two');  // Hides Error: one162 *       });163 * </code></pre>164 *165 *166 * @param {function(): (R|webdriver.promise.Promise.<R>)} callback The function167 *     to call when this promise is resolved.168 * @return {!webdriver.promise.Promise.<R>} A promise that will be fulfilled169 *     with the callback result.170 * @template R171 */172webdriver.promise.Thenable.prototype.thenFinally = function(callback) {};173174175/**176 * Property used to flag constructor's as implementing the Thenable interface177 * for runtime type checking.178 * @private {string}179 * @const180 */181webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_ = '$webdriver_Thenable';182183184/**185 * Adds a property to a class prototype to allow runtime checks of whether186 * instances of that class implement the Thenable interface. This function will187 * also ensure the prototype's {@code then} function is exported from compiled188 * code.189 * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The190 *     constructor whose prototype to modify.191 */192webdriver.promise.Thenable.addImplementation = function(ctor) {193  // Based on goog.promise.Thenable.isImplementation.194  ctor.prototype['then'] = ctor.prototype.then;195  try {196    // Old IE7 does not support defineProperty; IE8 only supports it for197    // DOM elements.198    Object.defineProperty(199        ctor.prototype,200        webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_,201        {'value': true, 'enumerable': false});202  } catch (ex) {203    ctor.prototype[webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_] = true;204  }205};206207208/**209 * Checks if an object has been tagged for implementing the Thenable interface210 * as defined by {@link webdriver.promise.Thenable.addImplementation}.211 * @param {*} object The object to test.212 * @return {boolean} Whether the object is an implementation of the Thenable213 *     interface.214 */215webdriver.promise.Thenable.isImplementation = function(object) {216  // Based on goog.promise.Thenable.isImplementation.217  if (!object) {218    return false;219  }220  try {221    return !!object[webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_];222  } catch (e) {223    return false;  // Property access seems to be forbidden.224  }225};226227228229/**230 * Represents the eventual value of a completed operation. Each promise may be231 * in one of three states: pending, resolved, or rejected. Each promise starts232 * in the pending state and may make a single transition to either a233 * fulfilled or rejected state, at which point the promise is considered234 * resolved.235 *236 * @constructor237 * @implements {webdriver.promise.Thenable.<T>}238 * @template T239 * @see http://promises-aplus.github.io/promises-spec/240 */241webdriver.promise.Promise = function() {};242webdriver.promise.Thenable.addImplementation(webdriver.promise.Promise);243244245/** @override */246webdriver.promise.Promise.prototype.cancel = function(reason) {247  throw new TypeError('Unimplemented function: "cancel"');248};249250251/** @override */252webdriver.promise.Promise.prototype.isPending = function() {253  throw new TypeError('Unimplemented function: "isPending"');254};255256257/** @override */258webdriver.promise.Promise.prototype.then = function(259    opt_callback, opt_errback) {260  throw new TypeError('Unimplemented function: "then"');261};262263264/** @override */265webdriver.promise.Promise.prototype.thenCatch = function(errback) {266  return this.then(null, errback);267};268269270/** @override */271webdriver.promise.Promise.prototype.thenFinally = function(callback) {272  return this.then(callback, function(err) {273    var value = callback();274    if (webdriver.promise.isPromise(value)) {275      return value.then(function() {276        throw err;277      });278    }279    throw err;280  });281};282283284285/**286 * Represents a value that will be resolved at some point in the future. This287 * class represents the protected "producer" half of a Promise - each Deferred288 * has a {@code promise} property that may be returned to consumers for289 * registering callbacks, reserving the ability to resolve the deferred to the290 * producer.291 *292 * <p>If this Deferred is rejected and there are no listeners registered before293 * the next turn of the event loop, the rejection will be passed to the294 * {@link webdriver.promise.ControlFlow} as an unhandled failure.295 *296 * <p>If this Deferred is cancelled, the cancellation reason will be forward to297 * the Deferred's canceller function (if provided). The canceller may return a298 * truth-y value to override the reason provided for rejection.299 *300 * @param {Function=} opt_canceller Function to call when cancelling the301 *     computation of this instance's value.302 * @param {webdriver.promise.ControlFlow=} opt_flow The control flow303 *     this instance was created under. This should only be provided during304 *     unit tests.305 * @constructor306 * @extends {webdriver.promise.Promise.<T>}307 * @template T308 */309webdriver.promise.Deferred = function(opt_canceller, opt_flow) {310  /* NOTE: This class's implementation diverges from the prototypical style311   * used in the rest of the atoms library. This was done intentionally to312   * protect the internal Deferred state from consumers, as outlined by313   *     http://wiki.commonjs.org/wiki/Promises314   */315  goog.base(this);316317  var flow = opt_flow || webdriver.promise.controlFlow();318319  /**320   * The listeners registered with this Deferred. Each element in the list will321   * be a 3-tuple of the callback function, errback function, and the322   * corresponding deferred object.323   * @type {!Array.<!webdriver.promise.Deferred.Listener_>}324   */325  var listeners = [];326327  /**328   * Whether this Deferred's resolution was ever handled by a listener.329   * If the Deferred is rejected and its value is not handled by a listener330   * before the next turn of the event loop, the error will be passed to the331   * global error handler.332   * @type {boolean}333   */334  var handled = false;335336  /**337   * Key for the timeout used to delay reproting an unhandled rejection to the338   * parent {@link webdriver.promise.ControlFlow}.339   * @type {?number}340   */341  var pendingRejectionKey = null;342343  /**344   * This Deferred's current state.345   * @type {!webdriver.promise.Deferred.State_}346   */347  var state = webdriver.promise.Deferred.State_.PENDING;348349  /**350   * This Deferred's resolved value; set when the state transitions from351   * {@code webdriver.promise.Deferred.State_.PENDING}.352   * @type {*}353   */354  var value;355356  /** @return {boolean} Whether this promise's value is still pending. */357  function isPending() {358    return state == webdriver.promise.Deferred.State_.PENDING;359  }360361  /**362   * Removes all of the listeners previously registered on this deferred.363   * @throws {Error} If this deferred has already been resolved.364   */365  function removeAll() {366    listeners = [];367  }368369  /**370   * Resolves this deferred. If the new value is a promise, this function will371   * wait for it to be resolved before notifying the registered listeners.372   * @param {!webdriver.promise.Deferred.State_} newState The deferred's new373   *     state.374   * @param {*} newValue The deferred's new value.375   */376  function resolve(newState, newValue) {377    if (webdriver.promise.Deferred.State_.PENDING !== state) {378      return;379    }380381    if (newValue === self) {382      // See promise a+, 2.3.1383      // http://promises-aplus.github.io/promises-spec/#point-48384      throw TypeError('A promise may not resolve to itself');385    }386387    state = webdriver.promise.Deferred.State_.BLOCKED;388389    if (webdriver.promise.isPromise(newValue)) {390      var onFulfill = goog.partial(notifyAll, newState);391      var onReject = goog.partial(392          notifyAll, webdriver.promise.Deferred.State_.REJECTED);393      if (newValue instanceof webdriver.promise.Deferred) {394        newValue.then(onFulfill, onReject);395      } else {396        webdriver.promise.asap(newValue, onFulfill, onReject);397      }398399    } else {400      notifyAll(newState, newValue);401    }402  }403404  /**405   * Notifies all of the listeners registered with this Deferred that its state406   * has changed.407   * @param {!webdriver.promise.Deferred.State_} newState The deferred's new408   *     state.409   * @param {*} newValue The deferred's new value.410   */411  function notifyAll(newState, newValue) {412    if (newState === webdriver.promise.Deferred.State_.REJECTED &&413        // We cannot check instanceof Error since the object may have been414        // created in a different JS context.415        goog.isObject(newValue) && goog.isString(newValue.message)) {416      newValue = flow.annotateError(/** @type {!Error} */(newValue));417    }418419    state = newState;420    value = newValue;421    while (listeners.length) {422      notify(listeners.shift());423    }424425    if (!handled && state == webdriver.promise.Deferred.State_.REJECTED) {426      flow.pendingRejections_ += 1;427      pendingRejectionKey = flow.timer.setTimeout(function() {428        pendingRejectionKey = null;429        flow.pendingRejections_ -= 1;430        flow.abortFrame_(value);431      }, 0);432    }433  }434435  /**436   * Notifies a single listener of this Deferred's change in state.437   * @param {!webdriver.promise.Deferred.Listener_} listener The listener to438   *     notify.439   */440  function notify(listener) {441    var func = state == webdriver.promise.Deferred.State_.RESOLVED ?442        listener.callback : listener.errback;443    if (func) {444      flow.runInNewFrame_(goog.partial(func, value),445          listener.fulfill, listener.reject);446    } else if (state == webdriver.promise.Deferred.State_.REJECTED) {447      listener.reject(value);448    } else {449      listener.fulfill(value);450    }451  }452453  /**454   * The consumer promise for this instance. Provides protected access to the455   * callback registering functions.456   * @type {!webdriver.promise.Promise.<T>}457   */458  var promise = new webdriver.promise.Promise();459460  /**461   * Registers a callback on this Deferred.462   *463   * @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback .464   * @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback .465   * @return {!webdriver.promise.Promise.<R>} A new promise representing the466   *     result of the callback.467   * @template R468   * @see webdriver.promise.Promise#then469   */470  function then(opt_callback, opt_errback) {471    // Avoid unnecessary allocations if we weren't given any callback functions.472    if (!opt_callback && !opt_errback) {473      return promise;474    }475476    // The moment a listener is registered, we consider this deferred to be477    // handled; the callback must handle any rejection errors.478    handled = true;479    if (pendingRejectionKey !== null) {480      flow.pendingRejections_ -= 1;481      flow.timer.clearTimeout(pendingRejectionKey);482      pendingRejectionKey = null;483    }484485    var deferred = new webdriver.promise.Deferred(cancel, flow);486    var listener = {487      callback: opt_callback,488      errback: opt_errback,489      fulfill: deferred.fulfill,490      reject: deferred.reject491    };492493    if (state == webdriver.promise.Deferred.State_.PENDING ||494        state == webdriver.promise.Deferred.State_.BLOCKED) {495      listeners.push(listener);496    } else {497      notify(listener);498    }499500    return deferred.promise;501  }502503  var self = this;504505  /**506   * Resolves this promise with the given value. If the value is itself a507   * promise and not a reference to this deferred, this instance will wait for508   * it before resolving.509   * @param {T=} opt_value The fulfilled value.510   */511  function fulfill(opt_value) {512    resolve(webdriver.promise.Deferred.State_.RESOLVED, opt_value);513  }514515  /**516   * Rejects this promise. If the error is itself a promise, this instance will517   * be chained to it and be rejected with the error's resolved value.518   * @param {*=} opt_error The rejection reason, typically either a519   *     {@code Error} or a {@code string}.520   */521  function reject(opt_error) {522    resolve(webdriver.promise.Deferred.State_.REJECTED, opt_error);523  }524525  /**526   * Attempts to cancel the computation of this instance's value. This attempt527   * will silently fail if this instance has already resolved.528   * @param {*=} opt_reason The reason for cancelling this promise.529   */530  function cancel(opt_reason) {531    if (!isPending()) {532      return;533    }534535    if (opt_canceller) {536      opt_reason = opt_canceller(opt_reason) || opt_reason;537    }538539    reject(opt_reason);540  }541542  this.promise = promise;543  this.promise.then = this.then = then;544  this.promise.cancel = this.cancel = cancel;545  this.promise.isPending = this.isPending = isPending;546  this.fulfill = fulfill;547  this.reject = this.errback = reject;548549  // Only expose this function to our internal classes.550  // TODO: find a cleaner way of handling this.551  if (this instanceof webdriver.promise.Task_) {552    this.removeAll = removeAll;553  }554555  // Export symbols necessary for the contract on this object to work in556  // compiled mode.557  goog.exportProperty(this, 'then', this.then);558  goog.exportProperty(this, 'cancel', cancel);559  goog.exportProperty(this, 'fulfill', fulfill);560  goog.exportProperty(this, 'reject', reject);561  goog.exportProperty(this, 'isPending', isPending);562  goog.exportProperty(this, 'promise', this.promise);563  goog.exportProperty(this.promise, 'then', this.then);564  goog.exportProperty(this.promise, 'cancel', cancel);565  goog.exportProperty(this.promise, 'isPending', isPending);566};567goog.inherits(webdriver.promise.Deferred, webdriver.promise.Promise);568569570/**571 * Type definition for a listener registered on a Deferred object.572 * @typedef {{callback:(Function|undefined),573 *            errback:(Function|undefined),574 *            fulfill: function(*), reject: function(*)}}575 * @private576 */577webdriver.promise.Deferred.Listener_;578579580/**581 * The three states a {@link webdriver.promise.Deferred} object may be in.582 * @enum {number}583 * @private584 */585webdriver.promise.Deferred.State_ = {586  REJECTED: -1,587  PENDING: 0,588  BLOCKED: 1,589  RESOLVED: 2590};591592593/**594 * Tests if a value is an Error-like object. This is more than an straight595 * instanceof check since the value may originate from another context.596 * @param {*} value The value to test.597 * @return {boolean} Whether the value is an error.598 * @private599 */600webdriver.promise.isError_ = function(value) {601  return value instanceof Error ||602      goog.isObject(value) &&603      (Object.prototype.toString.call(value) === '[object Error]' ||604       // A special test for goog.testing.JsUnitException.605       value.isJsUnitException);606607};608609610/**611 * Determines whether a {@code value} should be treated as a promise.612 * Any object whose "then" property is a function will be considered a promise.613 *614 * @param {*} value The value to test.615 * @return {boolean} Whether the value is a promise.616 */617webdriver.promise.isPromise = function(value) {618  return !!value && goog.isObject(value) &&619      // Use array notation so the Closure compiler does not obfuscate away our620      // contract.621      goog.isFunction(value['then']);622};623624625/**626 * Creates a promise that will be resolved at a set time in the future.627 * @param {number} ms The amount of time, in milliseconds, to wait before628 *     resolving the promise.629 * @return {!webdriver.promise.Promise} The promise.630 */631webdriver.promise.delayed = function(ms) {632  var timer = webdriver.promise.controlFlow().timer;633  var key;634  var deferred = new webdriver.promise.Deferred(function() {635    timer.clearTimeout(key);636  });637  key = timer.setTimeout(deferred.fulfill, ms);638  return deferred.promise;639};640641642/**643 * Creates a new deferred object.644 * @param {Function=} opt_canceller Function to call when cancelling the645 *     computation of this instance's value.646 * @return {!webdriver.promise.Deferred.<T>} The new deferred object.647 * @template T648 */649webdriver.promise.defer = function(opt_canceller) {650  return new webdriver.promise.Deferred(opt_canceller);651};652653654/**655 * Creates a promise that has been resolved with the given value.656 * @param {T=} opt_value The resolved value.657 * @return {!webdriver.promise.Promise.<T>} The resolved promise.658 * @template T659 */660webdriver.promise.fulfilled = function(opt_value) {661  if (opt_value instanceof webdriver.promise.Promise) {662    return opt_value;663  }664  var deferred = new webdriver.promise.Deferred();665  deferred.fulfill(opt_value);666  return deferred.promise;667};668669670/**671 * Creates a promise that has been rejected with the given reason.672 * @param {*=} opt_reason The rejection reason; may be any value, but is673 *     usually an Error or a string.674 * @return {!webdriver.promise.Promise.<T>} The rejected promise.675 * @template T676 */677webdriver.promise.rejected = function(opt_reason) {678  var deferred = new webdriver.promise.Deferred();679  deferred.reject(opt_reason);680  return deferred.promise;681};682683684/**685 * Wraps a function that is assumed to be a node-style callback as its final686 * argument. This callback takes two arguments: an error value (which will be687 * null if the call succeeded), and the success value as the second argument.688 * If the call fails, the returned promise will be rejected, otherwise it will689 * be resolved with the result.690 * @param {!Function} fn The function to wrap.691 * @param {...?} var_args The arguments to apply to the function, excluding the692 *     final callback.693 * @return {!webdriver.promise.Promise} A promise that will be resolved with the694 *     result of the provided function's callback.695 */696webdriver.promise.checkedNodeCall = function(fn, var_args) {697  var deferred = new webdriver.promise.Deferred(function() {698    throw Error('This Deferred may not be cancelled');699  });700  try {701    var args = goog.array.slice(arguments, 1);702    args.push(function(error, value) {703      error ? deferred.reject(error) : deferred.fulfill(value);704    });705    fn.apply(null, args);706  } catch (ex) {707    deferred.reject(ex);708  }709  return deferred.promise;710};711712713/**714 * Registers an observer on a promised {@code value}, returning a new promise715 * that will be resolved when the value is. If {@code value} is not a promise,716 * then the return promise will be immediately resolved.717 * @param {*} value The value to observe.718 * @param {Function=} opt_callback The function to call when the value is719 *     resolved successfully.720 * @param {Function=} opt_errback The function to call when the value is721 *     rejected.722 * @return {!webdriver.promise.Promise} A new promise.723 */724webdriver.promise.when = function(value, opt_callback, opt_errback) {725  if (webdriver.promise.Thenable.isImplementation(value)) {726    return value.then(opt_callback, opt_errback);727  }728729  var deferred = new webdriver.promise.Deferred();730731  webdriver.promise.asap(value, deferred.fulfill, deferred.reject);732733  return deferred.then(opt_callback, opt_errback);734};735736737/**738 * Invokes the appropriate callback function as soon as a promised739 * {@code value} is resolved. This function is similar to740 * {@link webdriver.promise.when}, except it does not return a new promise.741 * @param {*} value The value to observe.742 * @param {Function} callback The function to call when the value is743 *     resolved successfully.744 * @param {Function=} opt_errback The function to call when the value is745 *     rejected.746 */747webdriver.promise.asap = function(value, callback, opt_errback) {748  if (webdriver.promise.isPromise(value)) {749    value.then(callback, opt_errback);750751  // Maybe a Dojo-like deferred object?752  } else if (!!value && goog.isObject(value) &&753      goog.isFunction(value.addCallbacks)) {754    value.addCallbacks(callback, opt_errback);755756  // A raw value, return a resolved promise.757  } else if (callback) {758    callback(value);759  }760};761762763/**764 * Given an array of promises, will return a promise that will be fulfilled765 * with the fulfillment values of the input array's values. If any of the766 * input array's promises are rejected, the returned promise will be rejected767 * with the same reason.768 *769 * @param {!Array.<(T|!webdriver.promise.Promise.<T>)>} arr An array of770 *     promises to wait on.771 * @return {!webdriver.promise.Promise.<!Array.<T>>} A promise that is772 *     fulfilled with an array containing the fulfilled values of the773 *     input array, or rejected with the same reason as the first774 *     rejected value.775 * @template T776 */777webdriver.promise.all = function(arr) {778  var n = arr.length;779  if (!n) {780    return webdriver.promise.fulfilled([]);781  }782783  var toFulfill = n;784  var result = webdriver.promise.defer();785  var values = [];786787  var onFulfill = function(index, value) {788    values[index] = value;789    toFulfill--;790    if (toFulfill == 0) {791      result.fulfill(values);792    }793  };794795  for (var i = 0; i < n; ++i) {796    webdriver.promise.asap(797        arr[i], goog.partial(onFulfill, i), result.reject);798  }799800  return result.promise;801};802803804/**805 * Calls a function for each element in an array and inserts the result into a806 * new array, which is used as the fulfillment value of the promise returned807 * by this function.808 *809 * <p>If the return value of the mapping function is a promise, this function810 * will wait for it to be fulfilled before inserting it into the new array.811 *812 * <p>If the mapping function throws or returns a rejected promise, the813 * promise returned by this function will be rejected with the same reason.814 * Only the first failure will be reported; all subsequent errors will be815 * silently ignored.816 *817 * @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The818 *     array to iterator over, or a promise that will resolve to said array.819 * @param {function(this: SELF, TYPE, number, !Array.<TYPE>): ?} fn The820 *     function to call for each element in the array. This function should821 *     expect three arguments (the element, the index, and the array itself.822 * @param {SELF=} opt_self The object to be used as the value of 'this' within823 *     {@code fn}.824 * @template TYPE, SELF825 */826webdriver.promise.map = function(arr, fn, opt_self) {827  return webdriver.promise.when(arr, function(arr) {828    var result = goog.array.map(arr, fn, opt_self);829    return webdriver.promise.all(result);830  });831};832833834/**835 * Calls a function for each element in an array, and if the function returns836 * true adds the element to a new array.837 *838 * <p>If the return value of the filter function is a promise, this function839 * will wait for it to be fulfilled before determining whether to insert the840 * element into the new array.841 *842 * <p>If the filter function throws or returns a rejected promise, the promise843 * returned by this function will be rejected with the same reason. Only the844 * first failure will be reported; all subsequent errors will be silently845 * ignored.846 *847 * @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The848 *     array to iterator over, or a promise that will resolve to said array.849 * @param {function(this: SELF, TYPE, number, !Array.<TYPE>): (850 *             boolean|webdriver.promise.Promise.<boolean>)} fn The function851 *     to call for each element in the array.852 * @param {SELF=} opt_self The object to be used as the value of 'this' within853 *     {@code fn}.854 * @template TYPE, SELF855 */856webdriver.promise.filter = function(arr, fn, opt_self) {857  return webdriver.promise.when(arr, function(arr) {858    var originalValues = goog.array.clone(arr);859    return webdriver.promise.map(arr, fn, opt_self).then(function(include) {860      return goog.array.filter(originalValues, function(value, index) {861        return include[index];862      });863    });864  });865};866867868/**869 * Returns a promise that will be resolved with the input value in a870 * fully-resolved state. If the value is an array, each element will be fully871 * resolved. Likewise, if the value is an object, all keys will be fully872 * resolved. In both cases, all nested arrays and objects will also be873 * fully resolved.  All fields are resolved in place; the returned promise will874 * resolve on {@code value} and not a copy.875 *876 * Warning: This function makes no checks against objects that contain877 * cyclical references:878 * <pre><code>879 *   var value = {};880 *   value['self'] = value;881 *   webdriver.promise.fullyResolved(value);  // Stack overflow.882 * </code></pre>883 *884 * @param {*} value The value to fully resolve.885 * @return {!webdriver.promise.Promise} A promise for a fully resolved version886 *     of the input value.887 */888webdriver.promise.fullyResolved = function(value) {889  if (webdriver.promise.isPromise(value)) {890    return webdriver.promise.when(value, webdriver.promise.fullyResolveValue_);891  }892  return webdriver.promise.fullyResolveValue_(value);893};894895896/**897 * @param {*} value The value to fully resolve. If a promise, assumed to898 *     already be resolved.899 * @return {!webdriver.promise.Promise} A promise for a fully resolved version900 *     of the input value.901 * @private902 */903webdriver.promise.fullyResolveValue_ = function(value) {904  switch (goog.typeOf(value)) {905    case 'array':906      return webdriver.promise.fullyResolveKeys_(907          /** @type {!Array} */ (value));908909    case 'object':910      if (webdriver.promise.isPromise(value)) {911        // We get here when the original input value is a promise that912        // resolves to itself. When the user provides us with such a promise,913        // trust that it counts as a "fully resolved" value and return it.914        // Of course, since it's already a promise, we can just return it915        // to the user instead of wrapping it in another promise.916        return /** @type {!webdriver.promise.Promise} */ (value);917      }918919      if (goog.isNumber(value.nodeType) &&920          goog.isObject(value.ownerDocument) &&921          goog.isNumber(value.ownerDocument.nodeType)) {922        // DOM node; return early to avoid infinite recursion. Should we923        // only support objects with a certain level of nesting?924        return webdriver.promise.fulfilled(value);925      }926927      return webdriver.promise.fullyResolveKeys_(928          /** @type {!Object} */ (value));929930    default:  // boolean, function, null, number, string, undefined931      return webdriver.promise.fulfilled(value);932  }933};934935936/**937 * @param {!(Array|Object)} obj the object to resolve.938 * @return {!webdriver.promise.Promise} A promise that will be resolved with the939 *     input object once all of its values have been fully resolved.940 * @private941 */942webdriver.promise.fullyResolveKeys_ = function(obj) {943  var isArray = goog.isArray(obj);944  var numKeys = isArray ? obj.length : goog.object.getCount(obj);945  if (!numKeys) {946    return webdriver.promise.fulfilled(obj);947  }948949  var numResolved = 0;950  var deferred = new webdriver.promise.Deferred();951952  // In pre-IE9, goog.array.forEach will not iterate properly over arrays953  // containing undefined values because "index in array" returns false954  // when array[index] === undefined (even for x = [undefined, 1]). To get955  // around this, we need to use our own forEach implementation.956  // DO NOT REMOVE THIS UNTIL WE NO LONGER SUPPORT IE8. This cannot be957  // reproduced in IE9 by changing the browser/document modes, it requires an958  // actual pre-IE9 browser.  Yay, IE!959  var forEachKey = !isArray ? goog.object.forEach : function(arr, fn) {960    var n = arr.length;961    for (var i = 0; i < n; ++i) {962      fn.call(null, arr[i], i, arr);963    }964  };965966  forEachKey(obj, function(partialValue, key) {967    var type = goog.typeOf(partialValue);968    if (type != 'array' && type != 'object') {969      maybeResolveValue();970      return;971    }972973    webdriver.promise.fullyResolved(partialValue).then(974        function(resolvedValue) {975          obj[key] = resolvedValue;976          maybeResolveValue();977        },978        deferred.reject);979  });980981  return deferred.promise;982983  function maybeResolveValue() {984    if (++numResolved == numKeys) {985      deferred.fulfill(obj);986    }987  }988};989990991//////////////////////////////////////////////////////////////////////////////992//993//  webdriver.promise.ControlFlow994//995//////////////////////////////////////////////////////////////////////////////996997998999/**1000 * Handles the execution of scheduled tasks, each of which may be an1001 * asynchronous operation. The control flow will ensure tasks are executed in1002 * the ordered scheduled, starting each task only once those before it have1003 * completed.1004 *1005 * <p>Each task scheduled within this flow may return a1006 * {@link webdriver.promise.Promise} to indicate it is an asynchronous1007 * operation. The ControlFlow will wait for such promises to be resolved before1008 * marking the task as completed.1009 *1010 * <p>Tasks and each callback registered on a {@link webdriver.promise.Deferred}1011 * will be run in their own ControlFlow frame.  Any tasks scheduled within a1012 * frame will have priority over previously scheduled tasks. Furthermore, if1013 * any of the tasks in the frame fails, the remainder of the tasks in that frame1014 * will be discarded and the failure will be propagated to the user through the1015 * callback/task's promised result.1016 *1017 * <p>Each time a ControlFlow empties its task queue, it will fire an1018 * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely,1019 * whenever the flow terminates due to an unhandled error, it will remove all1020 * remaining tasks in its queue and fire an1021 * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If1022 * there are no listeners registered with the flow, the error will be1023 * rethrown to the global error handler.1024 *1025 * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object1026 *     to use. Should only be set for testing.1027 * @constructor1028 * @extends {webdriver.EventEmitter}1029 */1030webdriver.promise.ControlFlow = function(opt_timer) {1031  webdriver.EventEmitter.call(this);10321033  /**1034   * The timer used by this instance.1035   * @type {webdriver.promise.ControlFlow.Timer}1036   */1037  this.timer = opt_timer || webdriver.promise.ControlFlow.defaultTimer;10381039  /**1040   * A list of recent tasks. Each time a new task is started, or a frame is1041   * completed, the previously recorded task is removed from this list. If1042   * there are multiple tasks, task N+1 is considered a sub-task of task1043   * N.1044   * @private {!Array.<!webdriver.promise.Task_>}1045   */1046  this.history_ = [];1047};1048goog.inherits(webdriver.promise.ControlFlow, webdriver.EventEmitter);104910501051/**1052 * @typedef {{clearInterval: function(number),1053 *            clearTimeout: function(number),1054 *            setInterval: function(!Function, number): number,1055 *            setTimeout: function(!Function, number): number}}1056 */1057webdriver.promise.ControlFlow.Timer;105810591060/**1061 * The default timer object, which uses the global timer functions.1062 * @type {webdriver.promise.ControlFlow.Timer}1063 */1064webdriver.promise.ControlFlow.defaultTimer = (function() {1065  // The default timer functions may be defined as free variables for the1066  // current context, so do not reference them using "window" or1067  // "goog.global".  Also, we must invoke them in a closure, and not using1068  // bind(), so we do not get "TypeError: Illegal invocation" (WebKit) or1069  // "Invalid calling object" (IE) errors.1070  return {1071    clearInterval: wrap(clearInterval),1072    clearTimeout: wrap(clearTimeout),1073    setInterval: wrap(setInterval),1074    setTimeout: wrap(setTimeout)1075  };10761077  function wrap(fn) {1078    return function() {1079      // Cannot use .call() or .apply() since we do not know which variable1080      // the function is bound to, and using the wrong one will generate1081      // an error.1082      return fn(arguments[0], arguments[1]);1083    };1084  }1085})();108610871088/**1089 * Events that may be emitted by an {@link webdriver.promise.ControlFlow}.1090 * @enum {string}1091 */1092webdriver.promise.ControlFlow.EventType = {10931094  /** Emitted when all tasks have been successfully executed. */1095  IDLE: 'idle',10961097  /** Emitted when a ControlFlow has been reset. */1098  RESET: 'reset',10991100  /** Emitted whenever a new task has been scheduled. */1101  SCHEDULE_TASK: 'scheduleTask',11021103  /**1104   * Emitted whenever a control flow aborts due to an unhandled promise1105   * rejection. This event will be emitted along with the offending rejection1106   * reason. Upon emitting this event, the control flow will empty its task1107   * queue and revert to its initial state.1108   */1109  UNCAUGHT_EXCEPTION: 'uncaughtException'1110};111111121113/**1114 * How often, in milliseconds, the event loop should run.1115 * @type {number}1116 * @const1117 */1118webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY = 10;111911201121/**1122 * Tracks the active execution frame for this instance. Lazily initialized1123 * when the first task is scheduled.1124 * @private {webdriver.promise.Frame_}1125 */1126webdriver.promise.ControlFlow.prototype.activeFrame_ = null;112711281129/**1130 * A reference to the frame in which new tasks should be scheduled. If1131 * {@code null}, tasks will be scheduled within the active frame. When forcing1132 * a function to run in the context of a new frame, this pointer is used to1133 * ensure tasks are scheduled within the newly created frame, even though it1134 * won't be active yet.1135 * @private {webdriver.promise.Frame_}1136 * @see {#runInNewFrame_}1137 */1138webdriver.promise.ControlFlow.prototype.schedulingFrame_ = null;113911401141/**1142 * Timeout ID set when the flow is about to shutdown without any errors1143 * being detected. Upon shutting down, the flow will emit an1144 * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Idle events1145 * always follow a brief timeout in order to catch latent errors from the last1146 * completed task. If this task had a callback registered, but no errback, and1147 * the task fails, the unhandled failure would not be reported by the promise1148 * system until the next turn of the event loop:1149 *1150 *   // Schedule 1 task that fails.1151 *   var result = webriver.promise.controlFlow().schedule('example',1152 *       function() { return webdriver.promise.rejected('failed'); });1153 *   // Set a callback on the result. This delays reporting the unhandled1154 *   // failure for 1 turn of the event loop.1155 *   result.then(goog.nullFunction);1156 *1157 * @private {?number}1158 */1159webdriver.promise.ControlFlow.prototype.shutdownId_ = null;116011611162/**1163 * Interval ID for this instance's event loop.1164 * @private {?number}1165 */1166webdriver.promise.ControlFlow.prototype.eventLoopId_ = null;116711681169/**1170 * The number of "pending" promise rejections.1171 *1172 * <p>Each time a promise is rejected and is not handled by a listener, it will1173 * schedule a 0-based timeout to check if it is still unrejected in the next1174 * turn of the JS-event loop. This allows listeners to attach to, and handle,1175 * the rejected promise at any point in same turn of the event loop that the1176 * promise was rejected.1177 *1178 * <p>When this flow's own event loop triggers, it will not run if there1179 * are any outstanding promise rejections. This allows unhandled promises to1180 * be reported before a new task is started, ensuring the error is reported to1181 * the current task queue.1182 *1183 * @private {number}1184 */1185webdriver.promise.ControlFlow.prototype.pendingRejections_ = 0;118611871188/**1189 * The number of aborted frames since the last time a task was executed or a1190 * frame completed successfully.1191 * @private {number}1192 */1193webdriver.promise.ControlFlow.prototype.numAbortedFrames_ = 0;119411951196/**1197 * Resets this instance, clearing its queue and removing all event listeners.1198 */1199webdriver.promise.ControlFlow.prototype.reset = function() {1200  this.activeFrame_ = null;1201  this.clearHistory();1202  this.emit(webdriver.promise.ControlFlow.EventType.RESET);1203  this.removeAllListeners();1204  this.cancelShutdown_();1205  this.cancelEventLoop_();1206};120712081209/**1210 * Returns a summary of the recent task activity for this instance. This1211 * includes the most recently completed task, as well as any parent tasks. In1212 * the returned summary, the task at index N is considered a sub-task of the1213 * task at index N+1.1214 * @return {!Array.<string>} A summary of this instance's recent task1215 *     activity.1216 */1217webdriver.promise.ControlFlow.prototype.getHistory = function() {1218  var pendingTasks = [];1219  var currentFrame = this.activeFrame_;1220  while (currentFrame) {1221    var task = currentFrame.getPendingTask();1222    if (task) {1223      pendingTasks.push(task);1224    }1225    // A frame's parent node will always be another frame.1226    currentFrame =1227        /** @type {webdriver.promise.Frame_} */ (currentFrame.getParent());1228  }12291230  var fullHistory = goog.array.concat(this.history_, pendingTasks);1231  return goog.array.map(fullHistory, function(task) {1232    return task.toString();1233  });1234};123512361237/** Clears this instance's task history. */1238webdriver.promise.ControlFlow.prototype.clearHistory = function() {1239  this.history_ = [];1240};124112421243/**1244 * Removes a completed task from this instance's history record. If any1245 * tasks remain from aborted frames, those will be removed as well.1246 * @private1247 */1248webdriver.promise.ControlFlow.prototype.trimHistory_ = function() {1249  if (this.numAbortedFrames_) {1250    goog.array.splice(this.history_,1251        this.history_.length - this.numAbortedFrames_,1252        this.numAbortedFrames_);1253    this.numAbortedFrames_ = 0;1254  }1255  this.history_.pop();1256};125712581259/**1260 * Property used to track whether an error has been annotated by1261 * {@link webdriver.promise.ControlFlow#annotateError}.1262 * @private {string}1263 * @const1264 */1265webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_ =1266    'webdriver_promise_error_';126712681269/**1270 * Appends a summary of this instance's recent task history to the given1271 * error's stack trace. This function will also ensure the error's stack trace1272 * is in canonical form.1273 * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate.1274 * @return {!(Error|goog.testing.JsUnitException)} The annotated error.1275 */1276webdriver.promise.ControlFlow.prototype.annotateError = function(e) {1277  if (!!e[webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_]) {1278    return e;1279  }12801281  var history = this.getHistory();1282  if (history.length) {1283    e = webdriver.stacktrace.format(e);12841285    /** @type {!Error} */(e).stack += [1286      '\n==== async task ====\n',1287      history.join('\n==== async task ====\n')1288    ].join('');12891290    e[webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_] = true;1291  }12921293  return e;1294};129512961297/**1298 * @return {string} The scheduled tasks still pending with this instance.1299 */1300webdriver.promise.ControlFlow.prototype.getSchedule = function() {1301  return this.activeFrame_ ? this.activeFrame_.getRoot().toString() : '[]';1302};130313041305/**1306 * Schedules a task for execution. If there is nothing currently in the1307 * queue, the task will be executed in the next turn of the event loop. If1308 * the task function is a generator, the task will be executed using1309 * {@link webdriver.promise.consume}.1310 *1311 * @param {function(): (T|webdriver.promise.Promise.<T>)} fn The function to1312 *     call to start the task. If the function returns a1313 *     {@link webdriver.promise.Promise}, this instance will wait for it to be1314 *     resolved before starting the next task.1315 * @param {string=} opt_description A description of the task.1316 * @return {!webdriver.promise.Promise.<T>} A promise that will be resolved1317 *     with the result of the action.1318 * @template T1319 */1320webdriver.promise.ControlFlow.prototype.execute = function(1321    fn, opt_description) {1322  if (webdriver.promise.isGenerator(fn)) {1323    fn = goog.partial(webdriver.promise.consume, fn);1324  }13251326  this.cancelShutdown_();13271328  if (!this.activeFrame_) {1329    this.activeFrame_ = new webdriver.promise.Frame_(this);1330  }13311332  // Trim an extra frame off the generated stack trace for the call to this1333  // function.1334  var snapshot = new webdriver.stacktrace.Snapshot(1);1335  var task = new webdriver.promise.Task_(1336      this, fn, opt_description || '', snapshot);1337  var scheduleIn = this.schedulingFrame_ || this.activeFrame_;1338  scheduleIn.addChild(task);13391340  this.emit(webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK, opt_description);13411342  this.scheduleEventLoopStart_();1343  return task.promise;1344};134513461347/**1348 * Inserts a {@code setTimeout} into the command queue. This is equivalent to1349 * a thread sleep in a synchronous programming language.1350 *1351 * @param {number} ms The timeout delay, in milliseconds.1352 * @param {string=} opt_description A description to accompany the timeout.1353 * @return {!webdriver.promise.Promise} A promise that will be resolved with1354 *     the result of the action.1355 */1356webdriver.promise.ControlFlow.prototype.timeout = function(1357    ms, opt_description) {1358  return this.execute(function() {1359    return webdriver.promise.delayed(ms);1360  }, opt_description);1361};136213631364/**1365 * Schedules a task that shall wait for a condition to hold. Each condition1366 * function may return any value, but it will always be evaluated as a boolean.1367 *1368 * <p>Condition functions may schedule sub-tasks with this instance, however,1369 * their execution time will be factored into whether a wait has timed out.1370 *1371 * <p>In the event a condition returns a Promise, the polling loop will wait for1372 * it to be resolved before evaluating whether the condition has been satisfied.1373 * The resolution time for a promise is factored into whether a wait has timed1374 * out.1375 *1376 * <p>If the condition function throws, or returns a rejected promise, the1377 * wait task will fail.1378 *1379 * @param {!Function} condition The condition function to poll.1380 * @param {number} timeout How long to wait, in milliseconds, for the condition1381 *     to hold before timing out.1382 * @param {string=} opt_message An optional error message to include if the1383 *     wait times out; defaults to the empty string.1384 * @return {!webdriver.promise.Promise} A promise that will be resolved when the1385 *     condition has been satisified. The promise shall be rejected if the wait1386 *     times out waiting for the condition.1387 */1388webdriver.promise.ControlFlow.prototype.wait = function(1389    condition, timeout, opt_message) {1390  var sleep = Math.min(timeout, 100);1391  var self = this;13921393  if (webdriver.promise.isGenerator(condition)) {1394    condition = goog.partial(webdriver.promise.consume, condition);1395  }13961397  return this.execute(function() {1398    var startTime = goog.now();1399    var waitResult = new webdriver.promise.Deferred();1400    var waitFrame = self.activeFrame_;1401    waitFrame.isWaiting = true;1402    pollCondition();1403    return waitResult.promise;14041405    function pollCondition() {1406      self.runInNewFrame_(condition, function(value) {1407        var elapsed = goog.now() - startTime;1408        if (!!value) {1409          waitFrame.isWaiting = false;1410          waitResult.fulfill(value);1411        } else if (elapsed >= timeout) {1412          waitResult.reject(new Error((opt_message ? opt_message + '\n' : '') +1413              'Wait timed out after ' + elapsed + 'ms'));1414        } else {1415          self.timer.setTimeout(pollCondition, sleep);1416        }1417      }, waitResult.reject, true);1418    }1419  }, opt_message);1420};142114221423/**1424 * Schedules a task that will wait for another promise to resolve.  The resolved1425 * promise's value will be returned as the task result.1426 * @param {!webdriver.promise.Promise} promise The promise to wait on.1427 * @return {!webdriver.promise.Promise} A promise that will resolve when the1428 *     task has completed.1429 */1430webdriver.promise.ControlFlow.prototype.await = function(promise) {1431  return this.execute(function() {1432    return promise;1433  });1434};143514361437/**1438 * Schedules the interval for this instance's event loop, if necessary.1439 * @private1440 */1441webdriver.promise.ControlFlow.prototype.scheduleEventLoopStart_ = function() {1442  if (!this.eventLoopId_) {1443    this.eventLoopId_ = this.timer.setInterval(1444        goog.bind(this.runEventLoop_, this),1445        webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY);1446  }1447};144814491450/**1451 * Cancels the event loop, if necessary.1452 * @private1453 */1454webdriver.promise.ControlFlow.prototype.cancelEventLoop_ = function() {1455  if (this.eventLoopId_) {1456    this.timer.clearInterval(this.eventLoopId_);1457    this.eventLoopId_ = null;1458  }1459};146014611462/**1463 * Executes the next task for the current frame. If the current frame has no1464 * more tasks, the frame's result will be resolved, returning control to the1465 * frame's creator. This will terminate the flow if the completed frame was at1466 * the top of the stack.1467 * @private1468 */1469webdriver.promise.ControlFlow.prototype.runEventLoop_ = function() {1470  // If we get here and there are pending promise rejections, then those1471  // promises are queued up to run as soon as this (JS) event loop terminates.1472  // Short-circuit our loop to give those promises a chance to run. Otherwise,1473  // we might start a new task only to have it fail because of one of these1474  // pending rejections.1475  if (this.pendingRejections_) {1476    return;1477  }14781479  // If the flow aborts due to an unhandled exception after we've scheduled1480  // another turn of the execution loop, we can end up in here with no tasks1481  // left. This is OK, just quietly return.1482  if (!this.activeFrame_) {1483    this.commenceShutdown_();1484    return;1485  }14861487  var task;1488  if (this.activeFrame_.getPendingTask() || !(task = this.getNextTask_())) {1489    // Either the current frame is blocked on a pending task, or we don't have1490    // a task to finish because we've completed a frame. When completing a1491    // frame, we must abort the event loop to allow the frame's promise's1492    // callbacks to execute.1493    return;1494  }14951496  var activeFrame = this.activeFrame_;1497  activeFrame.setPendingTask(task);1498  var markTaskComplete = goog.bind(function() {1499    this.history_.push(/** @type {!webdriver.promise.Task_} */ (task));1500    activeFrame.setPendingTask(null);1501  }, this);15021503  this.trimHistory_();1504  var self = this;1505  this.runInNewFrame_(task.execute, function(result) {1506    markTaskComplete();1507    task.fulfill(result);1508  }, function(error) {1509    markTaskComplete();15101511    if (!webdriver.promise.isError_(error) &&1512        !webdriver.promise.isPromise(error)) {1513      error = Error(error);1514    }15151516    task.reject(self.annotateError(/** @type {!Error} */ (error)));1517  }, true);1518};151915201521/**1522 * @return {webdriver.promise.Task_} The next task to execute, or1523 *     {@code null} if a frame was resolved.1524 * @private1525 */1526webdriver.promise.ControlFlow.prototype.getNextTask_ = function() {1527  var firstChild = this.activeFrame_.getFirstChild();1528  if (!firstChild) {1529    if (!this.activeFrame_.isWaiting) {1530      this.resolveFrame_(this.activeFrame_);1531    }1532    return null;1533  }15341535  if (firstChild instanceof webdriver.promise.Frame_) {1536    this.activeFrame_ = firstChild;1537    return this.getNextTask_();1538  }15391540  firstChild.getParent().removeChild(firstChild);1541  return firstChild;1542};154315441545/**1546 * @param {!webdriver.promise.Frame_} frame The frame to resolve.1547 * @private1548 */1549webdriver.promise.ControlFlow.prototype.resolveFrame_ = function(frame) {1550  if (this.activeFrame_ === frame) {1551    // Frame parent is always another frame, but the compiler is not smart1552    // enough to recognize this.1553    this.activeFrame_ =1554        /** @type {webdriver.promise.Frame_} */ (frame.getParent());1555  }15561557  if (frame.getParent()) {1558    frame.getParent().removeChild(frame);1559  }1560  this.trimHistory_();1561  frame.fulfill();15621563  if (!this.activeFrame_) {1564    this.commenceShutdown_();1565  }1566};156715681569/**1570 * Aborts the current frame. The frame, and all of the tasks scheduled within it1571 * will be discarded. If this instance does not have an active frame, it will1572 * immediately terminate all execution.1573 * @param {*} error The reason the frame is being aborted; typically either1574 *     an Error or string.1575 * @private1576 */1577webdriver.promise.ControlFlow.prototype.abortFrame_ = function(error) {1578  // Annotate the error value if it is Error-like.1579  if (webdriver.promise.isError_(error)) {1580    this.annotateError(/** @type {!Error} */ (error));1581  }1582  this.numAbortedFrames_++;15831584  if (!this.activeFrame_) {1585    this.abortNow_(error);1586    return;1587  }15881589  // Frame parent is always another frame, but the compiler is not smart1590  // enough to recognize this.1591  var parent = /** @type {webdriver.promise.Frame_} */ (1592      this.activeFrame_.getParent());1593  if (parent) {1594    parent.removeChild(this.activeFrame_);1595  }15961597  var frame = this.activeFrame_;1598  this.activeFrame_ = parent;1599  frame.reject(error);1600};160116021603/**1604 * Executes a function in a new frame. If the function does not schedule any new1605 * tasks, the frame will be discarded and the function's result returned1606 * immediately. Otherwise, a promise will be returned. This promise will be1607 * resolved with the function's result once all of the tasks scheduled within1608 * the function have been completed. If the function's frame is aborted, the1609 * returned promise will be rejected.1610 *1611 * @param {!Function} fn The function to execute.1612 * @param {function(*)} callback The function to call with a successful result.1613 * @param {function(*)} errback The function to call if there is an error.1614 * @param {boolean=} opt_activate Whether the active frame should be updated to1615 *     the newly created frame so tasks are treated as sub-tasks.1616 * @private1617 */1618webdriver.promise.ControlFlow.prototype.runInNewFrame_ = function(1619    fn, callback, errback, opt_activate) {1620  var newFrame = new webdriver.promise.Frame_(this),1621      self = this,1622      oldFrame = this.activeFrame_;16231624  try {1625    if (!this.activeFrame_) {1626      this.activeFrame_ = newFrame;1627    } else {1628      this.activeFrame_.addChild(newFrame);1629    }16301631    // Activate the new frame to force tasks to be treated as sub-tasks of1632    // the parent frame.1633    if (opt_activate) {1634      this.activeFrame_ = newFrame;1635    }16361637    try {1638      this.schedulingFrame_ = newFrame;1639      webdriver.promise.pushFlow_(this);1640      var result = fn();1641    } finally {1642      webdriver.promise.popFlow_();1643      this.schedulingFrame_ = null;1644    }1645    newFrame.lockFrame();16461647    // If there was nothing scheduled in the new frame we can discard the1648    // frame and return immediately.1649    if (!newFrame.children_.length) {1650      removeNewFrame();1651      webdriver.promise.asap(result, callback, errback);1652      return;1653    }16541655    newFrame.then(function() {1656      webdriver.promise.asap(result, callback, errback);1657    }, function(e) {1658      if (webdriver.promise.Thenable.isImplementation(result) &&1659          result.isPending()) {1660        result.cancel(e);1661        e = result;1662      }1663      errback(e);1664    });1665  } catch (ex) {1666    removeNewFrame(new webdriver.promise.CanceledTaskError_(ex));1667    errback(ex);1668  }16691670  /**1671   * @param {webdriver.promise.CanceledTaskError_=} opt_err If provided, the1672   *     error that triggered the removal of this frame.1673   */1674  function removeNewFrame(opt_err) {1675    var parent = newFrame.getParent();1676    if (parent) {1677      parent.removeChild(newFrame);1678    }16791680    if (opt_err) {1681      newFrame.cancelRemainingTasks(opt_err);1682    }1683    self.activeFrame_ = oldFrame;1684  }1685};168616871688/**1689 * Commences the shutdown sequence for this instance. After one turn of the1690 * event loop, this object will emit the1691 * {@link webdriver.promise.ControlFlow.EventType.IDLE} event to signal1692 * listeners that it has completed. During this wait, if another task is1693 * scheduled, the shutdown will be aborted.1694 * @private1695 */1696webdriver.promise.ControlFlow.prototype.commenceShutdown_ = function() {1697  if (!this.shutdownId_) {1698    // Go ahead and stop the event loop now.  If we're in here, then there are1699    // no more frames with tasks to execute. If we waited to cancel the event1700    // loop in our timeout below, the event loop could trigger *before* the1701    // timeout, generating an error from there being no frames.1702    // If #execute is called before the timeout below fires, it will cancel1703    // the timeout and restart the event loop.1704    this.cancelEventLoop_();17051706    var self = this;1707    self.shutdownId_ = self.timer.setTimeout(function() {1708      self.shutdownId_ = null;1709      self.emit(webdriver.promise.ControlFlow.EventType.IDLE);1710    }, 0);1711  }1712};171317141715/**1716 * Cancels the shutdown sequence if it is currently scheduled.1717 * @private1718 */1719webdriver.promise.ControlFlow.prototype.cancelShutdown_ = function() {1720  if (this.shutdownId_) {1721    this.timer.clearTimeout(this.shutdownId_);1722    this.shutdownId_ = null;1723  }1724};172517261727/**1728 * Aborts this flow, abandoning all remaining tasks. If there are1729 * listeners registered, an {@code UNCAUGHT_EXCEPTION} will be emitted with the1730 * offending {@code error}, otherwise, the {@code error} will be rethrown to the1731 * global error handler.1732 * @param {*} error Object describing the error that caused the flow to1733 *     abort; usually either an Error or string value.1734 * @private1735 */1736webdriver.promise.ControlFlow.prototype.abortNow_ = function(error) {1737  this.activeFrame_ = null;1738  this.cancelShutdown_();1739  this.cancelEventLoop_();17401741  var listeners = this.listeners(1742      webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION);1743  if (!listeners.length) {1744    this.timer.setTimeout(function() {1745      throw error;1746    }, 0);1747  } else {1748    this.emit(webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION,1749        error);1750  }1751};1752175317541755/**1756 * A single node in an {@link webdriver.promise.ControlFlow}'s task tree.1757 * @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs1758 *     to.1759 * @constructor1760 * @extends {webdriver.promise.Deferred}1761 * @private1762 */1763webdriver.promise.Node_ = function(flow) {1764  webdriver.promise.Deferred.call(this, null, flow);1765};1766goog.inherits(webdriver.promise.Node_, webdriver.promise.Deferred);176717681769/**1770 * This node's parent.1771 * @private {webdriver.promise.Node_}1772 */1773webdriver.promise.Node_.prototype.parent_ = null;177417751776/** @return {webdriver.promise.Node_} This node's parent. */1777webdriver.promise.Node_.prototype.getParent = function() {1778  return this.parent_;1779};178017811782/**1783 * @param {webdriver.promise.Node_} parent This node's new parent.1784 */1785webdriver.promise.Node_.prototype.setParent = function(parent) {1786  this.parent_ = parent;1787};178817891790/**1791 * @return {!webdriver.promise.Node_} The root of this node's tree.1792 */1793webdriver.promise.Node_.prototype.getRoot = function() {1794  var root = this;1795  while (root.parent_) {1796    root = root.parent_;1797  }1798  return root;1799};1800180118021803/**1804 * An execution frame within a {@link webdriver.promise.ControlFlow}.  Each1805 * frame represents the execution context for either a1806 * {@link webdriver.promise.Task_} or a callback on a1807 * {@link webdriver.promise.Deferred}.1808 *1809 * <p>Each frame may contain sub-frames.  If child N is a sub-frame, then the1810 * items queued within it are given priority over child N+1.1811 *1812 * @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs1813 *     to.1814 * @constructor1815 * @extends {webdriver.promise.Node_}1816 * @private1817 */1818webdriver.promise.Frame_ = function(flow) {1819  webdriver.promise.Node_.call(this, flow);18201821  var reject = goog.bind(this.reject, this);1822  var cancelRemainingTasks = goog.bind(this.cancelRemainingTasks, this);18231824  /** @override */1825  this.reject = function(e) {1826    cancelRemainingTasks(new webdriver.promise.CanceledTaskError_(e));1827    reject(e);1828  };18291830  /**1831   * @private {!Array.<!(webdriver.promise.Frame_|webdriver.promise.Task_)>}1832   */1833  this.children_ = [];1834};1835goog.inherits(webdriver.promise.Frame_, webdriver.promise.Node_);183618371838/**1839 * The task currently being executed within this frame.1840 * @private {webdriver.promise.Task_}1841 */1842webdriver.promise.Frame_.prototype.pendingTask_ = null;184318441845/**1846 * Whether this frame is active. A frame is considered active once one of its1847 * descendants has been removed for execution.1848 *1849 * Adding a sub-frame as a child to an active frame is an indication that1850 * a callback to a {@link webdriver.promise.Deferred} is being invoked and any1851 * tasks scheduled within it should have priority over previously scheduled1852 * tasks:1853 * <code><pre>1854 *   var flow = webdriver.promise.controlFlow();1855 *   flow.execute('start here', goog.nullFunction).then(function() {1856 *     flow.execute('this should execute 2nd', goog.nullFunction);1857 *   });1858 *   flow.execute('this should execute last', goog.nullFunction);1859 * </pre></code>1860 *1861 * @private {boolean}1862 */1863webdriver.promise.Frame_.prototype.isActive_ = false;186418651866/**1867 * Whether this frame is currently locked. A locked frame represents a callback1868 * or task function which has run to completion and scheduled all of its tasks.1869 *1870 * <p>Once a frame becomes {@link #isActive_ active}, any new frames which are1871 * added represent callbacks on a {@link webdriver.promise.Deferred}, whose1872 * tasks must be given priority over previously scheduled tasks.1873 *1874 * @private {boolean}1875 */1876webdriver.promise.Frame_.prototype.isLocked_ = false;187718781879/**1880 * A reference to the last node inserted in this frame.1881 * @private {webdriver.promise.Node_}1882 */1883webdriver.promise.Frame_.prototype.lastInsertedChild_ = null;188418851886/**1887 * Marks all of the tasks that are descendants of this frame in the execution1888 * tree as cancelled. This is necessary for callbacks scheduled asynchronous.1889 * For example:1890 *1891 *     var someResult;1892 *     webdriver.promise.createFlow(function(flow) {1893 *       someResult = flow.execute(function() {});1894 *       throw Error();1895 *     }).addErrback(function(err) {1896 *       console.log('flow failed: ' + err);1897 *       someResult.then(function() {1898 *         console.log('task succeeded!');1899 *       }, function(err) {1900 *         console.log('task failed! ' + err);1901 *       });1902 *     });1903 *     // flow failed: Error: boom1904 *     // task failed! CanceledTaskError: Task discarded due to a previous1905 *     // task failure: Error: boom1906 *1907 * @param {!webdriver.promise.CanceledTaskError_} error The cancellation1908 *     error.1909 */1910webdriver.promise.Frame_.prototype.cancelRemainingTasks = function(error) {1911  goog.array.forEach(this.children_, function(child) {1912    if (child instanceof webdriver.promise.Frame_) {1913      child.cancelRemainingTasks(error);1914    } else {1915      // None of the previously registered listeners should be notified that1916      // the task is being canceled, however, we need at least one errback1917      // to prevent the cancellation from bubbling up.1918      child.removeAll();1919      child.thenCatch(goog.nullFunction);1920      child.cancel(error);1921    }1922  });1923};192419251926/**1927 * @return {webdriver.promise.Task_} The task currently executing1928 *     within this frame, if any.1929 */1930webdriver.promise.Frame_.prototype.getPendingTask = function() {1931  return this.pendingTask_;1932};193319341935/**1936 * @param {webdriver.promise.Task_} task The task currently1937 *     executing within this frame, if any.1938 */1939webdriver.promise.Frame_.prototype.setPendingTask = function(task) {1940  this.pendingTask_ = task;1941};194219431944/** Locks this frame. */1945webdriver.promise.Frame_.prototype.lockFrame = function() {1946  this.isLocked_ = true;1947};194819491950/**1951 * Adds a new node to this frame.1952 * @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} node1953 *     The node to insert.1954 */1955webdriver.promise.Frame_.prototype.addChild = function(node) {1956  if (this.lastInsertedChild_ &&1957      this.lastInsertedChild_ instanceof webdriver.promise.Frame_ &&1958      !this.lastInsertedChild_.isLocked_) {1959    this.lastInsertedChild_.addChild(node);1960    return;1961  }19621963  node.setParent(this);19641965  if (this.isActive_ && node instanceof webdriver.promise.Frame_) {1966    var index = 0;1967    if (this.lastInsertedChild_ instanceof1968        webdriver.promise.Frame_) {1969      index = goog.array.indexOf(this.children_, this.lastInsertedChild_) + 1;1970    }1971    goog.array.insertAt(this.children_, node, index);1972    this.lastInsertedChild_ = node;1973    return;1974  }19751976  this.lastInsertedChild_ = node;1977  this.children_.push(node);1978};197919801981/**1982 * @return {(webdriver.promise.Frame_|webdriver.promise.Task_)} This frame's1983 *     fist child.1984 */1985webdriver.promise.Frame_.prototype.getFirstChild = function() {1986  this.isActive_ = true;1987  this.lastInsertedChild_ = null;1988  return this.children_[0];1989};199019911992/**1993 * Removes a child from this frame.1994 * @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} child1995 *     The child to remove.1996 */1997webdriver.promise.Frame_.prototype.removeChild = function(child) {1998  var index = goog.array.indexOf(this.children_, child);1999  child.setParent(null);2000  goog.array.removeAt(this.children_, index);2001  if (this.lastInsertedChild_ === child) {2002    this.lastInsertedChild_ = null;2003  }2004};200520062007/** @override */2008webdriver.promise.Frame_.prototype.toString = function() {2009  return '[' + goog.array.map(this.children_, function(child) {2010    return child.toString();2011  }).join(', ') + ']';2012};2013201420152016/**2017 * A task to be executed by a {@link webdriver.promise.ControlFlow}.2018 *2019 * @param {!webdriver.promise.ControlFlow} flow The flow this instances belongs2020 *     to.2021 * @param {!Function} fn The function to call when the task executes. If it2022 *     returns a {@code webdriver.promise.Promise}, the flow will wait2023 *     for it to be resolved before starting the next task.2024 * @param {string} description A description of the task for debugging.2025 * @param {!webdriver.stacktrace.Snapshot} snapshot A snapshot of the stack2026 *     when this task was scheduled.2027 * @constructor2028 * @extends {webdriver.promise.Node_}2029 * @private2030 */2031webdriver.promise.Task_ = function(flow, fn, description, snapshot) {2032  webdriver.promise.Node_.call(this, flow);20332034  /**2035   * Executes this task.2036   * @type {!Function}2037   */2038  this.execute = fn;20392040  /** @private {string} */2041  this.description_ = description;20422043  /** @private {!webdriver.stacktrace.Snapshot} */2044  this.snapshot_ = snapshot;2045};2046goog.inherits(webdriver.promise.Task_, webdriver.promise.Node_);204720482049/** @return {string} This task's description. */2050webdriver.promise.Task_.prototype.getDescription = function() {2051  return this.description_;2052};205320542055/** @override */2056webdriver.promise.Task_.prototype.toString = function() {2057  var stack = this.snapshot_.getStacktrace();2058  var ret = this.description_;2059  if (stack.length) {2060    if (this.description_) {2061      ret += '\n';2062    }2063    ret += stack.join('\n');2064  }2065  return ret;2066};2067206820692070/**2071 * Special error used to signal when a task is canceled because a previous2072 * task in the same frame failed.2073 * @param {*} err The error that caused the task cancellation.2074 * @constructor2075 * @extends {goog.debug.Error}2076 * @private2077 */2078webdriver.promise.CanceledTaskError_ = function(err) {2079  goog.base(this, 'Task discarded due to a previous task failure: ' + err);2080};2081goog.inherits(webdriver.promise.CanceledTaskError_, goog.debug.Error);208220832084/** @override */2085webdriver.promise.CanceledTaskError_.prototype.name = 'CanceledTaskError';2086208720882089/**2090 * The default flow to use if no others are active.2091 * @private {!webdriver.promise.ControlFlow}2092 */2093webdriver.promise.defaultFlow_ = new webdriver.promise.ControlFlow();209420952096/**2097 * A stack of active control flows, with the top of the stack used to schedule2098 * commands. When there are multiple flows on the stack, the flow at index N2099 * represents a callback triggered within a task owned by the flow at index2100 * N-1.2101 * @private {!Array.<!webdriver.promise.ControlFlow>}2102 */2103webdriver.promise.activeFlows_ = [];210421052106/**2107 * Changes the default flow to use when no others are active.2108 * @param {!webdriver.promise.ControlFlow} flow The new default flow.2109 * @throws {Error} If the default flow is not currently active.2110 */2111webdriver.promise.setDefaultFlow = function(flow) {2112  if (webdriver.promise.activeFlows_.length) {2113    throw Error('You may only change the default flow while it is active');2114  }2115  webdriver.promise.defaultFlow_ = flow;2116};211721182119/**2120 * @return {!webdriver.promise.ControlFlow} The currently active control flow.2121 */2122webdriver.promise.controlFlow = function() {2123  return /** @type {!webdriver.promise.ControlFlow} */ (2124      goog.array.peek(webdriver.promise.activeFlows_) ||2125      webdriver.promise.defaultFlow_);2126};212721282129/**2130 * @param {!webdriver.promise.ControlFlow} flow The new flow.2131 * @private2132 */2133webdriver.promise.pushFlow_ = function(flow) {2134  webdriver.promise.activeFlows_.push(flow);2135};213621372138/** @private */2139webdriver.promise.popFlow_ = function() {2140  webdriver.promise.activeFlows_.pop();2141};214221432144/**2145 * Creates a new control flow. The provided callback will be invoked as the2146 * first task within the new flow, with the flow as its sole argument. Returns2147 * a promise that resolves to the callback result.2148 * @param {function(!webdriver.promise.ControlFlow)} callback The entry point2149 *     to the newly created flow.2150 * @return {!webdriver.promise.Promise} A promise that resolves to the callback2151 *     result.2152 */2153webdriver.promise.createFlow = function(callback) {2154  var flow = new webdriver.promise.ControlFlow(2155      webdriver.promise.defaultFlow_.timer);2156  return flow.execute(function() {2157    return callback(flow);2158  });2159};216021612162/**2163 * Tests is a function is a generator.2164 * @param {!Function} fn The function to test.2165 * @return {boolean} Whether the function is a generator.2166 */2167webdriver.promise.isGenerator = function(fn) {2168  return fn.constructor.name === 'GeneratorFunction';2169};217021712172/**2173 * Consumes a {@code GeneratorFunction}. Each time the generator yields a2174 * promise, this function will wait for it to be fulfilled before feeding the2175 * fulfilled value back into {@code next}. Likewise, if a yielded promise is2176 * rejected, the rejection error will be passed to {@code throw}.2177 *2178 * <p>Example 1: the Fibonacci Sequence.2179 * <pre><code>2180 * webdriver.promise.consume(function* fibonacci() {2181 *   var n1 = 1, n2 = 1;2182 *   for (var i = 0; i < 4; ++i) {2183 *     var tmp = yield n1 + n2;2184 *     n1 = n2;2185 *     n2 = tmp;2186 *   }2187 *   return n1 + n2;2188 * }).then(function(result) {2189 *   console.log(result);  // 132190 * });2191 * </code></pre>2192 *2193 * <p>Example 2: a generator that throws.2194 * <pre><code>2195 * webdriver.promise.consume(function* () {2196 *   yield webdriver.promise.delayed(250).then(function() {2197 *     throw Error('boom');2198 *   });2199 * }).thenCatch(function(e) {2200 *   console.log(e.toString());  // Error: boom2201 * });2202 * </code></pre>2203 *2204 * @param {!Function} generatorFn The generator function to execute.2205 * @param {Object=} opt_self The object to use as "this" when invoking the2206 *     initial generator.2207 * @param {...*} var_args Any arguments to pass to the initial generator.2208 * @return {!webdriver.promise.Promise.<?>} A promise that will resolve to the2209 *     generator's final result.2210 * @throws {TypeError} If the given function is not a generator.2211 */2212webdriver.promise.consume = function(generatorFn, opt_self, var_args) {2213  if (!webdriver.promise.isGenerator(generatorFn)) {2214    throw TypeError('Input is not a GeneratorFunction: ' +2215        generatorFn.constructor.name);2216  }22172218  var deferred = webdriver.promise.defer();2219  var generator = generatorFn.apply(opt_self, goog.array.slice(arguments, 2));2220  callNext();2221  return deferred.promise;22222223  /** @param {*=} opt_value . */2224  function callNext(opt_value) {2225    pump(generator.next, opt_value);2226  }22272228  /** @param {*=} opt_error . */2229  function callThrow(opt_error) {2230    // Dictionary lookup required because Closure compiler's built-in2231    // externs does not include GeneratorFunction.prototype.throw.2232    pump(generator['throw'], opt_error);2233  }22342235  function pump(fn, opt_arg) {2236    if (!deferred.isPending()) {2237      return;  // Defererd was cancelled; silently abort.2238    }22392240    try {2241      var result = fn.call(generator, opt_arg);2242    } catch (ex) {2243      deferred.reject(ex);2244      return;2245    }22462247    if (result.done) {2248      deferred.fulfill(result.value);2249      return;2250    }22512252    webdriver.promise.asap(result.value, callNext, callThrow);2253  }2254};