twitst4tz

twitter statistics web application
Log | Files | Refs | README | LICENSE

bluebird.js (183390B)


      1 /* @preserve
      2  * The MIT License (MIT)
      3  * 
      4  * Copyright (c) 2013-2018 Petka Antonov
      5  * 
      6  * Permission is hereby granted, free of charge, to any person obtaining a copy
      7  * of this software and associated documentation files (the "Software"), to deal
      8  * in the Software without restriction, including without limitation the rights
      9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     10  * copies of the Software, and to permit persons to whom the Software is
     11  * furnished to do so, subject to the following conditions:
     12  * 
     13  * The above copyright notice and this permission notice shall be included in
     14  * all copies or substantial portions of the Software.
     15  * 
     16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
     19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     22  * THE SOFTWARE.
     23  * 
     24  */
     25 /**
     26  * bluebird build version 3.7.2
     27  * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
     28 */
     29 !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
     30 "use strict";
     31 module.exports = function(Promise) {
     32 var SomePromiseArray = Promise._SomePromiseArray;
     33 function any(promises) {
     34     var ret = new SomePromiseArray(promises);
     35     var promise = ret.promise();
     36     ret.setHowMany(1);
     37     ret.setUnwrap();
     38     ret.init();
     39     return promise;
     40 }
     41 
     42 Promise.any = function (promises) {
     43     return any(promises);
     44 };
     45 
     46 Promise.prototype.any = function () {
     47     return any(this);
     48 };
     49 
     50 };
     51 
     52 },{}],2:[function(_dereq_,module,exports){
     53 "use strict";
     54 var firstLineError;
     55 try {throw new Error(); } catch (e) {firstLineError = e;}
     56 var schedule = _dereq_("./schedule");
     57 var Queue = _dereq_("./queue");
     58 
     59 function Async() {
     60     this._customScheduler = false;
     61     this._isTickUsed = false;
     62     this._lateQueue = new Queue(16);
     63     this._normalQueue = new Queue(16);
     64     this._haveDrainedQueues = false;
     65     var self = this;
     66     this.drainQueues = function () {
     67         self._drainQueues();
     68     };
     69     this._schedule = schedule;
     70 }
     71 
     72 Async.prototype.setScheduler = function(fn) {
     73     var prev = this._schedule;
     74     this._schedule = fn;
     75     this._customScheduler = true;
     76     return prev;
     77 };
     78 
     79 Async.prototype.hasCustomScheduler = function() {
     80     return this._customScheduler;
     81 };
     82 
     83 Async.prototype.haveItemsQueued = function () {
     84     return this._isTickUsed || this._haveDrainedQueues;
     85 };
     86 
     87 
     88 Async.prototype.fatalError = function(e, isNode) {
     89     if (isNode) {
     90         process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
     91             "\n");
     92         process.exit(2);
     93     } else {
     94         this.throwLater(e);
     95     }
     96 };
     97 
     98 Async.prototype.throwLater = function(fn, arg) {
     99     if (arguments.length === 1) {
    100         arg = fn;
    101         fn = function () { throw arg; };
    102     }
    103     if (typeof setTimeout !== "undefined") {
    104         setTimeout(function() {
    105             fn(arg);
    106         }, 0);
    107     } else try {
    108         this._schedule(function() {
    109             fn(arg);
    110         });
    111     } catch (e) {
    112         throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    113     }
    114 };
    115 
    116 function AsyncInvokeLater(fn, receiver, arg) {
    117     this._lateQueue.push(fn, receiver, arg);
    118     this._queueTick();
    119 }
    120 
    121 function AsyncInvoke(fn, receiver, arg) {
    122     this._normalQueue.push(fn, receiver, arg);
    123     this._queueTick();
    124 }
    125 
    126 function AsyncSettlePromises(promise) {
    127     this._normalQueue._pushOne(promise);
    128     this._queueTick();
    129 }
    130 
    131 Async.prototype.invokeLater = AsyncInvokeLater;
    132 Async.prototype.invoke = AsyncInvoke;
    133 Async.prototype.settlePromises = AsyncSettlePromises;
    134 
    135 
    136 function _drainQueue(queue) {
    137     while (queue.length() > 0) {
    138         _drainQueueStep(queue);
    139     }
    140 }
    141 
    142 function _drainQueueStep(queue) {
    143     var fn = queue.shift();
    144     if (typeof fn !== "function") {
    145         fn._settlePromises();
    146     } else {
    147         var receiver = queue.shift();
    148         var arg = queue.shift();
    149         fn.call(receiver, arg);
    150     }
    151 }
    152 
    153 Async.prototype._drainQueues = function () {
    154     _drainQueue(this._normalQueue);
    155     this._reset();
    156     this._haveDrainedQueues = true;
    157     _drainQueue(this._lateQueue);
    158 };
    159 
    160 Async.prototype._queueTick = function () {
    161     if (!this._isTickUsed) {
    162         this._isTickUsed = true;
    163         this._schedule(this.drainQueues);
    164     }
    165 };
    166 
    167 Async.prototype._reset = function () {
    168     this._isTickUsed = false;
    169 };
    170 
    171 module.exports = Async;
    172 module.exports.firstLineError = firstLineError;
    173 
    174 },{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){
    175 "use strict";
    176 module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
    177 var calledBind = false;
    178 var rejectThis = function(_, e) {
    179     this._reject(e);
    180 };
    181 
    182 var targetRejected = function(e, context) {
    183     context.promiseRejectionQueued = true;
    184     context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
    185 };
    186 
    187 var bindingResolved = function(thisArg, context) {
    188     if (((this._bitField & 50397184) === 0)) {
    189         this._resolveCallback(context.target);
    190     }
    191 };
    192 
    193 var bindingRejected = function(e, context) {
    194     if (!context.promiseRejectionQueued) this._reject(e);
    195 };
    196 
    197 Promise.prototype.bind = function (thisArg) {
    198     if (!calledBind) {
    199         calledBind = true;
    200         Promise.prototype._propagateFrom = debug.propagateFromFunction();
    201         Promise.prototype._boundValue = debug.boundValueFunction();
    202     }
    203     var maybePromise = tryConvertToPromise(thisArg);
    204     var ret = new Promise(INTERNAL);
    205     ret._propagateFrom(this, 1);
    206     var target = this._target();
    207     ret._setBoundTo(maybePromise);
    208     if (maybePromise instanceof Promise) {
    209         var context = {
    210             promiseRejectionQueued: false,
    211             promise: ret,
    212             target: target,
    213             bindingPromise: maybePromise
    214         };
    215         target._then(INTERNAL, targetRejected, undefined, ret, context);
    216         maybePromise._then(
    217             bindingResolved, bindingRejected, undefined, ret, context);
    218         ret._setOnCancel(maybePromise);
    219     } else {
    220         ret._resolveCallback(target);
    221     }
    222     return ret;
    223 };
    224 
    225 Promise.prototype._setBoundTo = function (obj) {
    226     if (obj !== undefined) {
    227         this._bitField = this._bitField | 2097152;
    228         this._boundTo = obj;
    229     } else {
    230         this._bitField = this._bitField & (~2097152);
    231     }
    232 };
    233 
    234 Promise.prototype._isBound = function () {
    235     return (this._bitField & 2097152) === 2097152;
    236 };
    237 
    238 Promise.bind = function (thisArg, value) {
    239     return Promise.resolve(value).bind(thisArg);
    240 };
    241 };
    242 
    243 },{}],4:[function(_dereq_,module,exports){
    244 "use strict";
    245 var old;
    246 if (typeof Promise !== "undefined") old = Promise;
    247 function noConflict() {
    248     try { if (Promise === bluebird) Promise = old; }
    249     catch (e) {}
    250     return bluebird;
    251 }
    252 var bluebird = _dereq_("./promise")();
    253 bluebird.noConflict = noConflict;
    254 module.exports = bluebird;
    255 
    256 },{"./promise":22}],5:[function(_dereq_,module,exports){
    257 "use strict";
    258 var cr = Object.create;
    259 if (cr) {
    260     var callerCache = cr(null);
    261     var getterCache = cr(null);
    262     callerCache[" size"] = getterCache[" size"] = 0;
    263 }
    264 
    265 module.exports = function(Promise) {
    266 var util = _dereq_("./util");
    267 var canEvaluate = util.canEvaluate;
    268 var isIdentifier = util.isIdentifier;
    269 
    270 var getMethodCaller;
    271 var getGetter;
    272 if (!true) {
    273 var makeMethodCaller = function (methodName) {
    274     return new Function("ensureMethod", "                                    \n\
    275         return function(obj) {                                               \n\
    276             'use strict'                                                     \n\
    277             var len = this.length;                                           \n\
    278             ensureMethod(obj, 'methodName');                                 \n\
    279             switch(len) {                                                    \n\
    280                 case 1: return obj.methodName(this[0]);                      \n\
    281                 case 2: return obj.methodName(this[0], this[1]);             \n\
    282                 case 3: return obj.methodName(this[0], this[1], this[2]);    \n\
    283                 case 0: return obj.methodName();                             \n\
    284                 default:                                                     \n\
    285                     return obj.methodName.apply(obj, this);                  \n\
    286             }                                                                \n\
    287         };                                                                   \n\
    288         ".replace(/methodName/g, methodName))(ensureMethod);
    289 };
    290 
    291 var makeGetter = function (propertyName) {
    292     return new Function("obj", "                                             \n\
    293         'use strict';                                                        \n\
    294         return obj.propertyName;                                             \n\
    295         ".replace("propertyName", propertyName));
    296 };
    297 
    298 var getCompiled = function(name, compiler, cache) {
    299     var ret = cache[name];
    300     if (typeof ret !== "function") {
    301         if (!isIdentifier(name)) {
    302             return null;
    303         }
    304         ret = compiler(name);
    305         cache[name] = ret;
    306         cache[" size"]++;
    307         if (cache[" size"] > 512) {
    308             var keys = Object.keys(cache);
    309             for (var i = 0; i < 256; ++i) delete cache[keys[i]];
    310             cache[" size"] = keys.length - 256;
    311         }
    312     }
    313     return ret;
    314 };
    315 
    316 getMethodCaller = function(name) {
    317     return getCompiled(name, makeMethodCaller, callerCache);
    318 };
    319 
    320 getGetter = function(name) {
    321     return getCompiled(name, makeGetter, getterCache);
    322 };
    323 }
    324 
    325 function ensureMethod(obj, methodName) {
    326     var fn;
    327     if (obj != null) fn = obj[methodName];
    328     if (typeof fn !== "function") {
    329         var message = "Object " + util.classString(obj) + " has no method '" +
    330             util.toString(methodName) + "'";
    331         throw new Promise.TypeError(message);
    332     }
    333     return fn;
    334 }
    335 
    336 function caller(obj) {
    337     var methodName = this.pop();
    338     var fn = ensureMethod(obj, methodName);
    339     return fn.apply(obj, this);
    340 }
    341 Promise.prototype.call = function (methodName) {
    342     var args = [].slice.call(arguments, 1);;
    343     if (!true) {
    344         if (canEvaluate) {
    345             var maybeCaller = getMethodCaller(methodName);
    346             if (maybeCaller !== null) {
    347                 return this._then(
    348                     maybeCaller, undefined, undefined, args, undefined);
    349             }
    350         }
    351     }
    352     args.push(methodName);
    353     return this._then(caller, undefined, undefined, args, undefined);
    354 };
    355 
    356 function namedGetter(obj) {
    357     return obj[this];
    358 }
    359 function indexedGetter(obj) {
    360     var index = +this;
    361     if (index < 0) index = Math.max(0, index + obj.length);
    362     return obj[index];
    363 }
    364 Promise.prototype.get = function (propertyName) {
    365     var isIndex = (typeof propertyName === "number");
    366     var getter;
    367     if (!isIndex) {
    368         if (canEvaluate) {
    369             var maybeGetter = getGetter(propertyName);
    370             getter = maybeGetter !== null ? maybeGetter : namedGetter;
    371         } else {
    372             getter = namedGetter;
    373         }
    374     } else {
    375         getter = indexedGetter;
    376     }
    377     return this._then(getter, undefined, undefined, propertyName, undefined);
    378 };
    379 };
    380 
    381 },{"./util":36}],6:[function(_dereq_,module,exports){
    382 "use strict";
    383 module.exports = function(Promise, PromiseArray, apiRejection, debug) {
    384 var util = _dereq_("./util");
    385 var tryCatch = util.tryCatch;
    386 var errorObj = util.errorObj;
    387 var async = Promise._async;
    388 
    389 Promise.prototype["break"] = Promise.prototype.cancel = function() {
    390     if (!debug.cancellation()) return this._warn("cancellation is disabled");
    391 
    392     var promise = this;
    393     var child = promise;
    394     while (promise._isCancellable()) {
    395         if (!promise._cancelBy(child)) {
    396             if (child._isFollowing()) {
    397                 child._followee().cancel();
    398             } else {
    399                 child._cancelBranched();
    400             }
    401             break;
    402         }
    403 
    404         var parent = promise._cancellationParent;
    405         if (parent == null || !parent._isCancellable()) {
    406             if (promise._isFollowing()) {
    407                 promise._followee().cancel();
    408             } else {
    409                 promise._cancelBranched();
    410             }
    411             break;
    412         } else {
    413             if (promise._isFollowing()) promise._followee().cancel();
    414             promise._setWillBeCancelled();
    415             child = promise;
    416             promise = parent;
    417         }
    418     }
    419 };
    420 
    421 Promise.prototype._branchHasCancelled = function() {
    422     this._branchesRemainingToCancel--;
    423 };
    424 
    425 Promise.prototype._enoughBranchesHaveCancelled = function() {
    426     return this._branchesRemainingToCancel === undefined ||
    427            this._branchesRemainingToCancel <= 0;
    428 };
    429 
    430 Promise.prototype._cancelBy = function(canceller) {
    431     if (canceller === this) {
    432         this._branchesRemainingToCancel = 0;
    433         this._invokeOnCancel();
    434         return true;
    435     } else {
    436         this._branchHasCancelled();
    437         if (this._enoughBranchesHaveCancelled()) {
    438             this._invokeOnCancel();
    439             return true;
    440         }
    441     }
    442     return false;
    443 };
    444 
    445 Promise.prototype._cancelBranched = function() {
    446     if (this._enoughBranchesHaveCancelled()) {
    447         this._cancel();
    448     }
    449 };
    450 
    451 Promise.prototype._cancel = function() {
    452     if (!this._isCancellable()) return;
    453     this._setCancelled();
    454     async.invoke(this._cancelPromises, this, undefined);
    455 };
    456 
    457 Promise.prototype._cancelPromises = function() {
    458     if (this._length() > 0) this._settlePromises();
    459 };
    460 
    461 Promise.prototype._unsetOnCancel = function() {
    462     this._onCancelField = undefined;
    463 };
    464 
    465 Promise.prototype._isCancellable = function() {
    466     return this.isPending() && !this._isCancelled();
    467 };
    468 
    469 Promise.prototype.isCancellable = function() {
    470     return this.isPending() && !this.isCancelled();
    471 };
    472 
    473 Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
    474     if (util.isArray(onCancelCallback)) {
    475         for (var i = 0; i < onCancelCallback.length; ++i) {
    476             this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
    477         }
    478     } else if (onCancelCallback !== undefined) {
    479         if (typeof onCancelCallback === "function") {
    480             if (!internalOnly) {
    481                 var e = tryCatch(onCancelCallback).call(this._boundValue());
    482                 if (e === errorObj) {
    483                     this._attachExtraTrace(e.e);
    484                     async.throwLater(e.e);
    485                 }
    486             }
    487         } else {
    488             onCancelCallback._resultCancelled(this);
    489         }
    490     }
    491 };
    492 
    493 Promise.prototype._invokeOnCancel = function() {
    494     var onCancelCallback = this._onCancel();
    495     this._unsetOnCancel();
    496     async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
    497 };
    498 
    499 Promise.prototype._invokeInternalOnCancel = function() {
    500     if (this._isCancellable()) {
    501         this._doInvokeOnCancel(this._onCancel(), true);
    502         this._unsetOnCancel();
    503     }
    504 };
    505 
    506 Promise.prototype._resultCancelled = function() {
    507     this.cancel();
    508 };
    509 
    510 };
    511 
    512 },{"./util":36}],7:[function(_dereq_,module,exports){
    513 "use strict";
    514 module.exports = function(NEXT_FILTER) {
    515 var util = _dereq_("./util");
    516 var getKeys = _dereq_("./es5").keys;
    517 var tryCatch = util.tryCatch;
    518 var errorObj = util.errorObj;
    519 
    520 function catchFilter(instances, cb, promise) {
    521     return function(e) {
    522         var boundTo = promise._boundValue();
    523         predicateLoop: for (var i = 0; i < instances.length; ++i) {
    524             var item = instances[i];
    525 
    526             if (item === Error ||
    527                 (item != null && item.prototype instanceof Error)) {
    528                 if (e instanceof item) {
    529                     return tryCatch(cb).call(boundTo, e);
    530                 }
    531             } else if (typeof item === "function") {
    532                 var matchesPredicate = tryCatch(item).call(boundTo, e);
    533                 if (matchesPredicate === errorObj) {
    534                     return matchesPredicate;
    535                 } else if (matchesPredicate) {
    536                     return tryCatch(cb).call(boundTo, e);
    537                 }
    538             } else if (util.isObject(e)) {
    539                 var keys = getKeys(item);
    540                 for (var j = 0; j < keys.length; ++j) {
    541                     var key = keys[j];
    542                     if (item[key] != e[key]) {
    543                         continue predicateLoop;
    544                     }
    545                 }
    546                 return tryCatch(cb).call(boundTo, e);
    547             }
    548         }
    549         return NEXT_FILTER;
    550     };
    551 }
    552 
    553 return catchFilter;
    554 };
    555 
    556 },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
    557 "use strict";
    558 module.exports = function(Promise) {
    559 var longStackTraces = false;
    560 var contextStack = [];
    561 
    562 Promise.prototype._promiseCreated = function() {};
    563 Promise.prototype._pushContext = function() {};
    564 Promise.prototype._popContext = function() {return null;};
    565 Promise._peekContext = Promise.prototype._peekContext = function() {};
    566 
    567 function Context() {
    568     this._trace = new Context.CapturedTrace(peekContext());
    569 }
    570 Context.prototype._pushContext = function () {
    571     if (this._trace !== undefined) {
    572         this._trace._promiseCreated = null;
    573         contextStack.push(this._trace);
    574     }
    575 };
    576 
    577 Context.prototype._popContext = function () {
    578     if (this._trace !== undefined) {
    579         var trace = contextStack.pop();
    580         var ret = trace._promiseCreated;
    581         trace._promiseCreated = null;
    582         return ret;
    583     }
    584     return null;
    585 };
    586 
    587 function createContext() {
    588     if (longStackTraces) return new Context();
    589 }
    590 
    591 function peekContext() {
    592     var lastIndex = contextStack.length - 1;
    593     if (lastIndex >= 0) {
    594         return contextStack[lastIndex];
    595     }
    596     return undefined;
    597 }
    598 Context.CapturedTrace = null;
    599 Context.create = createContext;
    600 Context.deactivateLongStackTraces = function() {};
    601 Context.activateLongStackTraces = function() {
    602     var Promise_pushContext = Promise.prototype._pushContext;
    603     var Promise_popContext = Promise.prototype._popContext;
    604     var Promise_PeekContext = Promise._peekContext;
    605     var Promise_peekContext = Promise.prototype._peekContext;
    606     var Promise_promiseCreated = Promise.prototype._promiseCreated;
    607     Context.deactivateLongStackTraces = function() {
    608         Promise.prototype._pushContext = Promise_pushContext;
    609         Promise.prototype._popContext = Promise_popContext;
    610         Promise._peekContext = Promise_PeekContext;
    611         Promise.prototype._peekContext = Promise_peekContext;
    612         Promise.prototype._promiseCreated = Promise_promiseCreated;
    613         longStackTraces = false;
    614     };
    615     longStackTraces = true;
    616     Promise.prototype._pushContext = Context.prototype._pushContext;
    617     Promise.prototype._popContext = Context.prototype._popContext;
    618     Promise._peekContext = Promise.prototype._peekContext = peekContext;
    619     Promise.prototype._promiseCreated = function() {
    620         var ctx = this._peekContext();
    621         if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
    622     };
    623 };
    624 return Context;
    625 };
    626 
    627 },{}],9:[function(_dereq_,module,exports){
    628 "use strict";
    629 module.exports = function(Promise, Context,
    630     enableAsyncHooks, disableAsyncHooks) {
    631 var async = Promise._async;
    632 var Warning = _dereq_("./errors").Warning;
    633 var util = _dereq_("./util");
    634 var es5 = _dereq_("./es5");
    635 var canAttachTrace = util.canAttachTrace;
    636 var unhandledRejectionHandled;
    637 var possiblyUnhandledRejection;
    638 var bluebirdFramePattern =
    639     /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
    640 var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
    641 var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
    642 var stackFramePattern = null;
    643 var formatStack = null;
    644 var indentStackFrames = false;
    645 var printWarning;
    646 var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
    647                         (true ||
    648                          util.env("BLUEBIRD_DEBUG") ||
    649                          util.env("NODE_ENV") === "development"));
    650 
    651 var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
    652     (debugging || util.env("BLUEBIRD_WARNINGS")));
    653 
    654 var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
    655     (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
    656 
    657 var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
    658     (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
    659 
    660 var deferUnhandledRejectionCheck;
    661 (function() {
    662     var promises = [];
    663 
    664     function unhandledRejectionCheck() {
    665         for (var i = 0; i < promises.length; ++i) {
    666             promises[i]._notifyUnhandledRejection();
    667         }
    668         unhandledRejectionClear();
    669     }
    670 
    671     function unhandledRejectionClear() {
    672         promises.length = 0;
    673     }
    674 
    675     deferUnhandledRejectionCheck = function(promise) {
    676         promises.push(promise);
    677         setTimeout(unhandledRejectionCheck, 1);
    678     };
    679 
    680     es5.defineProperty(Promise, "_unhandledRejectionCheck", {
    681         value: unhandledRejectionCheck
    682     });
    683     es5.defineProperty(Promise, "_unhandledRejectionClear", {
    684         value: unhandledRejectionClear
    685     });
    686 })();
    687 
    688 Promise.prototype.suppressUnhandledRejections = function() {
    689     var target = this._target();
    690     target._bitField = ((target._bitField & (~1048576)) |
    691                       524288);
    692 };
    693 
    694 Promise.prototype._ensurePossibleRejectionHandled = function () {
    695     if ((this._bitField & 524288) !== 0) return;
    696     this._setRejectionIsUnhandled();
    697     deferUnhandledRejectionCheck(this);
    698 };
    699 
    700 Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
    701     fireRejectionEvent("rejectionHandled",
    702                                   unhandledRejectionHandled, undefined, this);
    703 };
    704 
    705 Promise.prototype._setReturnedNonUndefined = function() {
    706     this._bitField = this._bitField | 268435456;
    707 };
    708 
    709 Promise.prototype._returnedNonUndefined = function() {
    710     return (this._bitField & 268435456) !== 0;
    711 };
    712 
    713 Promise.prototype._notifyUnhandledRejection = function () {
    714     if (this._isRejectionUnhandled()) {
    715         var reason = this._settledValue();
    716         this._setUnhandledRejectionIsNotified();
    717         fireRejectionEvent("unhandledRejection",
    718                                       possiblyUnhandledRejection, reason, this);
    719     }
    720 };
    721 
    722 Promise.prototype._setUnhandledRejectionIsNotified = function () {
    723     this._bitField = this._bitField | 262144;
    724 };
    725 
    726 Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
    727     this._bitField = this._bitField & (~262144);
    728 };
    729 
    730 Promise.prototype._isUnhandledRejectionNotified = function () {
    731     return (this._bitField & 262144) > 0;
    732 };
    733 
    734 Promise.prototype._setRejectionIsUnhandled = function () {
    735     this._bitField = this._bitField | 1048576;
    736 };
    737 
    738 Promise.prototype._unsetRejectionIsUnhandled = function () {
    739     this._bitField = this._bitField & (~1048576);
    740     if (this._isUnhandledRejectionNotified()) {
    741         this._unsetUnhandledRejectionIsNotified();
    742         this._notifyUnhandledRejectionIsHandled();
    743     }
    744 };
    745 
    746 Promise.prototype._isRejectionUnhandled = function () {
    747     return (this._bitField & 1048576) > 0;
    748 };
    749 
    750 Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
    751     return warn(message, shouldUseOwnTrace, promise || this);
    752 };
    753 
    754 Promise.onPossiblyUnhandledRejection = function (fn) {
    755     var context = Promise._getContext();
    756     possiblyUnhandledRejection = util.contextBind(context, fn);
    757 };
    758 
    759 Promise.onUnhandledRejectionHandled = function (fn) {
    760     var context = Promise._getContext();
    761     unhandledRejectionHandled = util.contextBind(context, fn);
    762 };
    763 
    764 var disableLongStackTraces = function() {};
    765 Promise.longStackTraces = function () {
    766     if (async.haveItemsQueued() && !config.longStackTraces) {
    767         throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    768     }
    769     if (!config.longStackTraces && longStackTracesIsSupported()) {
    770         var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
    771         var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
    772         var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
    773         config.longStackTraces = true;
    774         disableLongStackTraces = function() {
    775             if (async.haveItemsQueued() && !config.longStackTraces) {
    776                 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    777             }
    778             Promise.prototype._captureStackTrace = Promise_captureStackTrace;
    779             Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
    780             Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
    781             Context.deactivateLongStackTraces();
    782             config.longStackTraces = false;
    783         };
    784         Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
    785         Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
    786         Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
    787         Context.activateLongStackTraces();
    788     }
    789 };
    790 
    791 Promise.hasLongStackTraces = function () {
    792     return config.longStackTraces && longStackTracesIsSupported();
    793 };
    794 
    795 
    796 var legacyHandlers = {
    797     unhandledrejection: {
    798         before: function() {
    799             var ret = util.global.onunhandledrejection;
    800             util.global.onunhandledrejection = null;
    801             return ret;
    802         },
    803         after: function(fn) {
    804             util.global.onunhandledrejection = fn;
    805         }
    806     },
    807     rejectionhandled: {
    808         before: function() {
    809             var ret = util.global.onrejectionhandled;
    810             util.global.onrejectionhandled = null;
    811             return ret;
    812         },
    813         after: function(fn) {
    814             util.global.onrejectionhandled = fn;
    815         }
    816     }
    817 };
    818 
    819 var fireDomEvent = (function() {
    820     var dispatch = function(legacy, e) {
    821         if (legacy) {
    822             var fn;
    823             try {
    824                 fn = legacy.before();
    825                 return !util.global.dispatchEvent(e);
    826             } finally {
    827                 legacy.after(fn);
    828             }
    829         } else {
    830             return !util.global.dispatchEvent(e);
    831         }
    832     };
    833     try {
    834         if (typeof CustomEvent === "function") {
    835             var event = new CustomEvent("CustomEvent");
    836             util.global.dispatchEvent(event);
    837             return function(name, event) {
    838                 name = name.toLowerCase();
    839                 var eventData = {
    840                     detail: event,
    841                     cancelable: true
    842                 };
    843                 var domEvent = new CustomEvent(name, eventData);
    844                 es5.defineProperty(
    845                     domEvent, "promise", {value: event.promise});
    846                 es5.defineProperty(
    847                     domEvent, "reason", {value: event.reason});
    848 
    849                 return dispatch(legacyHandlers[name], domEvent);
    850             };
    851         } else if (typeof Event === "function") {
    852             var event = new Event("CustomEvent");
    853             util.global.dispatchEvent(event);
    854             return function(name, event) {
    855                 name = name.toLowerCase();
    856                 var domEvent = new Event(name, {
    857                     cancelable: true
    858                 });
    859                 domEvent.detail = event;
    860                 es5.defineProperty(domEvent, "promise", {value: event.promise});
    861                 es5.defineProperty(domEvent, "reason", {value: event.reason});
    862                 return dispatch(legacyHandlers[name], domEvent);
    863             };
    864         } else {
    865             var event = document.createEvent("CustomEvent");
    866             event.initCustomEvent("testingtheevent", false, true, {});
    867             util.global.dispatchEvent(event);
    868             return function(name, event) {
    869                 name = name.toLowerCase();
    870                 var domEvent = document.createEvent("CustomEvent");
    871                 domEvent.initCustomEvent(name, false, true,
    872                     event);
    873                 return dispatch(legacyHandlers[name], domEvent);
    874             };
    875         }
    876     } catch (e) {}
    877     return function() {
    878         return false;
    879     };
    880 })();
    881 
    882 var fireGlobalEvent = (function() {
    883     if (util.isNode) {
    884         return function() {
    885             return process.emit.apply(process, arguments);
    886         };
    887     } else {
    888         if (!util.global) {
    889             return function() {
    890                 return false;
    891             };
    892         }
    893         return function(name) {
    894             var methodName = "on" + name.toLowerCase();
    895             var method = util.global[methodName];
    896             if (!method) return false;
    897             method.apply(util.global, [].slice.call(arguments, 1));
    898             return true;
    899         };
    900     }
    901 })();
    902 
    903 function generatePromiseLifecycleEventObject(name, promise) {
    904     return {promise: promise};
    905 }
    906 
    907 var eventToObjectGenerator = {
    908     promiseCreated: generatePromiseLifecycleEventObject,
    909     promiseFulfilled: generatePromiseLifecycleEventObject,
    910     promiseRejected: generatePromiseLifecycleEventObject,
    911     promiseResolved: generatePromiseLifecycleEventObject,
    912     promiseCancelled: generatePromiseLifecycleEventObject,
    913     promiseChained: function(name, promise, child) {
    914         return {promise: promise, child: child};
    915     },
    916     warning: function(name, warning) {
    917         return {warning: warning};
    918     },
    919     unhandledRejection: function (name, reason, promise) {
    920         return {reason: reason, promise: promise};
    921     },
    922     rejectionHandled: generatePromiseLifecycleEventObject
    923 };
    924 
    925 var activeFireEvent = function (name) {
    926     var globalEventFired = false;
    927     try {
    928         globalEventFired = fireGlobalEvent.apply(null, arguments);
    929     } catch (e) {
    930         async.throwLater(e);
    931         globalEventFired = true;
    932     }
    933 
    934     var domEventFired = false;
    935     try {
    936         domEventFired = fireDomEvent(name,
    937                     eventToObjectGenerator[name].apply(null, arguments));
    938     } catch (e) {
    939         async.throwLater(e);
    940         domEventFired = true;
    941     }
    942 
    943     return domEventFired || globalEventFired;
    944 };
    945 
    946 Promise.config = function(opts) {
    947     opts = Object(opts);
    948     if ("longStackTraces" in opts) {
    949         if (opts.longStackTraces) {
    950             Promise.longStackTraces();
    951         } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
    952             disableLongStackTraces();
    953         }
    954     }
    955     if ("warnings" in opts) {
    956         var warningsOption = opts.warnings;
    957         config.warnings = !!warningsOption;
    958         wForgottenReturn = config.warnings;
    959 
    960         if (util.isObject(warningsOption)) {
    961             if ("wForgottenReturn" in warningsOption) {
    962                 wForgottenReturn = !!warningsOption.wForgottenReturn;
    963             }
    964         }
    965     }
    966     if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
    967         if (async.haveItemsQueued()) {
    968             throw new Error(
    969                 "cannot enable cancellation after promises are in use");
    970         }
    971         Promise.prototype._clearCancellationData =
    972             cancellationClearCancellationData;
    973         Promise.prototype._propagateFrom = cancellationPropagateFrom;
    974         Promise.prototype._onCancel = cancellationOnCancel;
    975         Promise.prototype._setOnCancel = cancellationSetOnCancel;
    976         Promise.prototype._attachCancellationCallback =
    977             cancellationAttachCancellationCallback;
    978         Promise.prototype._execute = cancellationExecute;
    979         propagateFromFunction = cancellationPropagateFrom;
    980         config.cancellation = true;
    981     }
    982     if ("monitoring" in opts) {
    983         if (opts.monitoring && !config.monitoring) {
    984             config.monitoring = true;
    985             Promise.prototype._fireEvent = activeFireEvent;
    986         } else if (!opts.monitoring && config.monitoring) {
    987             config.monitoring = false;
    988             Promise.prototype._fireEvent = defaultFireEvent;
    989         }
    990     }
    991     if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
    992         var prev = config.asyncHooks;
    993         var cur = !!opts.asyncHooks;
    994         if (prev !== cur) {
    995             config.asyncHooks = cur;
    996             if (cur) {
    997                 enableAsyncHooks();
    998             } else {
    999                 disableAsyncHooks();
   1000             }
   1001         }
   1002     }
   1003     return Promise;
   1004 };
   1005 
   1006 function defaultFireEvent() { return false; }
   1007 
   1008 Promise.prototype._fireEvent = defaultFireEvent;
   1009 Promise.prototype._execute = function(executor, resolve, reject) {
   1010     try {
   1011         executor(resolve, reject);
   1012     } catch (e) {
   1013         return e;
   1014     }
   1015 };
   1016 Promise.prototype._onCancel = function () {};
   1017 Promise.prototype._setOnCancel = function (handler) { ; };
   1018 Promise.prototype._attachCancellationCallback = function(onCancel) {
   1019     ;
   1020 };
   1021 Promise.prototype._captureStackTrace = function () {};
   1022 Promise.prototype._attachExtraTrace = function () {};
   1023 Promise.prototype._dereferenceTrace = function () {};
   1024 Promise.prototype._clearCancellationData = function() {};
   1025 Promise.prototype._propagateFrom = function (parent, flags) {
   1026     ;
   1027     ;
   1028 };
   1029 
   1030 function cancellationExecute(executor, resolve, reject) {
   1031     var promise = this;
   1032     try {
   1033         executor(resolve, reject, function(onCancel) {
   1034             if (typeof onCancel !== "function") {
   1035                 throw new TypeError("onCancel must be a function, got: " +
   1036                                     util.toString(onCancel));
   1037             }
   1038             promise._attachCancellationCallback(onCancel);
   1039         });
   1040     } catch (e) {
   1041         return e;
   1042     }
   1043 }
   1044 
   1045 function cancellationAttachCancellationCallback(onCancel) {
   1046     if (!this._isCancellable()) return this;
   1047 
   1048     var previousOnCancel = this._onCancel();
   1049     if (previousOnCancel !== undefined) {
   1050         if (util.isArray(previousOnCancel)) {
   1051             previousOnCancel.push(onCancel);
   1052         } else {
   1053             this._setOnCancel([previousOnCancel, onCancel]);
   1054         }
   1055     } else {
   1056         this._setOnCancel(onCancel);
   1057     }
   1058 }
   1059 
   1060 function cancellationOnCancel() {
   1061     return this._onCancelField;
   1062 }
   1063 
   1064 function cancellationSetOnCancel(onCancel) {
   1065     this._onCancelField = onCancel;
   1066 }
   1067 
   1068 function cancellationClearCancellationData() {
   1069     this._cancellationParent = undefined;
   1070     this._onCancelField = undefined;
   1071 }
   1072 
   1073 function cancellationPropagateFrom(parent, flags) {
   1074     if ((flags & 1) !== 0) {
   1075         this._cancellationParent = parent;
   1076         var branchesRemainingToCancel = parent._branchesRemainingToCancel;
   1077         if (branchesRemainingToCancel === undefined) {
   1078             branchesRemainingToCancel = 0;
   1079         }
   1080         parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
   1081     }
   1082     if ((flags & 2) !== 0 && parent._isBound()) {
   1083         this._setBoundTo(parent._boundTo);
   1084     }
   1085 }
   1086 
   1087 function bindingPropagateFrom(parent, flags) {
   1088     if ((flags & 2) !== 0 && parent._isBound()) {
   1089         this._setBoundTo(parent._boundTo);
   1090     }
   1091 }
   1092 var propagateFromFunction = bindingPropagateFrom;
   1093 
   1094 function boundValueFunction() {
   1095     var ret = this._boundTo;
   1096     if (ret !== undefined) {
   1097         if (ret instanceof Promise) {
   1098             if (ret.isFulfilled()) {
   1099                 return ret.value();
   1100             } else {
   1101                 return undefined;
   1102             }
   1103         }
   1104     }
   1105     return ret;
   1106 }
   1107 
   1108 function longStackTracesCaptureStackTrace() {
   1109     this._trace = new CapturedTrace(this._peekContext());
   1110 }
   1111 
   1112 function longStackTracesAttachExtraTrace(error, ignoreSelf) {
   1113     if (canAttachTrace(error)) {
   1114         var trace = this._trace;
   1115         if (trace !== undefined) {
   1116             if (ignoreSelf) trace = trace._parent;
   1117         }
   1118         if (trace !== undefined) {
   1119             trace.attachExtraTrace(error);
   1120         } else if (!error.__stackCleaned__) {
   1121             var parsed = parseStackAndMessage(error);
   1122             util.notEnumerableProp(error, "stack",
   1123                 parsed.message + "\n" + parsed.stack.join("\n"));
   1124             util.notEnumerableProp(error, "__stackCleaned__", true);
   1125         }
   1126     }
   1127 }
   1128 
   1129 function longStackTracesDereferenceTrace() {
   1130     this._trace = undefined;
   1131 }
   1132 
   1133 function checkForgottenReturns(returnValue, promiseCreated, name, promise,
   1134                                parent) {
   1135     if (returnValue === undefined && promiseCreated !== null &&
   1136         wForgottenReturn) {
   1137         if (parent !== undefined && parent._returnedNonUndefined()) return;
   1138         if ((promise._bitField & 65535) === 0) return;
   1139 
   1140         if (name) name = name + " ";
   1141         var handlerLine = "";
   1142         var creatorLine = "";
   1143         if (promiseCreated._trace) {
   1144             var traceLines = promiseCreated._trace.stack.split("\n");
   1145             var stack = cleanStack(traceLines);
   1146             for (var i = stack.length - 1; i >= 0; --i) {
   1147                 var line = stack[i];
   1148                 if (!nodeFramePattern.test(line)) {
   1149                     var lineMatches = line.match(parseLinePattern);
   1150                     if (lineMatches) {
   1151                         handlerLine  = "at " + lineMatches[1] +
   1152                             ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
   1153                     }
   1154                     break;
   1155                 }
   1156             }
   1157 
   1158             if (stack.length > 0) {
   1159                 var firstUserLine = stack[0];
   1160                 for (var i = 0; i < traceLines.length; ++i) {
   1161 
   1162                     if (traceLines[i] === firstUserLine) {
   1163                         if (i > 0) {
   1164                             creatorLine = "\n" + traceLines[i - 1];
   1165                         }
   1166                         break;
   1167                     }
   1168                 }
   1169 
   1170             }
   1171         }
   1172         var msg = "a promise was created in a " + name +
   1173             "handler " + handlerLine + "but was not returned from it, " +
   1174             "see http://goo.gl/rRqMUw" +
   1175             creatorLine;
   1176         promise._warn(msg, true, promiseCreated);
   1177     }
   1178 }
   1179 
   1180 function deprecated(name, replacement) {
   1181     var message = name +
   1182         " is deprecated and will be removed in a future version.";
   1183     if (replacement) message += " Use " + replacement + " instead.";
   1184     return warn(message);
   1185 }
   1186 
   1187 function warn(message, shouldUseOwnTrace, promise) {
   1188     if (!config.warnings) return;
   1189     var warning = new Warning(message);
   1190     var ctx;
   1191     if (shouldUseOwnTrace) {
   1192         promise._attachExtraTrace(warning);
   1193     } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
   1194         ctx.attachExtraTrace(warning);
   1195     } else {
   1196         var parsed = parseStackAndMessage(warning);
   1197         warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
   1198     }
   1199 
   1200     if (!activeFireEvent("warning", warning)) {
   1201         formatAndLogError(warning, "", true);
   1202     }
   1203 }
   1204 
   1205 function reconstructStack(message, stacks) {
   1206     for (var i = 0; i < stacks.length - 1; ++i) {
   1207         stacks[i].push("From previous event:");
   1208         stacks[i] = stacks[i].join("\n");
   1209     }
   1210     if (i < stacks.length) {
   1211         stacks[i] = stacks[i].join("\n");
   1212     }
   1213     return message + "\n" + stacks.join("\n");
   1214 }
   1215 
   1216 function removeDuplicateOrEmptyJumps(stacks) {
   1217     for (var i = 0; i < stacks.length; ++i) {
   1218         if (stacks[i].length === 0 ||
   1219             ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
   1220             stacks.splice(i, 1);
   1221             i--;
   1222         }
   1223     }
   1224 }
   1225 
   1226 function removeCommonRoots(stacks) {
   1227     var current = stacks[0];
   1228     for (var i = 1; i < stacks.length; ++i) {
   1229         var prev = stacks[i];
   1230         var currentLastIndex = current.length - 1;
   1231         var currentLastLine = current[currentLastIndex];
   1232         var commonRootMeetPoint = -1;
   1233 
   1234         for (var j = prev.length - 1; j >= 0; --j) {
   1235             if (prev[j] === currentLastLine) {
   1236                 commonRootMeetPoint = j;
   1237                 break;
   1238             }
   1239         }
   1240 
   1241         for (var j = commonRootMeetPoint; j >= 0; --j) {
   1242             var line = prev[j];
   1243             if (current[currentLastIndex] === line) {
   1244                 current.pop();
   1245                 currentLastIndex--;
   1246             } else {
   1247                 break;
   1248             }
   1249         }
   1250         current = prev;
   1251     }
   1252 }
   1253 
   1254 function cleanStack(stack) {
   1255     var ret = [];
   1256     for (var i = 0; i < stack.length; ++i) {
   1257         var line = stack[i];
   1258         var isTraceLine = "    (No stack trace)" === line ||
   1259             stackFramePattern.test(line);
   1260         var isInternalFrame = isTraceLine && shouldIgnore(line);
   1261         if (isTraceLine && !isInternalFrame) {
   1262             if (indentStackFrames && line.charAt(0) !== " ") {
   1263                 line = "    " + line;
   1264             }
   1265             ret.push(line);
   1266         }
   1267     }
   1268     return ret;
   1269 }
   1270 
   1271 function stackFramesAsArray(error) {
   1272     var stack = error.stack.replace(/\s+$/g, "").split("\n");
   1273     for (var i = 0; i < stack.length; ++i) {
   1274         var line = stack[i];
   1275         if ("    (No stack trace)" === line || stackFramePattern.test(line)) {
   1276             break;
   1277         }
   1278     }
   1279     if (i > 0 && error.name != "SyntaxError") {
   1280         stack = stack.slice(i);
   1281     }
   1282     return stack;
   1283 }
   1284 
   1285 function parseStackAndMessage(error) {
   1286     var stack = error.stack;
   1287     var message = error.toString();
   1288     stack = typeof stack === "string" && stack.length > 0
   1289                 ? stackFramesAsArray(error) : ["    (No stack trace)"];
   1290     return {
   1291         message: message,
   1292         stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
   1293     };
   1294 }
   1295 
   1296 function formatAndLogError(error, title, isSoft) {
   1297     if (typeof console !== "undefined") {
   1298         var message;
   1299         if (util.isObject(error)) {
   1300             var stack = error.stack;
   1301             message = title + formatStack(stack, error);
   1302         } else {
   1303             message = title + String(error);
   1304         }
   1305         if (typeof printWarning === "function") {
   1306             printWarning(message, isSoft);
   1307         } else if (typeof console.log === "function" ||
   1308             typeof console.log === "object") {
   1309             console.log(message);
   1310         }
   1311     }
   1312 }
   1313 
   1314 function fireRejectionEvent(name, localHandler, reason, promise) {
   1315     var localEventFired = false;
   1316     try {
   1317         if (typeof localHandler === "function") {
   1318             localEventFired = true;
   1319             if (name === "rejectionHandled") {
   1320                 localHandler(promise);
   1321             } else {
   1322                 localHandler(reason, promise);
   1323             }
   1324         }
   1325     } catch (e) {
   1326         async.throwLater(e);
   1327     }
   1328 
   1329     if (name === "unhandledRejection") {
   1330         if (!activeFireEvent(name, reason, promise) && !localEventFired) {
   1331             formatAndLogError(reason, "Unhandled rejection ");
   1332         }
   1333     } else {
   1334         activeFireEvent(name, promise);
   1335     }
   1336 }
   1337 
   1338 function formatNonError(obj) {
   1339     var str;
   1340     if (typeof obj === "function") {
   1341         str = "[function " +
   1342             (obj.name || "anonymous") +
   1343             "]";
   1344     } else {
   1345         str = obj && typeof obj.toString === "function"
   1346             ? obj.toString() : util.toString(obj);
   1347         var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
   1348         if (ruselessToString.test(str)) {
   1349             try {
   1350                 var newStr = JSON.stringify(obj);
   1351                 str = newStr;
   1352             }
   1353             catch(e) {
   1354 
   1355             }
   1356         }
   1357         if (str.length === 0) {
   1358             str = "(empty array)";
   1359         }
   1360     }
   1361     return ("(<" + snip(str) + ">, no stack trace)");
   1362 }
   1363 
   1364 function snip(str) {
   1365     var maxChars = 41;
   1366     if (str.length < maxChars) {
   1367         return str;
   1368     }
   1369     return str.substr(0, maxChars - 3) + "...";
   1370 }
   1371 
   1372 function longStackTracesIsSupported() {
   1373     return typeof captureStackTrace === "function";
   1374 }
   1375 
   1376 var shouldIgnore = function() { return false; };
   1377 var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
   1378 function parseLineInfo(line) {
   1379     var matches = line.match(parseLineInfoRegex);
   1380     if (matches) {
   1381         return {
   1382             fileName: matches[1],
   1383             line: parseInt(matches[2], 10)
   1384         };
   1385     }
   1386 }
   1387 
   1388 function setBounds(firstLineError, lastLineError) {
   1389     if (!longStackTracesIsSupported()) return;
   1390     var firstStackLines = (firstLineError.stack || "").split("\n");
   1391     var lastStackLines = (lastLineError.stack || "").split("\n");
   1392     var firstIndex = -1;
   1393     var lastIndex = -1;
   1394     var firstFileName;
   1395     var lastFileName;
   1396     for (var i = 0; i < firstStackLines.length; ++i) {
   1397         var result = parseLineInfo(firstStackLines[i]);
   1398         if (result) {
   1399             firstFileName = result.fileName;
   1400             firstIndex = result.line;
   1401             break;
   1402         }
   1403     }
   1404     for (var i = 0; i < lastStackLines.length; ++i) {
   1405         var result = parseLineInfo(lastStackLines[i]);
   1406         if (result) {
   1407             lastFileName = result.fileName;
   1408             lastIndex = result.line;
   1409             break;
   1410         }
   1411     }
   1412     if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
   1413         firstFileName !== lastFileName || firstIndex >= lastIndex) {
   1414         return;
   1415     }
   1416 
   1417     shouldIgnore = function(line) {
   1418         if (bluebirdFramePattern.test(line)) return true;
   1419         var info = parseLineInfo(line);
   1420         if (info) {
   1421             if (info.fileName === firstFileName &&
   1422                 (firstIndex <= info.line && info.line <= lastIndex)) {
   1423                 return true;
   1424             }
   1425         }
   1426         return false;
   1427     };
   1428 }
   1429 
   1430 function CapturedTrace(parent) {
   1431     this._parent = parent;
   1432     this._promisesCreated = 0;
   1433     var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
   1434     captureStackTrace(this, CapturedTrace);
   1435     if (length > 32) this.uncycle();
   1436 }
   1437 util.inherits(CapturedTrace, Error);
   1438 Context.CapturedTrace = CapturedTrace;
   1439 
   1440 CapturedTrace.prototype.uncycle = function() {
   1441     var length = this._length;
   1442     if (length < 2) return;
   1443     var nodes = [];
   1444     var stackToIndex = {};
   1445 
   1446     for (var i = 0, node = this; node !== undefined; ++i) {
   1447         nodes.push(node);
   1448         node = node._parent;
   1449     }
   1450     length = this._length = i;
   1451     for (var i = length - 1; i >= 0; --i) {
   1452         var stack = nodes[i].stack;
   1453         if (stackToIndex[stack] === undefined) {
   1454             stackToIndex[stack] = i;
   1455         }
   1456     }
   1457     for (var i = 0; i < length; ++i) {
   1458         var currentStack = nodes[i].stack;
   1459         var index = stackToIndex[currentStack];
   1460         if (index !== undefined && index !== i) {
   1461             if (index > 0) {
   1462                 nodes[index - 1]._parent = undefined;
   1463                 nodes[index - 1]._length = 1;
   1464             }
   1465             nodes[i]._parent = undefined;
   1466             nodes[i]._length = 1;
   1467             var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
   1468 
   1469             if (index < length - 1) {
   1470                 cycleEdgeNode._parent = nodes[index + 1];
   1471                 cycleEdgeNode._parent.uncycle();
   1472                 cycleEdgeNode._length =
   1473                     cycleEdgeNode._parent._length + 1;
   1474             } else {
   1475                 cycleEdgeNode._parent = undefined;
   1476                 cycleEdgeNode._length = 1;
   1477             }
   1478             var currentChildLength = cycleEdgeNode._length + 1;
   1479             for (var j = i - 2; j >= 0; --j) {
   1480                 nodes[j]._length = currentChildLength;
   1481                 currentChildLength++;
   1482             }
   1483             return;
   1484         }
   1485     }
   1486 };
   1487 
   1488 CapturedTrace.prototype.attachExtraTrace = function(error) {
   1489     if (error.__stackCleaned__) return;
   1490     this.uncycle();
   1491     var parsed = parseStackAndMessage(error);
   1492     var message = parsed.message;
   1493     var stacks = [parsed.stack];
   1494 
   1495     var trace = this;
   1496     while (trace !== undefined) {
   1497         stacks.push(cleanStack(trace.stack.split("\n")));
   1498         trace = trace._parent;
   1499     }
   1500     removeCommonRoots(stacks);
   1501     removeDuplicateOrEmptyJumps(stacks);
   1502     util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
   1503     util.notEnumerableProp(error, "__stackCleaned__", true);
   1504 };
   1505 
   1506 var captureStackTrace = (function stackDetection() {
   1507     var v8stackFramePattern = /^\s*at\s*/;
   1508     var v8stackFormatter = function(stack, error) {
   1509         if (typeof stack === "string") return stack;
   1510 
   1511         if (error.name !== undefined &&
   1512             error.message !== undefined) {
   1513             return error.toString();
   1514         }
   1515         return formatNonError(error);
   1516     };
   1517 
   1518     if (typeof Error.stackTraceLimit === "number" &&
   1519         typeof Error.captureStackTrace === "function") {
   1520         Error.stackTraceLimit += 6;
   1521         stackFramePattern = v8stackFramePattern;
   1522         formatStack = v8stackFormatter;
   1523         var captureStackTrace = Error.captureStackTrace;
   1524 
   1525         shouldIgnore = function(line) {
   1526             return bluebirdFramePattern.test(line);
   1527         };
   1528         return function(receiver, ignoreUntil) {
   1529             Error.stackTraceLimit += 6;
   1530             captureStackTrace(receiver, ignoreUntil);
   1531             Error.stackTraceLimit -= 6;
   1532         };
   1533     }
   1534     var err = new Error();
   1535 
   1536     if (typeof err.stack === "string" &&
   1537         err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
   1538         stackFramePattern = /@/;
   1539         formatStack = v8stackFormatter;
   1540         indentStackFrames = true;
   1541         return function captureStackTrace(o) {
   1542             o.stack = new Error().stack;
   1543         };
   1544     }
   1545 
   1546     var hasStackAfterThrow;
   1547     try { throw new Error(); }
   1548     catch(e) {
   1549         hasStackAfterThrow = ("stack" in e);
   1550     }
   1551     if (!("stack" in err) && hasStackAfterThrow &&
   1552         typeof Error.stackTraceLimit === "number") {
   1553         stackFramePattern = v8stackFramePattern;
   1554         formatStack = v8stackFormatter;
   1555         return function captureStackTrace(o) {
   1556             Error.stackTraceLimit += 6;
   1557             try { throw new Error(); }
   1558             catch(e) { o.stack = e.stack; }
   1559             Error.stackTraceLimit -= 6;
   1560         };
   1561     }
   1562 
   1563     formatStack = function(stack, error) {
   1564         if (typeof stack === "string") return stack;
   1565 
   1566         if ((typeof error === "object" ||
   1567             typeof error === "function") &&
   1568             error.name !== undefined &&
   1569             error.message !== undefined) {
   1570             return error.toString();
   1571         }
   1572         return formatNonError(error);
   1573     };
   1574 
   1575     return null;
   1576 
   1577 })([]);
   1578 
   1579 if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
   1580     printWarning = function (message) {
   1581         console.warn(message);
   1582     };
   1583     if (util.isNode && process.stderr.isTTY) {
   1584         printWarning = function(message, isSoft) {
   1585             var color = isSoft ? "\u001b[33m" : "\u001b[31m";
   1586             console.warn(color + message + "\u001b[0m\n");
   1587         };
   1588     } else if (!util.isNode && typeof (new Error().stack) === "string") {
   1589         printWarning = function(message, isSoft) {
   1590             console.warn("%c" + message,
   1591                         isSoft ? "color: darkorange" : "color: red");
   1592         };
   1593     }
   1594 }
   1595 
   1596 var config = {
   1597     warnings: warnings,
   1598     longStackTraces: false,
   1599     cancellation: false,
   1600     monitoring: false,
   1601     asyncHooks: false
   1602 };
   1603 
   1604 if (longStackTraces) Promise.longStackTraces();
   1605 
   1606 return {
   1607     asyncHooks: function() {
   1608         return config.asyncHooks;
   1609     },
   1610     longStackTraces: function() {
   1611         return config.longStackTraces;
   1612     },
   1613     warnings: function() {
   1614         return config.warnings;
   1615     },
   1616     cancellation: function() {
   1617         return config.cancellation;
   1618     },
   1619     monitoring: function() {
   1620         return config.monitoring;
   1621     },
   1622     propagateFromFunction: function() {
   1623         return propagateFromFunction;
   1624     },
   1625     boundValueFunction: function() {
   1626         return boundValueFunction;
   1627     },
   1628     checkForgottenReturns: checkForgottenReturns,
   1629     setBounds: setBounds,
   1630     warn: warn,
   1631     deprecated: deprecated,
   1632     CapturedTrace: CapturedTrace,
   1633     fireDomEvent: fireDomEvent,
   1634     fireGlobalEvent: fireGlobalEvent
   1635 };
   1636 };
   1637 
   1638 },{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){
   1639 "use strict";
   1640 module.exports = function(Promise) {
   1641 function returner() {
   1642     return this.value;
   1643 }
   1644 function thrower() {
   1645     throw this.reason;
   1646 }
   1647 
   1648 Promise.prototype["return"] =
   1649 Promise.prototype.thenReturn = function (value) {
   1650     if (value instanceof Promise) value.suppressUnhandledRejections();
   1651     return this._then(
   1652         returner, undefined, undefined, {value: value}, undefined);
   1653 };
   1654 
   1655 Promise.prototype["throw"] =
   1656 Promise.prototype.thenThrow = function (reason) {
   1657     return this._then(
   1658         thrower, undefined, undefined, {reason: reason}, undefined);
   1659 };
   1660 
   1661 Promise.prototype.catchThrow = function (reason) {
   1662     if (arguments.length <= 1) {
   1663         return this._then(
   1664             undefined, thrower, undefined, {reason: reason}, undefined);
   1665     } else {
   1666         var _reason = arguments[1];
   1667         var handler = function() {throw _reason;};
   1668         return this.caught(reason, handler);
   1669     }
   1670 };
   1671 
   1672 Promise.prototype.catchReturn = function (value) {
   1673     if (arguments.length <= 1) {
   1674         if (value instanceof Promise) value.suppressUnhandledRejections();
   1675         return this._then(
   1676             undefined, returner, undefined, {value: value}, undefined);
   1677     } else {
   1678         var _value = arguments[1];
   1679         if (_value instanceof Promise) _value.suppressUnhandledRejections();
   1680         var handler = function() {return _value;};
   1681         return this.caught(value, handler);
   1682     }
   1683 };
   1684 };
   1685 
   1686 },{}],11:[function(_dereq_,module,exports){
   1687 "use strict";
   1688 module.exports = function(Promise, INTERNAL) {
   1689 var PromiseReduce = Promise.reduce;
   1690 var PromiseAll = Promise.all;
   1691 
   1692 function promiseAllThis() {
   1693     return PromiseAll(this);
   1694 }
   1695 
   1696 function PromiseMapSeries(promises, fn) {
   1697     return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
   1698 }
   1699 
   1700 Promise.prototype.each = function (fn) {
   1701     return PromiseReduce(this, fn, INTERNAL, 0)
   1702               ._then(promiseAllThis, undefined, undefined, this, undefined);
   1703 };
   1704 
   1705 Promise.prototype.mapSeries = function (fn) {
   1706     return PromiseReduce(this, fn, INTERNAL, INTERNAL);
   1707 };
   1708 
   1709 Promise.each = function (promises, fn) {
   1710     return PromiseReduce(promises, fn, INTERNAL, 0)
   1711               ._then(promiseAllThis, undefined, undefined, promises, undefined);
   1712 };
   1713 
   1714 Promise.mapSeries = PromiseMapSeries;
   1715 };
   1716 
   1717 
   1718 },{}],12:[function(_dereq_,module,exports){
   1719 "use strict";
   1720 var es5 = _dereq_("./es5");
   1721 var Objectfreeze = es5.freeze;
   1722 var util = _dereq_("./util");
   1723 var inherits = util.inherits;
   1724 var notEnumerableProp = util.notEnumerableProp;
   1725 
   1726 function subError(nameProperty, defaultMessage) {
   1727     function SubError(message) {
   1728         if (!(this instanceof SubError)) return new SubError(message);
   1729         notEnumerableProp(this, "message",
   1730             typeof message === "string" ? message : defaultMessage);
   1731         notEnumerableProp(this, "name", nameProperty);
   1732         if (Error.captureStackTrace) {
   1733             Error.captureStackTrace(this, this.constructor);
   1734         } else {
   1735             Error.call(this);
   1736         }
   1737     }
   1738     inherits(SubError, Error);
   1739     return SubError;
   1740 }
   1741 
   1742 var _TypeError, _RangeError;
   1743 var Warning = subError("Warning", "warning");
   1744 var CancellationError = subError("CancellationError", "cancellation error");
   1745 var TimeoutError = subError("TimeoutError", "timeout error");
   1746 var AggregateError = subError("AggregateError", "aggregate error");
   1747 try {
   1748     _TypeError = TypeError;
   1749     _RangeError = RangeError;
   1750 } catch(e) {
   1751     _TypeError = subError("TypeError", "type error");
   1752     _RangeError = subError("RangeError", "range error");
   1753 }
   1754 
   1755 var methods = ("join pop push shift unshift slice filter forEach some " +
   1756     "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
   1757 
   1758 for (var i = 0; i < methods.length; ++i) {
   1759     if (typeof Array.prototype[methods[i]] === "function") {
   1760         AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
   1761     }
   1762 }
   1763 
   1764 es5.defineProperty(AggregateError.prototype, "length", {
   1765     value: 0,
   1766     configurable: false,
   1767     writable: true,
   1768     enumerable: true
   1769 });
   1770 AggregateError.prototype["isOperational"] = true;
   1771 var level = 0;
   1772 AggregateError.prototype.toString = function() {
   1773     var indent = Array(level * 4 + 1).join(" ");
   1774     var ret = "\n" + indent + "AggregateError of:" + "\n";
   1775     level++;
   1776     indent = Array(level * 4 + 1).join(" ");
   1777     for (var i = 0; i < this.length; ++i) {
   1778         var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
   1779         var lines = str.split("\n");
   1780         for (var j = 0; j < lines.length; ++j) {
   1781             lines[j] = indent + lines[j];
   1782         }
   1783         str = lines.join("\n");
   1784         ret += str + "\n";
   1785     }
   1786     level--;
   1787     return ret;
   1788 };
   1789 
   1790 function OperationalError(message) {
   1791     if (!(this instanceof OperationalError))
   1792         return new OperationalError(message);
   1793     notEnumerableProp(this, "name", "OperationalError");
   1794     notEnumerableProp(this, "message", message);
   1795     this.cause = message;
   1796     this["isOperational"] = true;
   1797 
   1798     if (message instanceof Error) {
   1799         notEnumerableProp(this, "message", message.message);
   1800         notEnumerableProp(this, "stack", message.stack);
   1801     } else if (Error.captureStackTrace) {
   1802         Error.captureStackTrace(this, this.constructor);
   1803     }
   1804 
   1805 }
   1806 inherits(OperationalError, Error);
   1807 
   1808 var errorTypes = Error["__BluebirdErrorTypes__"];
   1809 if (!errorTypes) {
   1810     errorTypes = Objectfreeze({
   1811         CancellationError: CancellationError,
   1812         TimeoutError: TimeoutError,
   1813         OperationalError: OperationalError,
   1814         RejectionError: OperationalError,
   1815         AggregateError: AggregateError
   1816     });
   1817     es5.defineProperty(Error, "__BluebirdErrorTypes__", {
   1818         value: errorTypes,
   1819         writable: false,
   1820         enumerable: false,
   1821         configurable: false
   1822     });
   1823 }
   1824 
   1825 module.exports = {
   1826     Error: Error,
   1827     TypeError: _TypeError,
   1828     RangeError: _RangeError,
   1829     CancellationError: errorTypes.CancellationError,
   1830     OperationalError: errorTypes.OperationalError,
   1831     TimeoutError: errorTypes.TimeoutError,
   1832     AggregateError: errorTypes.AggregateError,
   1833     Warning: Warning
   1834 };
   1835 
   1836 },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
   1837 var isES5 = (function(){
   1838     "use strict";
   1839     return this === undefined;
   1840 })();
   1841 
   1842 if (isES5) {
   1843     module.exports = {
   1844         freeze: Object.freeze,
   1845         defineProperty: Object.defineProperty,
   1846         getDescriptor: Object.getOwnPropertyDescriptor,
   1847         keys: Object.keys,
   1848         names: Object.getOwnPropertyNames,
   1849         getPrototypeOf: Object.getPrototypeOf,
   1850         isArray: Array.isArray,
   1851         isES5: isES5,
   1852         propertyIsWritable: function(obj, prop) {
   1853             var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
   1854             return !!(!descriptor || descriptor.writable || descriptor.set);
   1855         }
   1856     };
   1857 } else {
   1858     var has = {}.hasOwnProperty;
   1859     var str = {}.toString;
   1860     var proto = {}.constructor.prototype;
   1861 
   1862     var ObjectKeys = function (o) {
   1863         var ret = [];
   1864         for (var key in o) {
   1865             if (has.call(o, key)) {
   1866                 ret.push(key);
   1867             }
   1868         }
   1869         return ret;
   1870     };
   1871 
   1872     var ObjectGetDescriptor = function(o, key) {
   1873         return {value: o[key]};
   1874     };
   1875 
   1876     var ObjectDefineProperty = function (o, key, desc) {
   1877         o[key] = desc.value;
   1878         return o;
   1879     };
   1880 
   1881     var ObjectFreeze = function (obj) {
   1882         return obj;
   1883     };
   1884 
   1885     var ObjectGetPrototypeOf = function (obj) {
   1886         try {
   1887             return Object(obj).constructor.prototype;
   1888         }
   1889         catch (e) {
   1890             return proto;
   1891         }
   1892     };
   1893 
   1894     var ArrayIsArray = function (obj) {
   1895         try {
   1896             return str.call(obj) === "[object Array]";
   1897         }
   1898         catch(e) {
   1899             return false;
   1900         }
   1901     };
   1902 
   1903     module.exports = {
   1904         isArray: ArrayIsArray,
   1905         keys: ObjectKeys,
   1906         names: ObjectKeys,
   1907         defineProperty: ObjectDefineProperty,
   1908         getDescriptor: ObjectGetDescriptor,
   1909         freeze: ObjectFreeze,
   1910         getPrototypeOf: ObjectGetPrototypeOf,
   1911         isES5: isES5,
   1912         propertyIsWritable: function() {
   1913             return true;
   1914         }
   1915     };
   1916 }
   1917 
   1918 },{}],14:[function(_dereq_,module,exports){
   1919 "use strict";
   1920 module.exports = function(Promise, INTERNAL) {
   1921 var PromiseMap = Promise.map;
   1922 
   1923 Promise.prototype.filter = function (fn, options) {
   1924     return PromiseMap(this, fn, options, INTERNAL);
   1925 };
   1926 
   1927 Promise.filter = function (promises, fn, options) {
   1928     return PromiseMap(promises, fn, options, INTERNAL);
   1929 };
   1930 };
   1931 
   1932 },{}],15:[function(_dereq_,module,exports){
   1933 "use strict";
   1934 module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
   1935 var util = _dereq_("./util");
   1936 var CancellationError = Promise.CancellationError;
   1937 var errorObj = util.errorObj;
   1938 var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
   1939 
   1940 function PassThroughHandlerContext(promise, type, handler) {
   1941     this.promise = promise;
   1942     this.type = type;
   1943     this.handler = handler;
   1944     this.called = false;
   1945     this.cancelPromise = null;
   1946 }
   1947 
   1948 PassThroughHandlerContext.prototype.isFinallyHandler = function() {
   1949     return this.type === 0;
   1950 };
   1951 
   1952 function FinallyHandlerCancelReaction(finallyHandler) {
   1953     this.finallyHandler = finallyHandler;
   1954 }
   1955 
   1956 FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
   1957     checkCancel(this.finallyHandler);
   1958 };
   1959 
   1960 function checkCancel(ctx, reason) {
   1961     if (ctx.cancelPromise != null) {
   1962         if (arguments.length > 1) {
   1963             ctx.cancelPromise._reject(reason);
   1964         } else {
   1965             ctx.cancelPromise._cancel();
   1966         }
   1967         ctx.cancelPromise = null;
   1968         return true;
   1969     }
   1970     return false;
   1971 }
   1972 
   1973 function succeed() {
   1974     return finallyHandler.call(this, this.promise._target()._settledValue());
   1975 }
   1976 function fail(reason) {
   1977     if (checkCancel(this, reason)) return;
   1978     errorObj.e = reason;
   1979     return errorObj;
   1980 }
   1981 function finallyHandler(reasonOrValue) {
   1982     var promise = this.promise;
   1983     var handler = this.handler;
   1984 
   1985     if (!this.called) {
   1986         this.called = true;
   1987         var ret = this.isFinallyHandler()
   1988             ? handler.call(promise._boundValue())
   1989             : handler.call(promise._boundValue(), reasonOrValue);
   1990         if (ret === NEXT_FILTER) {
   1991             return ret;
   1992         } else if (ret !== undefined) {
   1993             promise._setReturnedNonUndefined();
   1994             var maybePromise = tryConvertToPromise(ret, promise);
   1995             if (maybePromise instanceof Promise) {
   1996                 if (this.cancelPromise != null) {
   1997                     if (maybePromise._isCancelled()) {
   1998                         var reason =
   1999                             new CancellationError("late cancellation observer");
   2000                         promise._attachExtraTrace(reason);
   2001                         errorObj.e = reason;
   2002                         return errorObj;
   2003                     } else if (maybePromise.isPending()) {
   2004                         maybePromise._attachCancellationCallback(
   2005                             new FinallyHandlerCancelReaction(this));
   2006                     }
   2007                 }
   2008                 return maybePromise._then(
   2009                     succeed, fail, undefined, this, undefined);
   2010             }
   2011         }
   2012     }
   2013 
   2014     if (promise.isRejected()) {
   2015         checkCancel(this);
   2016         errorObj.e = reasonOrValue;
   2017         return errorObj;
   2018     } else {
   2019         checkCancel(this);
   2020         return reasonOrValue;
   2021     }
   2022 }
   2023 
   2024 Promise.prototype._passThrough = function(handler, type, success, fail) {
   2025     if (typeof handler !== "function") return this.then();
   2026     return this._then(success,
   2027                       fail,
   2028                       undefined,
   2029                       new PassThroughHandlerContext(this, type, handler),
   2030                       undefined);
   2031 };
   2032 
   2033 Promise.prototype.lastly =
   2034 Promise.prototype["finally"] = function (handler) {
   2035     return this._passThrough(handler,
   2036                              0,
   2037                              finallyHandler,
   2038                              finallyHandler);
   2039 };
   2040 
   2041 
   2042 Promise.prototype.tap = function (handler) {
   2043     return this._passThrough(handler, 1, finallyHandler);
   2044 };
   2045 
   2046 Promise.prototype.tapCatch = function (handlerOrPredicate) {
   2047     var len = arguments.length;
   2048     if(len === 1) {
   2049         return this._passThrough(handlerOrPredicate,
   2050                                  1,
   2051                                  undefined,
   2052                                  finallyHandler);
   2053     } else {
   2054          var catchInstances = new Array(len - 1),
   2055             j = 0, i;
   2056         for (i = 0; i < len - 1; ++i) {
   2057             var item = arguments[i];
   2058             if (util.isObject(item)) {
   2059                 catchInstances[j++] = item;
   2060             } else {
   2061                 return Promise.reject(new TypeError(
   2062                     "tapCatch statement predicate: "
   2063                     + "expecting an object but got " + util.classString(item)
   2064                 ));
   2065             }
   2066         }
   2067         catchInstances.length = j;
   2068         var handler = arguments[i];
   2069         return this._passThrough(catchFilter(catchInstances, handler, this),
   2070                                  1,
   2071                                  undefined,
   2072                                  finallyHandler);
   2073     }
   2074 
   2075 };
   2076 
   2077 return PassThroughHandlerContext;
   2078 };
   2079 
   2080 },{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){
   2081 "use strict";
   2082 module.exports = function(Promise,
   2083                           apiRejection,
   2084                           INTERNAL,
   2085                           tryConvertToPromise,
   2086                           Proxyable,
   2087                           debug) {
   2088 var errors = _dereq_("./errors");
   2089 var TypeError = errors.TypeError;
   2090 var util = _dereq_("./util");
   2091 var errorObj = util.errorObj;
   2092 var tryCatch = util.tryCatch;
   2093 var yieldHandlers = [];
   2094 
   2095 function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
   2096     for (var i = 0; i < yieldHandlers.length; ++i) {
   2097         traceParent._pushContext();
   2098         var result = tryCatch(yieldHandlers[i])(value);
   2099         traceParent._popContext();
   2100         if (result === errorObj) {
   2101             traceParent._pushContext();
   2102             var ret = Promise.reject(errorObj.e);
   2103             traceParent._popContext();
   2104             return ret;
   2105         }
   2106         var maybePromise = tryConvertToPromise(result, traceParent);
   2107         if (maybePromise instanceof Promise) return maybePromise;
   2108     }
   2109     return null;
   2110 }
   2111 
   2112 function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
   2113     if (debug.cancellation()) {
   2114         var internal = new Promise(INTERNAL);
   2115         var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
   2116         this._promise = internal.lastly(function() {
   2117             return _finallyPromise;
   2118         });
   2119         internal._captureStackTrace();
   2120         internal._setOnCancel(this);
   2121     } else {
   2122         var promise = this._promise = new Promise(INTERNAL);
   2123         promise._captureStackTrace();
   2124     }
   2125     this._stack = stack;
   2126     this._generatorFunction = generatorFunction;
   2127     this._receiver = receiver;
   2128     this._generator = undefined;
   2129     this._yieldHandlers = typeof yieldHandler === "function"
   2130         ? [yieldHandler].concat(yieldHandlers)
   2131         : yieldHandlers;
   2132     this._yieldedPromise = null;
   2133     this._cancellationPhase = false;
   2134 }
   2135 util.inherits(PromiseSpawn, Proxyable);
   2136 
   2137 PromiseSpawn.prototype._isResolved = function() {
   2138     return this._promise === null;
   2139 };
   2140 
   2141 PromiseSpawn.prototype._cleanup = function() {
   2142     this._promise = this._generator = null;
   2143     if (debug.cancellation() && this._finallyPromise !== null) {
   2144         this._finallyPromise._fulfill();
   2145         this._finallyPromise = null;
   2146     }
   2147 };
   2148 
   2149 PromiseSpawn.prototype._promiseCancelled = function() {
   2150     if (this._isResolved()) return;
   2151     var implementsReturn = typeof this._generator["return"] !== "undefined";
   2152 
   2153     var result;
   2154     if (!implementsReturn) {
   2155         var reason = new Promise.CancellationError(
   2156             "generator .return() sentinel");
   2157         Promise.coroutine.returnSentinel = reason;
   2158         this._promise._attachExtraTrace(reason);
   2159         this._promise._pushContext();
   2160         result = tryCatch(this._generator["throw"]).call(this._generator,
   2161                                                          reason);
   2162         this._promise._popContext();
   2163     } else {
   2164         this._promise._pushContext();
   2165         result = tryCatch(this._generator["return"]).call(this._generator,
   2166                                                           undefined);
   2167         this._promise._popContext();
   2168     }
   2169     this._cancellationPhase = true;
   2170     this._yieldedPromise = null;
   2171     this._continue(result);
   2172 };
   2173 
   2174 PromiseSpawn.prototype._promiseFulfilled = function(value) {
   2175     this._yieldedPromise = null;
   2176     this._promise._pushContext();
   2177     var result = tryCatch(this._generator.next).call(this._generator, value);
   2178     this._promise._popContext();
   2179     this._continue(result);
   2180 };
   2181 
   2182 PromiseSpawn.prototype._promiseRejected = function(reason) {
   2183     this._yieldedPromise = null;
   2184     this._promise._attachExtraTrace(reason);
   2185     this._promise._pushContext();
   2186     var result = tryCatch(this._generator["throw"])
   2187         .call(this._generator, reason);
   2188     this._promise._popContext();
   2189     this._continue(result);
   2190 };
   2191 
   2192 PromiseSpawn.prototype._resultCancelled = function() {
   2193     if (this._yieldedPromise instanceof Promise) {
   2194         var promise = this._yieldedPromise;
   2195         this._yieldedPromise = null;
   2196         promise.cancel();
   2197     }
   2198 };
   2199 
   2200 PromiseSpawn.prototype.promise = function () {
   2201     return this._promise;
   2202 };
   2203 
   2204 PromiseSpawn.prototype._run = function () {
   2205     this._generator = this._generatorFunction.call(this._receiver);
   2206     this._receiver =
   2207         this._generatorFunction = undefined;
   2208     this._promiseFulfilled(undefined);
   2209 };
   2210 
   2211 PromiseSpawn.prototype._continue = function (result) {
   2212     var promise = this._promise;
   2213     if (result === errorObj) {
   2214         this._cleanup();
   2215         if (this._cancellationPhase) {
   2216             return promise.cancel();
   2217         } else {
   2218             return promise._rejectCallback(result.e, false);
   2219         }
   2220     }
   2221 
   2222     var value = result.value;
   2223     if (result.done === true) {
   2224         this._cleanup();
   2225         if (this._cancellationPhase) {
   2226             return promise.cancel();
   2227         } else {
   2228             return promise._resolveCallback(value);
   2229         }
   2230     } else {
   2231         var maybePromise = tryConvertToPromise(value, this._promise);
   2232         if (!(maybePromise instanceof Promise)) {
   2233             maybePromise =
   2234                 promiseFromYieldHandler(maybePromise,
   2235                                         this._yieldHandlers,
   2236                                         this._promise);
   2237             if (maybePromise === null) {
   2238                 this._promiseRejected(
   2239                     new TypeError(
   2240                         "A value %s was yielded that could not be treated as a promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) +
   2241                         "From coroutine:\u000a" +
   2242                         this._stack.split("\n").slice(1, -7).join("\n")
   2243                     )
   2244                 );
   2245                 return;
   2246             }
   2247         }
   2248         maybePromise = maybePromise._target();
   2249         var bitField = maybePromise._bitField;
   2250         ;
   2251         if (((bitField & 50397184) === 0)) {
   2252             this._yieldedPromise = maybePromise;
   2253             maybePromise._proxy(this, null);
   2254         } else if (((bitField & 33554432) !== 0)) {
   2255             Promise._async.invoke(
   2256                 this._promiseFulfilled, this, maybePromise._value()
   2257             );
   2258         } else if (((bitField & 16777216) !== 0)) {
   2259             Promise._async.invoke(
   2260                 this._promiseRejected, this, maybePromise._reason()
   2261             );
   2262         } else {
   2263             this._promiseCancelled();
   2264         }
   2265     }
   2266 };
   2267 
   2268 Promise.coroutine = function (generatorFunction, options) {
   2269     if (typeof generatorFunction !== "function") {
   2270         throw new TypeError("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   2271     }
   2272     var yieldHandler = Object(options).yieldHandler;
   2273     var PromiseSpawn$ = PromiseSpawn;
   2274     var stack = new Error().stack;
   2275     return function () {
   2276         var generator = generatorFunction.apply(this, arguments);
   2277         var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
   2278                                       stack);
   2279         var ret = spawn.promise();
   2280         spawn._generator = generator;
   2281         spawn._promiseFulfilled(undefined);
   2282         return ret;
   2283     };
   2284 };
   2285 
   2286 Promise.coroutine.addYieldHandler = function(fn) {
   2287     if (typeof fn !== "function") {
   2288         throw new TypeError("expecting a function but got " + util.classString(fn));
   2289     }
   2290     yieldHandlers.push(fn);
   2291 };
   2292 
   2293 Promise.spawn = function (generatorFunction) {
   2294     debug.deprecated("Promise.spawn()", "Promise.coroutine()");
   2295     if (typeof generatorFunction !== "function") {
   2296         return apiRejection("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   2297     }
   2298     var spawn = new PromiseSpawn(generatorFunction, this);
   2299     var ret = spawn.promise();
   2300     spawn._run(Promise.spawn);
   2301     return ret;
   2302 };
   2303 };
   2304 
   2305 },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
   2306 "use strict";
   2307 module.exports =
   2308 function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) {
   2309 var util = _dereq_("./util");
   2310 var canEvaluate = util.canEvaluate;
   2311 var tryCatch = util.tryCatch;
   2312 var errorObj = util.errorObj;
   2313 var reject;
   2314 
   2315 if (!true) {
   2316 if (canEvaluate) {
   2317     var thenCallback = function(i) {
   2318         return new Function("value", "holder", "                             \n\
   2319             'use strict';                                                    \n\
   2320             holder.pIndex = value;                                           \n\
   2321             holder.checkFulfillment(this);                                   \n\
   2322             ".replace(/Index/g, i));
   2323     };
   2324 
   2325     var promiseSetter = function(i) {
   2326         return new Function("promise", "holder", "                           \n\
   2327             'use strict';                                                    \n\
   2328             holder.pIndex = promise;                                         \n\
   2329             ".replace(/Index/g, i));
   2330     };
   2331 
   2332     var generateHolderClass = function(total) {
   2333         var props = new Array(total);
   2334         for (var i = 0; i < props.length; ++i) {
   2335             props[i] = "this.p" + (i+1);
   2336         }
   2337         var assignment = props.join(" = ") + " = null;";
   2338         var cancellationCode= "var promise;\n" + props.map(function(prop) {
   2339             return "                                                         \n\
   2340                 promise = " + prop + ";                                      \n\
   2341                 if (promise instanceof Promise) {                            \n\
   2342                     promise.cancel();                                        \n\
   2343                 }                                                            \n\
   2344             ";
   2345         }).join("\n");
   2346         var passedArguments = props.join(", ");
   2347         var name = "Holder$" + total;
   2348 
   2349 
   2350         var code = "return function(tryCatch, errorObj, Promise, async) {    \n\
   2351             'use strict';                                                    \n\
   2352             function [TheName](fn) {                                         \n\
   2353                 [TheProperties]                                              \n\
   2354                 this.fn = fn;                                                \n\
   2355                 this.asyncNeeded = true;                                     \n\
   2356                 this.now = 0;                                                \n\
   2357             }                                                                \n\
   2358                                                                              \n\
   2359             [TheName].prototype._callFunction = function(promise) {          \n\
   2360                 promise._pushContext();                                      \n\
   2361                 var ret = tryCatch(this.fn)([ThePassedArguments]);           \n\
   2362                 promise._popContext();                                       \n\
   2363                 if (ret === errorObj) {                                      \n\
   2364                     promise._rejectCallback(ret.e, false);                   \n\
   2365                 } else {                                                     \n\
   2366                     promise._resolveCallback(ret);                           \n\
   2367                 }                                                            \n\
   2368             };                                                               \n\
   2369                                                                              \n\
   2370             [TheName].prototype.checkFulfillment = function(promise) {       \n\
   2371                 var now = ++this.now;                                        \n\
   2372                 if (now === [TheTotal]) {                                    \n\
   2373                     if (this.asyncNeeded) {                                  \n\
   2374                         async.invoke(this._callFunction, this, promise);     \n\
   2375                     } else {                                                 \n\
   2376                         this._callFunction(promise);                         \n\
   2377                     }                                                        \n\
   2378                                                                              \n\
   2379                 }                                                            \n\
   2380             };                                                               \n\
   2381                                                                              \n\
   2382             [TheName].prototype._resultCancelled = function() {              \n\
   2383                 [CancellationCode]                                           \n\
   2384             };                                                               \n\
   2385                                                                              \n\
   2386             return [TheName];                                                \n\
   2387         }(tryCatch, errorObj, Promise, async);                               \n\
   2388         ";
   2389 
   2390         code = code.replace(/\[TheName\]/g, name)
   2391             .replace(/\[TheTotal\]/g, total)
   2392             .replace(/\[ThePassedArguments\]/g, passedArguments)
   2393             .replace(/\[TheProperties\]/g, assignment)
   2394             .replace(/\[CancellationCode\]/g, cancellationCode);
   2395 
   2396         return new Function("tryCatch", "errorObj", "Promise", "async", code)
   2397                            (tryCatch, errorObj, Promise, async);
   2398     };
   2399 
   2400     var holderClasses = [];
   2401     var thenCallbacks = [];
   2402     var promiseSetters = [];
   2403 
   2404     for (var i = 0; i < 8; ++i) {
   2405         holderClasses.push(generateHolderClass(i + 1));
   2406         thenCallbacks.push(thenCallback(i + 1));
   2407         promiseSetters.push(promiseSetter(i + 1));
   2408     }
   2409 
   2410     reject = function (reason) {
   2411         this._reject(reason);
   2412     };
   2413 }}
   2414 
   2415 Promise.join = function () {
   2416     var last = arguments.length - 1;
   2417     var fn;
   2418     if (last > 0 && typeof arguments[last] === "function") {
   2419         fn = arguments[last];
   2420         if (!true) {
   2421             if (last <= 8 && canEvaluate) {
   2422                 var ret = new Promise(INTERNAL);
   2423                 ret._captureStackTrace();
   2424                 var HolderClass = holderClasses[last - 1];
   2425                 var holder = new HolderClass(fn);
   2426                 var callbacks = thenCallbacks;
   2427 
   2428                 for (var i = 0; i < last; ++i) {
   2429                     var maybePromise = tryConvertToPromise(arguments[i], ret);
   2430                     if (maybePromise instanceof Promise) {
   2431                         maybePromise = maybePromise._target();
   2432                         var bitField = maybePromise._bitField;
   2433                         ;
   2434                         if (((bitField & 50397184) === 0)) {
   2435                             maybePromise._then(callbacks[i], reject,
   2436                                                undefined, ret, holder);
   2437                             promiseSetters[i](maybePromise, holder);
   2438                             holder.asyncNeeded = false;
   2439                         } else if (((bitField & 33554432) !== 0)) {
   2440                             callbacks[i].call(ret,
   2441                                               maybePromise._value(), holder);
   2442                         } else if (((bitField & 16777216) !== 0)) {
   2443                             ret._reject(maybePromise._reason());
   2444                         } else {
   2445                             ret._cancel();
   2446                         }
   2447                     } else {
   2448                         callbacks[i].call(ret, maybePromise, holder);
   2449                     }
   2450                 }
   2451 
   2452                 if (!ret._isFateSealed()) {
   2453                     if (holder.asyncNeeded) {
   2454                         var context = Promise._getContext();
   2455                         holder.fn = util.contextBind(context, holder.fn);
   2456                     }
   2457                     ret._setAsyncGuaranteed();
   2458                     ret._setOnCancel(holder);
   2459                 }
   2460                 return ret;
   2461             }
   2462         }
   2463     }
   2464     var args = [].slice.call(arguments);;
   2465     if (fn) args.pop();
   2466     var ret = new PromiseArray(args).promise();
   2467     return fn !== undefined ? ret.spread(fn) : ret;
   2468 };
   2469 
   2470 };
   2471 
   2472 },{"./util":36}],18:[function(_dereq_,module,exports){
   2473 "use strict";
   2474 module.exports = function(Promise,
   2475                           PromiseArray,
   2476                           apiRejection,
   2477                           tryConvertToPromise,
   2478                           INTERNAL,
   2479                           debug) {
   2480 var util = _dereq_("./util");
   2481 var tryCatch = util.tryCatch;
   2482 var errorObj = util.errorObj;
   2483 var async = Promise._async;
   2484 
   2485 function MappingPromiseArray(promises, fn, limit, _filter) {
   2486     this.constructor$(promises);
   2487     this._promise._captureStackTrace();
   2488     var context = Promise._getContext();
   2489     this._callback = util.contextBind(context, fn);
   2490     this._preservedValues = _filter === INTERNAL
   2491         ? new Array(this.length())
   2492         : null;
   2493     this._limit = limit;
   2494     this._inFlight = 0;
   2495     this._queue = [];
   2496     async.invoke(this._asyncInit, this, undefined);
   2497     if (util.isArray(promises)) {
   2498         for (var i = 0; i < promises.length; ++i) {
   2499             var maybePromise = promises[i];
   2500             if (maybePromise instanceof Promise) {
   2501                 maybePromise.suppressUnhandledRejections();
   2502             }
   2503         }
   2504     }
   2505 }
   2506 util.inherits(MappingPromiseArray, PromiseArray);
   2507 
   2508 MappingPromiseArray.prototype._asyncInit = function() {
   2509     this._init$(undefined, -2);
   2510 };
   2511 
   2512 MappingPromiseArray.prototype._init = function () {};
   2513 
   2514 MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
   2515     var values = this._values;
   2516     var length = this.length();
   2517     var preservedValues = this._preservedValues;
   2518     var limit = this._limit;
   2519 
   2520     if (index < 0) {
   2521         index = (index * -1) - 1;
   2522         values[index] = value;
   2523         if (limit >= 1) {
   2524             this._inFlight--;
   2525             this._drainQueue();
   2526             if (this._isResolved()) return true;
   2527         }
   2528     } else {
   2529         if (limit >= 1 && this._inFlight >= limit) {
   2530             values[index] = value;
   2531             this._queue.push(index);
   2532             return false;
   2533         }
   2534         if (preservedValues !== null) preservedValues[index] = value;
   2535 
   2536         var promise = this._promise;
   2537         var callback = this._callback;
   2538         var receiver = promise._boundValue();
   2539         promise._pushContext();
   2540         var ret = tryCatch(callback).call(receiver, value, index, length);
   2541         var promiseCreated = promise._popContext();
   2542         debug.checkForgottenReturns(
   2543             ret,
   2544             promiseCreated,
   2545             preservedValues !== null ? "Promise.filter" : "Promise.map",
   2546             promise
   2547         );
   2548         if (ret === errorObj) {
   2549             this._reject(ret.e);
   2550             return true;
   2551         }
   2552 
   2553         var maybePromise = tryConvertToPromise(ret, this._promise);
   2554         if (maybePromise instanceof Promise) {
   2555             maybePromise = maybePromise._target();
   2556             var bitField = maybePromise._bitField;
   2557             ;
   2558             if (((bitField & 50397184) === 0)) {
   2559                 if (limit >= 1) this._inFlight++;
   2560                 values[index] = maybePromise;
   2561                 maybePromise._proxy(this, (index + 1) * -1);
   2562                 return false;
   2563             } else if (((bitField & 33554432) !== 0)) {
   2564                 ret = maybePromise._value();
   2565             } else if (((bitField & 16777216) !== 0)) {
   2566                 this._reject(maybePromise._reason());
   2567                 return true;
   2568             } else {
   2569                 this._cancel();
   2570                 return true;
   2571             }
   2572         }
   2573         values[index] = ret;
   2574     }
   2575     var totalResolved = ++this._totalResolved;
   2576     if (totalResolved >= length) {
   2577         if (preservedValues !== null) {
   2578             this._filter(values, preservedValues);
   2579         } else {
   2580             this._resolve(values);
   2581         }
   2582         return true;
   2583     }
   2584     return false;
   2585 };
   2586 
   2587 MappingPromiseArray.prototype._drainQueue = function () {
   2588     var queue = this._queue;
   2589     var limit = this._limit;
   2590     var values = this._values;
   2591     while (queue.length > 0 && this._inFlight < limit) {
   2592         if (this._isResolved()) return;
   2593         var index = queue.pop();
   2594         this._promiseFulfilled(values[index], index);
   2595     }
   2596 };
   2597 
   2598 MappingPromiseArray.prototype._filter = function (booleans, values) {
   2599     var len = values.length;
   2600     var ret = new Array(len);
   2601     var j = 0;
   2602     for (var i = 0; i < len; ++i) {
   2603         if (booleans[i]) ret[j++] = values[i];
   2604     }
   2605     ret.length = j;
   2606     this._resolve(ret);
   2607 };
   2608 
   2609 MappingPromiseArray.prototype.preservedValues = function () {
   2610     return this._preservedValues;
   2611 };
   2612 
   2613 function map(promises, fn, options, _filter) {
   2614     if (typeof fn !== "function") {
   2615         return apiRejection("expecting a function but got " + util.classString(fn));
   2616     }
   2617 
   2618     var limit = 0;
   2619     if (options !== undefined) {
   2620         if (typeof options === "object" && options !== null) {
   2621             if (typeof options.concurrency !== "number") {
   2622                 return Promise.reject(
   2623                     new TypeError("'concurrency' must be a number but it is " +
   2624                                     util.classString(options.concurrency)));
   2625             }
   2626             limit = options.concurrency;
   2627         } else {
   2628             return Promise.reject(new TypeError(
   2629                             "options argument must be an object but it is " +
   2630                              util.classString(options)));
   2631         }
   2632     }
   2633     limit = typeof limit === "number" &&
   2634         isFinite(limit) && limit >= 1 ? limit : 0;
   2635     return new MappingPromiseArray(promises, fn, limit, _filter).promise();
   2636 }
   2637 
   2638 Promise.prototype.map = function (fn, options) {
   2639     return map(this, fn, options, null);
   2640 };
   2641 
   2642 Promise.map = function (promises, fn, options, _filter) {
   2643     return map(promises, fn, options, _filter);
   2644 };
   2645 
   2646 
   2647 };
   2648 
   2649 },{"./util":36}],19:[function(_dereq_,module,exports){
   2650 "use strict";
   2651 module.exports =
   2652 function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
   2653 var util = _dereq_("./util");
   2654 var tryCatch = util.tryCatch;
   2655 
   2656 Promise.method = function (fn) {
   2657     if (typeof fn !== "function") {
   2658         throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
   2659     }
   2660     return function () {
   2661         var ret = new Promise(INTERNAL);
   2662         ret._captureStackTrace();
   2663         ret._pushContext();
   2664         var value = tryCatch(fn).apply(this, arguments);
   2665         var promiseCreated = ret._popContext();
   2666         debug.checkForgottenReturns(
   2667             value, promiseCreated, "Promise.method", ret);
   2668         ret._resolveFromSyncValue(value);
   2669         return ret;
   2670     };
   2671 };
   2672 
   2673 Promise.attempt = Promise["try"] = function (fn) {
   2674     if (typeof fn !== "function") {
   2675         return apiRejection("expecting a function but got " + util.classString(fn));
   2676     }
   2677     var ret = new Promise(INTERNAL);
   2678     ret._captureStackTrace();
   2679     ret._pushContext();
   2680     var value;
   2681     if (arguments.length > 1) {
   2682         debug.deprecated("calling Promise.try with more than 1 argument");
   2683         var arg = arguments[1];
   2684         var ctx = arguments[2];
   2685         value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
   2686                                   : tryCatch(fn).call(ctx, arg);
   2687     } else {
   2688         value = tryCatch(fn)();
   2689     }
   2690     var promiseCreated = ret._popContext();
   2691     debug.checkForgottenReturns(
   2692         value, promiseCreated, "Promise.try", ret);
   2693     ret._resolveFromSyncValue(value);
   2694     return ret;
   2695 };
   2696 
   2697 Promise.prototype._resolveFromSyncValue = function (value) {
   2698     if (value === util.errorObj) {
   2699         this._rejectCallback(value.e, false);
   2700     } else {
   2701         this._resolveCallback(value, true);
   2702     }
   2703 };
   2704 };
   2705 
   2706 },{"./util":36}],20:[function(_dereq_,module,exports){
   2707 "use strict";
   2708 var util = _dereq_("./util");
   2709 var maybeWrapAsError = util.maybeWrapAsError;
   2710 var errors = _dereq_("./errors");
   2711 var OperationalError = errors.OperationalError;
   2712 var es5 = _dereq_("./es5");
   2713 
   2714 function isUntypedError(obj) {
   2715     return obj instanceof Error &&
   2716         es5.getPrototypeOf(obj) === Error.prototype;
   2717 }
   2718 
   2719 var rErrorKey = /^(?:name|message|stack|cause)$/;
   2720 function wrapAsOperationalError(obj) {
   2721     var ret;
   2722     if (isUntypedError(obj)) {
   2723         ret = new OperationalError(obj);
   2724         ret.name = obj.name;
   2725         ret.message = obj.message;
   2726         ret.stack = obj.stack;
   2727         var keys = es5.keys(obj);
   2728         for (var i = 0; i < keys.length; ++i) {
   2729             var key = keys[i];
   2730             if (!rErrorKey.test(key)) {
   2731                 ret[key] = obj[key];
   2732             }
   2733         }
   2734         return ret;
   2735     }
   2736     util.markAsOriginatingFromRejection(obj);
   2737     return obj;
   2738 }
   2739 
   2740 function nodebackForPromise(promise, multiArgs) {
   2741     return function(err, value) {
   2742         if (promise === null) return;
   2743         if (err) {
   2744             var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
   2745             promise._attachExtraTrace(wrapped);
   2746             promise._reject(wrapped);
   2747         } else if (!multiArgs) {
   2748             promise._fulfill(value);
   2749         } else {
   2750             var args = [].slice.call(arguments, 1);;
   2751             promise._fulfill(args);
   2752         }
   2753         promise = null;
   2754     };
   2755 }
   2756 
   2757 module.exports = nodebackForPromise;
   2758 
   2759 },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
   2760 "use strict";
   2761 module.exports = function(Promise) {
   2762 var util = _dereq_("./util");
   2763 var async = Promise._async;
   2764 var tryCatch = util.tryCatch;
   2765 var errorObj = util.errorObj;
   2766 
   2767 function spreadAdapter(val, nodeback) {
   2768     var promise = this;
   2769     if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
   2770     var ret =
   2771         tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
   2772     if (ret === errorObj) {
   2773         async.throwLater(ret.e);
   2774     }
   2775 }
   2776 
   2777 function successAdapter(val, nodeback) {
   2778     var promise = this;
   2779     var receiver = promise._boundValue();
   2780     var ret = val === undefined
   2781         ? tryCatch(nodeback).call(receiver, null)
   2782         : tryCatch(nodeback).call(receiver, null, val);
   2783     if (ret === errorObj) {
   2784         async.throwLater(ret.e);
   2785     }
   2786 }
   2787 function errorAdapter(reason, nodeback) {
   2788     var promise = this;
   2789     if (!reason) {
   2790         var newReason = new Error(reason + "");
   2791         newReason.cause = reason;
   2792         reason = newReason;
   2793     }
   2794     var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
   2795     if (ret === errorObj) {
   2796         async.throwLater(ret.e);
   2797     }
   2798 }
   2799 
   2800 Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
   2801                                                                      options) {
   2802     if (typeof nodeback == "function") {
   2803         var adapter = successAdapter;
   2804         if (options !== undefined && Object(options).spread) {
   2805             adapter = spreadAdapter;
   2806         }
   2807         this._then(
   2808             adapter,
   2809             errorAdapter,
   2810             undefined,
   2811             this,
   2812             nodeback
   2813         );
   2814     }
   2815     return this;
   2816 };
   2817 };
   2818 
   2819 },{"./util":36}],22:[function(_dereq_,module,exports){
   2820 "use strict";
   2821 module.exports = function() {
   2822 var makeSelfResolutionError = function () {
   2823     return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   2824 };
   2825 var reflectHandler = function() {
   2826     return new Promise.PromiseInspection(this._target());
   2827 };
   2828 var apiRejection = function(msg) {
   2829     return Promise.reject(new TypeError(msg));
   2830 };
   2831 function Proxyable() {}
   2832 var UNDEFINED_BINDING = {};
   2833 var util = _dereq_("./util");
   2834 util.setReflectHandler(reflectHandler);
   2835 
   2836 var getDomain = function() {
   2837     var domain = process.domain;
   2838     if (domain === undefined) {
   2839         return null;
   2840     }
   2841     return domain;
   2842 };
   2843 var getContextDefault = function() {
   2844     return null;
   2845 };
   2846 var getContextDomain = function() {
   2847     return {
   2848         domain: getDomain(),
   2849         async: null
   2850     };
   2851 };
   2852 var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ?
   2853     _dereq_("async_hooks").AsyncResource : null;
   2854 var getContextAsyncHooks = function() {
   2855     return {
   2856         domain: getDomain(),
   2857         async: new AsyncResource("Bluebird::Promise")
   2858     };
   2859 };
   2860 var getContext = util.isNode ? getContextDomain : getContextDefault;
   2861 util.notEnumerableProp(Promise, "_getContext", getContext);
   2862 var enableAsyncHooks = function() {
   2863     getContext = getContextAsyncHooks;
   2864     util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
   2865 };
   2866 var disableAsyncHooks = function() {
   2867     getContext = getContextDomain;
   2868     util.notEnumerableProp(Promise, "_getContext", getContextDomain);
   2869 };
   2870 
   2871 var es5 = _dereq_("./es5");
   2872 var Async = _dereq_("./async");
   2873 var async = new Async();
   2874 es5.defineProperty(Promise, "_async", {value: async});
   2875 var errors = _dereq_("./errors");
   2876 var TypeError = Promise.TypeError = errors.TypeError;
   2877 Promise.RangeError = errors.RangeError;
   2878 var CancellationError = Promise.CancellationError = errors.CancellationError;
   2879 Promise.TimeoutError = errors.TimeoutError;
   2880 Promise.OperationalError = errors.OperationalError;
   2881 Promise.RejectionError = errors.OperationalError;
   2882 Promise.AggregateError = errors.AggregateError;
   2883 var INTERNAL = function(){};
   2884 var APPLY = {};
   2885 var NEXT_FILTER = {};
   2886 var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
   2887 var PromiseArray =
   2888     _dereq_("./promise_array")(Promise, INTERNAL,
   2889                                tryConvertToPromise, apiRejection, Proxyable);
   2890 var Context = _dereq_("./context")(Promise);
   2891  /*jshint unused:false*/
   2892 var createContext = Context.create;
   2893 
   2894 var debug = _dereq_("./debuggability")(Promise, Context,
   2895     enableAsyncHooks, disableAsyncHooks);
   2896 var CapturedTrace = debug.CapturedTrace;
   2897 var PassThroughHandlerContext =
   2898     _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
   2899 var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
   2900 var nodebackForPromise = _dereq_("./nodeback");
   2901 var errorObj = util.errorObj;
   2902 var tryCatch = util.tryCatch;
   2903 function check(self, executor) {
   2904     if (self == null || self.constructor !== Promise) {
   2905         throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   2906     }
   2907     if (typeof executor !== "function") {
   2908         throw new TypeError("expecting a function but got " + util.classString(executor));
   2909     }
   2910 
   2911 }
   2912 
   2913 function Promise(executor) {
   2914     if (executor !== INTERNAL) {
   2915         check(this, executor);
   2916     }
   2917     this._bitField = 0;
   2918     this._fulfillmentHandler0 = undefined;
   2919     this._rejectionHandler0 = undefined;
   2920     this._promise0 = undefined;
   2921     this._receiver0 = undefined;
   2922     this._resolveFromExecutor(executor);
   2923     this._promiseCreated();
   2924     this._fireEvent("promiseCreated", this);
   2925 }
   2926 
   2927 Promise.prototype.toString = function () {
   2928     return "[object Promise]";
   2929 };
   2930 
   2931 Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
   2932     var len = arguments.length;
   2933     if (len > 1) {
   2934         var catchInstances = new Array(len - 1),
   2935             j = 0, i;
   2936         for (i = 0; i < len - 1; ++i) {
   2937             var item = arguments[i];
   2938             if (util.isObject(item)) {
   2939                 catchInstances[j++] = item;
   2940             } else {
   2941                 return apiRejection("Catch statement predicate: " +
   2942                     "expecting an object but got " + util.classString(item));
   2943             }
   2944         }
   2945         catchInstances.length = j;
   2946         fn = arguments[i];
   2947 
   2948         if (typeof fn !== "function") {
   2949             throw new TypeError("The last argument to .catch() " +
   2950                 "must be a function, got " + util.toString(fn));
   2951         }
   2952         return this.then(undefined, catchFilter(catchInstances, fn, this));
   2953     }
   2954     return this.then(undefined, fn);
   2955 };
   2956 
   2957 Promise.prototype.reflect = function () {
   2958     return this._then(reflectHandler,
   2959         reflectHandler, undefined, this, undefined);
   2960 };
   2961 
   2962 Promise.prototype.then = function (didFulfill, didReject) {
   2963     if (debug.warnings() && arguments.length > 0 &&
   2964         typeof didFulfill !== "function" &&
   2965         typeof didReject !== "function") {
   2966         var msg = ".then() only accepts functions but was passed: " +
   2967                 util.classString(didFulfill);
   2968         if (arguments.length > 1) {
   2969             msg += ", " + util.classString(didReject);
   2970         }
   2971         this._warn(msg);
   2972     }
   2973     return this._then(didFulfill, didReject, undefined, undefined, undefined);
   2974 };
   2975 
   2976 Promise.prototype.done = function (didFulfill, didReject) {
   2977     var promise =
   2978         this._then(didFulfill, didReject, undefined, undefined, undefined);
   2979     promise._setIsFinal();
   2980 };
   2981 
   2982 Promise.prototype.spread = function (fn) {
   2983     if (typeof fn !== "function") {
   2984         return apiRejection("expecting a function but got " + util.classString(fn));
   2985     }
   2986     return this.all()._then(fn, undefined, undefined, APPLY, undefined);
   2987 };
   2988 
   2989 Promise.prototype.toJSON = function () {
   2990     var ret = {
   2991         isFulfilled: false,
   2992         isRejected: false,
   2993         fulfillmentValue: undefined,
   2994         rejectionReason: undefined
   2995     };
   2996     if (this.isFulfilled()) {
   2997         ret.fulfillmentValue = this.value();
   2998         ret.isFulfilled = true;
   2999     } else if (this.isRejected()) {
   3000         ret.rejectionReason = this.reason();
   3001         ret.isRejected = true;
   3002     }
   3003     return ret;
   3004 };
   3005 
   3006 Promise.prototype.all = function () {
   3007     if (arguments.length > 0) {
   3008         this._warn(".all() was passed arguments but it does not take any");
   3009     }
   3010     return new PromiseArray(this).promise();
   3011 };
   3012 
   3013 Promise.prototype.error = function (fn) {
   3014     return this.caught(util.originatesFromRejection, fn);
   3015 };
   3016 
   3017 Promise.getNewLibraryCopy = module.exports;
   3018 
   3019 Promise.is = function (val) {
   3020     return val instanceof Promise;
   3021 };
   3022 
   3023 Promise.fromNode = Promise.fromCallback = function(fn) {
   3024     var ret = new Promise(INTERNAL);
   3025     ret._captureStackTrace();
   3026     var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
   3027                                          : false;
   3028     var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
   3029     if (result === errorObj) {
   3030         ret._rejectCallback(result.e, true);
   3031     }
   3032     if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
   3033     return ret;
   3034 };
   3035 
   3036 Promise.all = function (promises) {
   3037     return new PromiseArray(promises).promise();
   3038 };
   3039 
   3040 Promise.cast = function (obj) {
   3041     var ret = tryConvertToPromise(obj);
   3042     if (!(ret instanceof Promise)) {
   3043         ret = new Promise(INTERNAL);
   3044         ret._captureStackTrace();
   3045         ret._setFulfilled();
   3046         ret._rejectionHandler0 = obj;
   3047     }
   3048     return ret;
   3049 };
   3050 
   3051 Promise.resolve = Promise.fulfilled = Promise.cast;
   3052 
   3053 Promise.reject = Promise.rejected = function (reason) {
   3054     var ret = new Promise(INTERNAL);
   3055     ret._captureStackTrace();
   3056     ret._rejectCallback(reason, true);
   3057     return ret;
   3058 };
   3059 
   3060 Promise.setScheduler = function(fn) {
   3061     if (typeof fn !== "function") {
   3062         throw new TypeError("expecting a function but got " + util.classString(fn));
   3063     }
   3064     return async.setScheduler(fn);
   3065 };
   3066 
   3067 Promise.prototype._then = function (
   3068     didFulfill,
   3069     didReject,
   3070     _,    receiver,
   3071     internalData
   3072 ) {
   3073     var haveInternalData = internalData !== undefined;
   3074     var promise = haveInternalData ? internalData : new Promise(INTERNAL);
   3075     var target = this._target();
   3076     var bitField = target._bitField;
   3077 
   3078     if (!haveInternalData) {
   3079         promise._propagateFrom(this, 3);
   3080         promise._captureStackTrace();
   3081         if (receiver === undefined &&
   3082             ((this._bitField & 2097152) !== 0)) {
   3083             if (!((bitField & 50397184) === 0)) {
   3084                 receiver = this._boundValue();
   3085             } else {
   3086                 receiver = target === this ? undefined : this._boundTo;
   3087             }
   3088         }
   3089         this._fireEvent("promiseChained", this, promise);
   3090     }
   3091 
   3092     var context = getContext();
   3093     if (!((bitField & 50397184) === 0)) {
   3094         var handler, value, settler = target._settlePromiseCtx;
   3095         if (((bitField & 33554432) !== 0)) {
   3096             value = target._rejectionHandler0;
   3097             handler = didFulfill;
   3098         } else if (((bitField & 16777216) !== 0)) {
   3099             value = target._fulfillmentHandler0;
   3100             handler = didReject;
   3101             target._unsetRejectionIsUnhandled();
   3102         } else {
   3103             settler = target._settlePromiseLateCancellationObserver;
   3104             value = new CancellationError("late cancellation observer");
   3105             target._attachExtraTrace(value);
   3106             handler = didReject;
   3107         }
   3108 
   3109         async.invoke(settler, target, {
   3110             handler: util.contextBind(context, handler),
   3111             promise: promise,
   3112             receiver: receiver,
   3113             value: value
   3114         });
   3115     } else {
   3116         target._addCallbacks(didFulfill, didReject, promise,
   3117                 receiver, context);
   3118     }
   3119 
   3120     return promise;
   3121 };
   3122 
   3123 Promise.prototype._length = function () {
   3124     return this._bitField & 65535;
   3125 };
   3126 
   3127 Promise.prototype._isFateSealed = function () {
   3128     return (this._bitField & 117506048) !== 0;
   3129 };
   3130 
   3131 Promise.prototype._isFollowing = function () {
   3132     return (this._bitField & 67108864) === 67108864;
   3133 };
   3134 
   3135 Promise.prototype._setLength = function (len) {
   3136     this._bitField = (this._bitField & -65536) |
   3137         (len & 65535);
   3138 };
   3139 
   3140 Promise.prototype._setFulfilled = function () {
   3141     this._bitField = this._bitField | 33554432;
   3142     this._fireEvent("promiseFulfilled", this);
   3143 };
   3144 
   3145 Promise.prototype._setRejected = function () {
   3146     this._bitField = this._bitField | 16777216;
   3147     this._fireEvent("promiseRejected", this);
   3148 };
   3149 
   3150 Promise.prototype._setFollowing = function () {
   3151     this._bitField = this._bitField | 67108864;
   3152     this._fireEvent("promiseResolved", this);
   3153 };
   3154 
   3155 Promise.prototype._setIsFinal = function () {
   3156     this._bitField = this._bitField | 4194304;
   3157 };
   3158 
   3159 Promise.prototype._isFinal = function () {
   3160     return (this._bitField & 4194304) > 0;
   3161 };
   3162 
   3163 Promise.prototype._unsetCancelled = function() {
   3164     this._bitField = this._bitField & (~65536);
   3165 };
   3166 
   3167 Promise.prototype._setCancelled = function() {
   3168     this._bitField = this._bitField | 65536;
   3169     this._fireEvent("promiseCancelled", this);
   3170 };
   3171 
   3172 Promise.prototype._setWillBeCancelled = function() {
   3173     this._bitField = this._bitField | 8388608;
   3174 };
   3175 
   3176 Promise.prototype._setAsyncGuaranteed = function() {
   3177     if (async.hasCustomScheduler()) return;
   3178     var bitField = this._bitField;
   3179     this._bitField = bitField |
   3180         (((bitField & 536870912) >> 2) ^
   3181         134217728);
   3182 };
   3183 
   3184 Promise.prototype._setNoAsyncGuarantee = function() {
   3185     this._bitField = (this._bitField | 536870912) &
   3186         (~134217728);
   3187 };
   3188 
   3189 Promise.prototype._receiverAt = function (index) {
   3190     var ret = index === 0 ? this._receiver0 : this[
   3191             index * 4 - 4 + 3];
   3192     if (ret === UNDEFINED_BINDING) {
   3193         return undefined;
   3194     } else if (ret === undefined && this._isBound()) {
   3195         return this._boundValue();
   3196     }
   3197     return ret;
   3198 };
   3199 
   3200 Promise.prototype._promiseAt = function (index) {
   3201     return this[
   3202             index * 4 - 4 + 2];
   3203 };
   3204 
   3205 Promise.prototype._fulfillmentHandlerAt = function (index) {
   3206     return this[
   3207             index * 4 - 4 + 0];
   3208 };
   3209 
   3210 Promise.prototype._rejectionHandlerAt = function (index) {
   3211     return this[
   3212             index * 4 - 4 + 1];
   3213 };
   3214 
   3215 Promise.prototype._boundValue = function() {};
   3216 
   3217 Promise.prototype._migrateCallback0 = function (follower) {
   3218     var bitField = follower._bitField;
   3219     var fulfill = follower._fulfillmentHandler0;
   3220     var reject = follower._rejectionHandler0;
   3221     var promise = follower._promise0;
   3222     var receiver = follower._receiverAt(0);
   3223     if (receiver === undefined) receiver = UNDEFINED_BINDING;
   3224     this._addCallbacks(fulfill, reject, promise, receiver, null);
   3225 };
   3226 
   3227 Promise.prototype._migrateCallbackAt = function (follower, index) {
   3228     var fulfill = follower._fulfillmentHandlerAt(index);
   3229     var reject = follower._rejectionHandlerAt(index);
   3230     var promise = follower._promiseAt(index);
   3231     var receiver = follower._receiverAt(index);
   3232     if (receiver === undefined) receiver = UNDEFINED_BINDING;
   3233     this._addCallbacks(fulfill, reject, promise, receiver, null);
   3234 };
   3235 
   3236 Promise.prototype._addCallbacks = function (
   3237     fulfill,
   3238     reject,
   3239     promise,
   3240     receiver,
   3241     context
   3242 ) {
   3243     var index = this._length();
   3244 
   3245     if (index >= 65535 - 4) {
   3246         index = 0;
   3247         this._setLength(0);
   3248     }
   3249 
   3250     if (index === 0) {
   3251         this._promise0 = promise;
   3252         this._receiver0 = receiver;
   3253         if (typeof fulfill === "function") {
   3254             this._fulfillmentHandler0 = util.contextBind(context, fulfill);
   3255         }
   3256         if (typeof reject === "function") {
   3257             this._rejectionHandler0 = util.contextBind(context, reject);
   3258         }
   3259     } else {
   3260         var base = index * 4 - 4;
   3261         this[base + 2] = promise;
   3262         this[base + 3] = receiver;
   3263         if (typeof fulfill === "function") {
   3264             this[base + 0] =
   3265                 util.contextBind(context, fulfill);
   3266         }
   3267         if (typeof reject === "function") {
   3268             this[base + 1] =
   3269                 util.contextBind(context, reject);
   3270         }
   3271     }
   3272     this._setLength(index + 1);
   3273     return index;
   3274 };
   3275 
   3276 Promise.prototype._proxy = function (proxyable, arg) {
   3277     this._addCallbacks(undefined, undefined, arg, proxyable, null);
   3278 };
   3279 
   3280 Promise.prototype._resolveCallback = function(value, shouldBind) {
   3281     if (((this._bitField & 117506048) !== 0)) return;
   3282     if (value === this)
   3283         return this._rejectCallback(makeSelfResolutionError(), false);
   3284     var maybePromise = tryConvertToPromise(value, this);
   3285     if (!(maybePromise instanceof Promise)) return this._fulfill(value);
   3286 
   3287     if (shouldBind) this._propagateFrom(maybePromise, 2);
   3288 
   3289 
   3290     var promise = maybePromise._target();
   3291 
   3292     if (promise === this) {
   3293         this._reject(makeSelfResolutionError());
   3294         return;
   3295     }
   3296 
   3297     var bitField = promise._bitField;
   3298     if (((bitField & 50397184) === 0)) {
   3299         var len = this._length();
   3300         if (len > 0) promise._migrateCallback0(this);
   3301         for (var i = 1; i < len; ++i) {
   3302             promise._migrateCallbackAt(this, i);
   3303         }
   3304         this._setFollowing();
   3305         this._setLength(0);
   3306         this._setFollowee(maybePromise);
   3307     } else if (((bitField & 33554432) !== 0)) {
   3308         this._fulfill(promise._value());
   3309     } else if (((bitField & 16777216) !== 0)) {
   3310         this._reject(promise._reason());
   3311     } else {
   3312         var reason = new CancellationError("late cancellation observer");
   3313         promise._attachExtraTrace(reason);
   3314         this._reject(reason);
   3315     }
   3316 };
   3317 
   3318 Promise.prototype._rejectCallback =
   3319 function(reason, synchronous, ignoreNonErrorWarnings) {
   3320     var trace = util.ensureErrorObject(reason);
   3321     var hasStack = trace === reason;
   3322     if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
   3323         var message = "a promise was rejected with a non-error: " +
   3324             util.classString(reason);
   3325         this._warn(message, true);
   3326     }
   3327     this._attachExtraTrace(trace, synchronous ? hasStack : false);
   3328     this._reject(reason);
   3329 };
   3330 
   3331 Promise.prototype._resolveFromExecutor = function (executor) {
   3332     if (executor === INTERNAL) return;
   3333     var promise = this;
   3334     this._captureStackTrace();
   3335     this._pushContext();
   3336     var synchronous = true;
   3337     var r = this._execute(executor, function(value) {
   3338         promise._resolveCallback(value);
   3339     }, function (reason) {
   3340         promise._rejectCallback(reason, synchronous);
   3341     });
   3342     synchronous = false;
   3343     this._popContext();
   3344 
   3345     if (r !== undefined) {
   3346         promise._rejectCallback(r, true);
   3347     }
   3348 };
   3349 
   3350 Promise.prototype._settlePromiseFromHandler = function (
   3351     handler, receiver, value, promise
   3352 ) {
   3353     var bitField = promise._bitField;
   3354     if (((bitField & 65536) !== 0)) return;
   3355     promise._pushContext();
   3356     var x;
   3357     if (receiver === APPLY) {
   3358         if (!value || typeof value.length !== "number") {
   3359             x = errorObj;
   3360             x.e = new TypeError("cannot .spread() a non-array: " +
   3361                                     util.classString(value));
   3362         } else {
   3363             x = tryCatch(handler).apply(this._boundValue(), value);
   3364         }
   3365     } else {
   3366         x = tryCatch(handler).call(receiver, value);
   3367     }
   3368     var promiseCreated = promise._popContext();
   3369     bitField = promise._bitField;
   3370     if (((bitField & 65536) !== 0)) return;
   3371 
   3372     if (x === NEXT_FILTER) {
   3373         promise._reject(value);
   3374     } else if (x === errorObj) {
   3375         promise._rejectCallback(x.e, false);
   3376     } else {
   3377         debug.checkForgottenReturns(x, promiseCreated, "",  promise, this);
   3378         promise._resolveCallback(x);
   3379     }
   3380 };
   3381 
   3382 Promise.prototype._target = function() {
   3383     var ret = this;
   3384     while (ret._isFollowing()) ret = ret._followee();
   3385     return ret;
   3386 };
   3387 
   3388 Promise.prototype._followee = function() {
   3389     return this._rejectionHandler0;
   3390 };
   3391 
   3392 Promise.prototype._setFollowee = function(promise) {
   3393     this._rejectionHandler0 = promise;
   3394 };
   3395 
   3396 Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
   3397     var isPromise = promise instanceof Promise;
   3398     var bitField = this._bitField;
   3399     var asyncGuaranteed = ((bitField & 134217728) !== 0);
   3400     if (((bitField & 65536) !== 0)) {
   3401         if (isPromise) promise._invokeInternalOnCancel();
   3402 
   3403         if (receiver instanceof PassThroughHandlerContext &&
   3404             receiver.isFinallyHandler()) {
   3405             receiver.cancelPromise = promise;
   3406             if (tryCatch(handler).call(receiver, value) === errorObj) {
   3407                 promise._reject(errorObj.e);
   3408             }
   3409         } else if (handler === reflectHandler) {
   3410             promise._fulfill(reflectHandler.call(receiver));
   3411         } else if (receiver instanceof Proxyable) {
   3412             receiver._promiseCancelled(promise);
   3413         } else if (isPromise || promise instanceof PromiseArray) {
   3414             promise._cancel();
   3415         } else {
   3416             receiver.cancel();
   3417         }
   3418     } else if (typeof handler === "function") {
   3419         if (!isPromise) {
   3420             handler.call(receiver, value, promise);
   3421         } else {
   3422             if (asyncGuaranteed) promise._setAsyncGuaranteed();
   3423             this._settlePromiseFromHandler(handler, receiver, value, promise);
   3424         }
   3425     } else if (receiver instanceof Proxyable) {
   3426         if (!receiver._isResolved()) {
   3427             if (((bitField & 33554432) !== 0)) {
   3428                 receiver._promiseFulfilled(value, promise);
   3429             } else {
   3430                 receiver._promiseRejected(value, promise);
   3431             }
   3432         }
   3433     } else if (isPromise) {
   3434         if (asyncGuaranteed) promise._setAsyncGuaranteed();
   3435         if (((bitField & 33554432) !== 0)) {
   3436             promise._fulfill(value);
   3437         } else {
   3438             promise._reject(value);
   3439         }
   3440     }
   3441 };
   3442 
   3443 Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
   3444     var handler = ctx.handler;
   3445     var promise = ctx.promise;
   3446     var receiver = ctx.receiver;
   3447     var value = ctx.value;
   3448     if (typeof handler === "function") {
   3449         if (!(promise instanceof Promise)) {
   3450             handler.call(receiver, value, promise);
   3451         } else {
   3452             this._settlePromiseFromHandler(handler, receiver, value, promise);
   3453         }
   3454     } else if (promise instanceof Promise) {
   3455         promise._reject(value);
   3456     }
   3457 };
   3458 
   3459 Promise.prototype._settlePromiseCtx = function(ctx) {
   3460     this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
   3461 };
   3462 
   3463 Promise.prototype._settlePromise0 = function(handler, value, bitField) {
   3464     var promise = this._promise0;
   3465     var receiver = this._receiverAt(0);
   3466     this._promise0 = undefined;
   3467     this._receiver0 = undefined;
   3468     this._settlePromise(promise, handler, receiver, value);
   3469 };
   3470 
   3471 Promise.prototype._clearCallbackDataAtIndex = function(index) {
   3472     var base = index * 4 - 4;
   3473     this[base + 2] =
   3474     this[base + 3] =
   3475     this[base + 0] =
   3476     this[base + 1] = undefined;
   3477 };
   3478 
   3479 Promise.prototype._fulfill = function (value) {
   3480     var bitField = this._bitField;
   3481     if (((bitField & 117506048) >>> 16)) return;
   3482     if (value === this) {
   3483         var err = makeSelfResolutionError();
   3484         this._attachExtraTrace(err);
   3485         return this._reject(err);
   3486     }
   3487     this._setFulfilled();
   3488     this._rejectionHandler0 = value;
   3489 
   3490     if ((bitField & 65535) > 0) {
   3491         if (((bitField & 134217728) !== 0)) {
   3492             this._settlePromises();
   3493         } else {
   3494             async.settlePromises(this);
   3495         }
   3496         this._dereferenceTrace();
   3497     }
   3498 };
   3499 
   3500 Promise.prototype._reject = function (reason) {
   3501     var bitField = this._bitField;
   3502     if (((bitField & 117506048) >>> 16)) return;
   3503     this._setRejected();
   3504     this._fulfillmentHandler0 = reason;
   3505 
   3506     if (this._isFinal()) {
   3507         return async.fatalError(reason, util.isNode);
   3508     }
   3509 
   3510     if ((bitField & 65535) > 0) {
   3511         async.settlePromises(this);
   3512     } else {
   3513         this._ensurePossibleRejectionHandled();
   3514     }
   3515 };
   3516 
   3517 Promise.prototype._fulfillPromises = function (len, value) {
   3518     for (var i = 1; i < len; i++) {
   3519         var handler = this._fulfillmentHandlerAt(i);
   3520         var promise = this._promiseAt(i);
   3521         var receiver = this._receiverAt(i);
   3522         this._clearCallbackDataAtIndex(i);
   3523         this._settlePromise(promise, handler, receiver, value);
   3524     }
   3525 };
   3526 
   3527 Promise.prototype._rejectPromises = function (len, reason) {
   3528     for (var i = 1; i < len; i++) {
   3529         var handler = this._rejectionHandlerAt(i);
   3530         var promise = this._promiseAt(i);
   3531         var receiver = this._receiverAt(i);
   3532         this._clearCallbackDataAtIndex(i);
   3533         this._settlePromise(promise, handler, receiver, reason);
   3534     }
   3535 };
   3536 
   3537 Promise.prototype._settlePromises = function () {
   3538     var bitField = this._bitField;
   3539     var len = (bitField & 65535);
   3540 
   3541     if (len > 0) {
   3542         if (((bitField & 16842752) !== 0)) {
   3543             var reason = this._fulfillmentHandler0;
   3544             this._settlePromise0(this._rejectionHandler0, reason, bitField);
   3545             this._rejectPromises(len, reason);
   3546         } else {
   3547             var value = this._rejectionHandler0;
   3548             this._settlePromise0(this._fulfillmentHandler0, value, bitField);
   3549             this._fulfillPromises(len, value);
   3550         }
   3551         this._setLength(0);
   3552     }
   3553     this._clearCancellationData();
   3554 };
   3555 
   3556 Promise.prototype._settledValue = function() {
   3557     var bitField = this._bitField;
   3558     if (((bitField & 33554432) !== 0)) {
   3559         return this._rejectionHandler0;
   3560     } else if (((bitField & 16777216) !== 0)) {
   3561         return this._fulfillmentHandler0;
   3562     }
   3563 };
   3564 
   3565 if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
   3566     es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
   3567         get: function () {
   3568             return "Object";
   3569         }
   3570     });
   3571 }
   3572 
   3573 function deferResolve(v) {this.promise._resolveCallback(v);}
   3574 function deferReject(v) {this.promise._rejectCallback(v, false);}
   3575 
   3576 Promise.defer = Promise.pending = function() {
   3577     debug.deprecated("Promise.defer", "new Promise");
   3578     var promise = new Promise(INTERNAL);
   3579     return {
   3580         promise: promise,
   3581         resolve: deferResolve,
   3582         reject: deferReject
   3583     };
   3584 };
   3585 
   3586 util.notEnumerableProp(Promise,
   3587                        "_makeSelfResolutionError",
   3588                        makeSelfResolutionError);
   3589 
   3590 _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
   3591     debug);
   3592 _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
   3593 _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
   3594 _dereq_("./direct_resolve")(Promise);
   3595 _dereq_("./synchronous_inspection")(Promise);
   3596 _dereq_("./join")(
   3597     Promise, PromiseArray, tryConvertToPromise, INTERNAL, async);
   3598 Promise.Promise = Promise;
   3599 Promise.version = "3.7.2";
   3600 _dereq_('./call_get.js')(Promise);
   3601 _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
   3602 _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
   3603 _dereq_('./nodeify.js')(Promise);
   3604 _dereq_('./promisify.js')(Promise, INTERNAL);
   3605 _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
   3606 _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
   3607 _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
   3608 _dereq_('./settle.js')(Promise, PromiseArray, debug);
   3609 _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
   3610 _dereq_('./timers.js')(Promise, INTERNAL, debug);
   3611 _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
   3612 _dereq_('./any.js')(Promise);
   3613 _dereq_('./each.js')(Promise, INTERNAL);
   3614 _dereq_('./filter.js')(Promise, INTERNAL);
   3615                                                          
   3616     util.toFastProperties(Promise);                                          
   3617     util.toFastProperties(Promise.prototype);                                
   3618     function fillTypes(value) {                                              
   3619         var p = new Promise(INTERNAL);                                       
   3620         p._fulfillmentHandler0 = value;                                      
   3621         p._rejectionHandler0 = value;                                        
   3622         p._promise0 = value;                                                 
   3623         p._receiver0 = value;                                                
   3624     }                                                                        
   3625     // Complete slack tracking, opt out of field-type tracking and           
   3626     // stabilize map                                                         
   3627     fillTypes({a: 1});                                                       
   3628     fillTypes({b: 2});                                                       
   3629     fillTypes({c: 3});                                                       
   3630     fillTypes(1);                                                            
   3631     fillTypes(function(){});                                                 
   3632     fillTypes(undefined);                                                    
   3633     fillTypes(false);                                                        
   3634     fillTypes(new Promise(INTERNAL));                                        
   3635     debug.setBounds(Async.firstLineError, util.lastLineError);               
   3636     return Promise;                                                          
   3637 
   3638 };
   3639 
   3640 },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,"async_hooks":undefined}],23:[function(_dereq_,module,exports){
   3641 "use strict";
   3642 module.exports = function(Promise, INTERNAL, tryConvertToPromise,
   3643     apiRejection, Proxyable) {
   3644 var util = _dereq_("./util");
   3645 var isArray = util.isArray;
   3646 
   3647 function toResolutionValue(val) {
   3648     switch(val) {
   3649     case -2: return [];
   3650     case -3: return {};
   3651     case -6: return new Map();
   3652     }
   3653 }
   3654 
   3655 function PromiseArray(values) {
   3656     var promise = this._promise = new Promise(INTERNAL);
   3657     if (values instanceof Promise) {
   3658         promise._propagateFrom(values, 3);
   3659         values.suppressUnhandledRejections();
   3660     }
   3661     promise._setOnCancel(this);
   3662     this._values = values;
   3663     this._length = 0;
   3664     this._totalResolved = 0;
   3665     this._init(undefined, -2);
   3666 }
   3667 util.inherits(PromiseArray, Proxyable);
   3668 
   3669 PromiseArray.prototype.length = function () {
   3670     return this._length;
   3671 };
   3672 
   3673 PromiseArray.prototype.promise = function () {
   3674     return this._promise;
   3675 };
   3676 
   3677 PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
   3678     var values = tryConvertToPromise(this._values, this._promise);
   3679     if (values instanceof Promise) {
   3680         values = values._target();
   3681         var bitField = values._bitField;
   3682         ;
   3683         this._values = values;
   3684 
   3685         if (((bitField & 50397184) === 0)) {
   3686             this._promise._setAsyncGuaranteed();
   3687             return values._then(
   3688                 init,
   3689                 this._reject,
   3690                 undefined,
   3691                 this,
   3692                 resolveValueIfEmpty
   3693            );
   3694         } else if (((bitField & 33554432) !== 0)) {
   3695             values = values._value();
   3696         } else if (((bitField & 16777216) !== 0)) {
   3697             return this._reject(values._reason());
   3698         } else {
   3699             return this._cancel();
   3700         }
   3701     }
   3702     values = util.asArray(values);
   3703     if (values === null) {
   3704         var err = apiRejection(
   3705             "expecting an array or an iterable object but got " + util.classString(values)).reason();
   3706         this._promise._rejectCallback(err, false);
   3707         return;
   3708     }
   3709 
   3710     if (values.length === 0) {
   3711         if (resolveValueIfEmpty === -5) {
   3712             this._resolveEmptyArray();
   3713         }
   3714         else {
   3715             this._resolve(toResolutionValue(resolveValueIfEmpty));
   3716         }
   3717         return;
   3718     }
   3719     this._iterate(values);
   3720 };
   3721 
   3722 PromiseArray.prototype._iterate = function(values) {
   3723     var len = this.getActualLength(values.length);
   3724     this._length = len;
   3725     this._values = this.shouldCopyValues() ? new Array(len) : this._values;
   3726     var result = this._promise;
   3727     var isResolved = false;
   3728     var bitField = null;
   3729     for (var i = 0; i < len; ++i) {
   3730         var maybePromise = tryConvertToPromise(values[i], result);
   3731 
   3732         if (maybePromise instanceof Promise) {
   3733             maybePromise = maybePromise._target();
   3734             bitField = maybePromise._bitField;
   3735         } else {
   3736             bitField = null;
   3737         }
   3738 
   3739         if (isResolved) {
   3740             if (bitField !== null) {
   3741                 maybePromise.suppressUnhandledRejections();
   3742             }
   3743         } else if (bitField !== null) {
   3744             if (((bitField & 50397184) === 0)) {
   3745                 maybePromise._proxy(this, i);
   3746                 this._values[i] = maybePromise;
   3747             } else if (((bitField & 33554432) !== 0)) {
   3748                 isResolved = this._promiseFulfilled(maybePromise._value(), i);
   3749             } else if (((bitField & 16777216) !== 0)) {
   3750                 isResolved = this._promiseRejected(maybePromise._reason(), i);
   3751             } else {
   3752                 isResolved = this._promiseCancelled(i);
   3753             }
   3754         } else {
   3755             isResolved = this._promiseFulfilled(maybePromise, i);
   3756         }
   3757     }
   3758     if (!isResolved) result._setAsyncGuaranteed();
   3759 };
   3760 
   3761 PromiseArray.prototype._isResolved = function () {
   3762     return this._values === null;
   3763 };
   3764 
   3765 PromiseArray.prototype._resolve = function (value) {
   3766     this._values = null;
   3767     this._promise._fulfill(value);
   3768 };
   3769 
   3770 PromiseArray.prototype._cancel = function() {
   3771     if (this._isResolved() || !this._promise._isCancellable()) return;
   3772     this._values = null;
   3773     this._promise._cancel();
   3774 };
   3775 
   3776 PromiseArray.prototype._reject = function (reason) {
   3777     this._values = null;
   3778     this._promise._rejectCallback(reason, false);
   3779 };
   3780 
   3781 PromiseArray.prototype._promiseFulfilled = function (value, index) {
   3782     this._values[index] = value;
   3783     var totalResolved = ++this._totalResolved;
   3784     if (totalResolved >= this._length) {
   3785         this._resolve(this._values);
   3786         return true;
   3787     }
   3788     return false;
   3789 };
   3790 
   3791 PromiseArray.prototype._promiseCancelled = function() {
   3792     this._cancel();
   3793     return true;
   3794 };
   3795 
   3796 PromiseArray.prototype._promiseRejected = function (reason) {
   3797     this._totalResolved++;
   3798     this._reject(reason);
   3799     return true;
   3800 };
   3801 
   3802 PromiseArray.prototype._resultCancelled = function() {
   3803     if (this._isResolved()) return;
   3804     var values = this._values;
   3805     this._cancel();
   3806     if (values instanceof Promise) {
   3807         values.cancel();
   3808     } else {
   3809         for (var i = 0; i < values.length; ++i) {
   3810             if (values[i] instanceof Promise) {
   3811                 values[i].cancel();
   3812             }
   3813         }
   3814     }
   3815 };
   3816 
   3817 PromiseArray.prototype.shouldCopyValues = function () {
   3818     return true;
   3819 };
   3820 
   3821 PromiseArray.prototype.getActualLength = function (len) {
   3822     return len;
   3823 };
   3824 
   3825 return PromiseArray;
   3826 };
   3827 
   3828 },{"./util":36}],24:[function(_dereq_,module,exports){
   3829 "use strict";
   3830 module.exports = function(Promise, INTERNAL) {
   3831 var THIS = {};
   3832 var util = _dereq_("./util");
   3833 var nodebackForPromise = _dereq_("./nodeback");
   3834 var withAppended = util.withAppended;
   3835 var maybeWrapAsError = util.maybeWrapAsError;
   3836 var canEvaluate = util.canEvaluate;
   3837 var TypeError = _dereq_("./errors").TypeError;
   3838 var defaultSuffix = "Async";
   3839 var defaultPromisified = {__isPromisified__: true};
   3840 var noCopyProps = [
   3841     "arity",    "length",
   3842     "name",
   3843     "arguments",
   3844     "caller",
   3845     "callee",
   3846     "prototype",
   3847     "__isPromisified__"
   3848 ];
   3849 var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
   3850 
   3851 var defaultFilter = function(name) {
   3852     return util.isIdentifier(name) &&
   3853         name.charAt(0) !== "_" &&
   3854         name !== "constructor";
   3855 };
   3856 
   3857 function propsFilter(key) {
   3858     return !noCopyPropsPattern.test(key);
   3859 }
   3860 
   3861 function isPromisified(fn) {
   3862     try {
   3863         return fn.__isPromisified__ === true;
   3864     }
   3865     catch (e) {
   3866         return false;
   3867     }
   3868 }
   3869 
   3870 function hasPromisified(obj, key, suffix) {
   3871     var val = util.getDataPropertyOrDefault(obj, key + suffix,
   3872                                             defaultPromisified);
   3873     return val ? isPromisified(val) : false;
   3874 }
   3875 function checkValid(ret, suffix, suffixRegexp) {
   3876     for (var i = 0; i < ret.length; i += 2) {
   3877         var key = ret[i];
   3878         if (suffixRegexp.test(key)) {
   3879             var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
   3880             for (var j = 0; j < ret.length; j += 2) {
   3881                 if (ret[j] === keyWithoutAsyncSuffix) {
   3882                     throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a    See http://goo.gl/MqrFmX\u000a"
   3883                         .replace("%s", suffix));
   3884                 }
   3885             }
   3886         }
   3887     }
   3888 }
   3889 
   3890 function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
   3891     var keys = util.inheritedDataKeys(obj);
   3892     var ret = [];
   3893     for (var i = 0; i < keys.length; ++i) {
   3894         var key = keys[i];
   3895         var value = obj[key];
   3896         var passesDefaultFilter = filter === defaultFilter
   3897             ? true : defaultFilter(key, value, obj);
   3898         if (typeof value === "function" &&
   3899             !isPromisified(value) &&
   3900             !hasPromisified(obj, key, suffix) &&
   3901             filter(key, value, obj, passesDefaultFilter)) {
   3902             ret.push(key, value);
   3903         }
   3904     }
   3905     checkValid(ret, suffix, suffixRegexp);
   3906     return ret;
   3907 }
   3908 
   3909 var escapeIdentRegex = function(str) {
   3910     return str.replace(/([$])/, "\\$");
   3911 };
   3912 
   3913 var makeNodePromisifiedEval;
   3914 if (!true) {
   3915 var switchCaseArgumentOrder = function(likelyArgumentCount) {
   3916     var ret = [likelyArgumentCount];
   3917     var min = Math.max(0, likelyArgumentCount - 1 - 3);
   3918     for(var i = likelyArgumentCount - 1; i >= min; --i) {
   3919         ret.push(i);
   3920     }
   3921     for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
   3922         ret.push(i);
   3923     }
   3924     return ret;
   3925 };
   3926 
   3927 var argumentSequence = function(argumentCount) {
   3928     return util.filledRange(argumentCount, "_arg", "");
   3929 };
   3930 
   3931 var parameterDeclaration = function(parameterCount) {
   3932     return util.filledRange(
   3933         Math.max(parameterCount, 3), "_arg", "");
   3934 };
   3935 
   3936 var parameterCount = function(fn) {
   3937     if (typeof fn.length === "number") {
   3938         return Math.max(Math.min(fn.length, 1023 + 1), 0);
   3939     }
   3940     return 0;
   3941 };
   3942 
   3943 makeNodePromisifiedEval =
   3944 function(callback, receiver, originalName, fn, _, multiArgs) {
   3945     var newParameterCount = Math.max(0, parameterCount(fn) - 1);
   3946     var argumentOrder = switchCaseArgumentOrder(newParameterCount);
   3947     var shouldProxyThis = typeof callback === "string" || receiver === THIS;
   3948 
   3949     function generateCallForArgumentCount(count) {
   3950         var args = argumentSequence(count).join(", ");
   3951         var comma = count > 0 ? ", " : "";
   3952         var ret;
   3953         if (shouldProxyThis) {
   3954             ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
   3955         } else {
   3956             ret = receiver === undefined
   3957                 ? "ret = callback({{args}}, nodeback); break;\n"
   3958                 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
   3959         }
   3960         return ret.replace("{{args}}", args).replace(", ", comma);
   3961     }
   3962 
   3963     function generateArgumentSwitchCase() {
   3964         var ret = "";
   3965         for (var i = 0; i < argumentOrder.length; ++i) {
   3966             ret += "case " + argumentOrder[i] +":" +
   3967                 generateCallForArgumentCount(argumentOrder[i]);
   3968         }
   3969 
   3970         ret += "                                                             \n\
   3971         default:                                                             \n\
   3972             var args = new Array(len + 1);                                   \n\
   3973             var i = 0;                                                       \n\
   3974             for (var i = 0; i < len; ++i) {                                  \n\
   3975                args[i] = arguments[i];                                       \n\
   3976             }                                                                \n\
   3977             args[i] = nodeback;                                              \n\
   3978             [CodeForCall]                                                    \n\
   3979             break;                                                           \n\
   3980         ".replace("[CodeForCall]", (shouldProxyThis
   3981                                 ? "ret = callback.apply(this, args);\n"
   3982                                 : "ret = callback.apply(receiver, args);\n"));
   3983         return ret;
   3984     }
   3985 
   3986     var getFunctionCode = typeof callback === "string"
   3987                                 ? ("this != null ? this['"+callback+"'] : fn")
   3988                                 : "fn";
   3989     var body = "'use strict';                                                \n\
   3990         var ret = function (Parameters) {                                    \n\
   3991             'use strict';                                                    \n\
   3992             var len = arguments.length;                                      \n\
   3993             var promise = new Promise(INTERNAL);                             \n\
   3994             promise._captureStackTrace();                                    \n\
   3995             var nodeback = nodebackForPromise(promise, " + multiArgs + ");   \n\
   3996             var ret;                                                         \n\
   3997             var callback = tryCatch([GetFunctionCode]);                      \n\
   3998             switch(len) {                                                    \n\
   3999                 [CodeForSwitchCase]                                          \n\
   4000             }                                                                \n\
   4001             if (ret === errorObj) {                                          \n\
   4002                 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
   4003             }                                                                \n\
   4004             if (!promise._isFateSealed()) promise._setAsyncGuaranteed();     \n\
   4005             return promise;                                                  \n\
   4006         };                                                                   \n\
   4007         notEnumerableProp(ret, '__isPromisified__', true);                   \n\
   4008         return ret;                                                          \n\
   4009     ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
   4010         .replace("[GetFunctionCode]", getFunctionCode);
   4011     body = body.replace("Parameters", parameterDeclaration(newParameterCount));
   4012     return new Function("Promise",
   4013                         "fn",
   4014                         "receiver",
   4015                         "withAppended",
   4016                         "maybeWrapAsError",
   4017                         "nodebackForPromise",
   4018                         "tryCatch",
   4019                         "errorObj",
   4020                         "notEnumerableProp",
   4021                         "INTERNAL",
   4022                         body)(
   4023                     Promise,
   4024                     fn,
   4025                     receiver,
   4026                     withAppended,
   4027                     maybeWrapAsError,
   4028                     nodebackForPromise,
   4029                     util.tryCatch,
   4030                     util.errorObj,
   4031                     util.notEnumerableProp,
   4032                     INTERNAL);
   4033 };
   4034 }
   4035 
   4036 function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
   4037     var defaultThis = (function() {return this;})();
   4038     var method = callback;
   4039     if (typeof method === "string") {
   4040         callback = fn;
   4041     }
   4042     function promisified() {
   4043         var _receiver = receiver;
   4044         if (receiver === THIS) _receiver = this;
   4045         var promise = new Promise(INTERNAL);
   4046         promise._captureStackTrace();
   4047         var cb = typeof method === "string" && this !== defaultThis
   4048             ? this[method] : callback;
   4049         var fn = nodebackForPromise(promise, multiArgs);
   4050         try {
   4051             cb.apply(_receiver, withAppended(arguments, fn));
   4052         } catch(e) {
   4053             promise._rejectCallback(maybeWrapAsError(e), true, true);
   4054         }
   4055         if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
   4056         return promise;
   4057     }
   4058     util.notEnumerableProp(promisified, "__isPromisified__", true);
   4059     return promisified;
   4060 }
   4061 
   4062 var makeNodePromisified = canEvaluate
   4063     ? makeNodePromisifiedEval
   4064     : makeNodePromisifiedClosure;
   4065 
   4066 function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
   4067     var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
   4068     var methods =
   4069         promisifiableMethods(obj, suffix, suffixRegexp, filter);
   4070 
   4071     for (var i = 0, len = methods.length; i < len; i+= 2) {
   4072         var key = methods[i];
   4073         var fn = methods[i+1];
   4074         var promisifiedKey = key + suffix;
   4075         if (promisifier === makeNodePromisified) {
   4076             obj[promisifiedKey] =
   4077                 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
   4078         } else {
   4079             var promisified = promisifier(fn, function() {
   4080                 return makeNodePromisified(key, THIS, key,
   4081                                            fn, suffix, multiArgs);
   4082             });
   4083             util.notEnumerableProp(promisified, "__isPromisified__", true);
   4084             obj[promisifiedKey] = promisified;
   4085         }
   4086     }
   4087     util.toFastProperties(obj);
   4088     return obj;
   4089 }
   4090 
   4091 function promisify(callback, receiver, multiArgs) {
   4092     return makeNodePromisified(callback, receiver, undefined,
   4093                                 callback, null, multiArgs);
   4094 }
   4095 
   4096 Promise.promisify = function (fn, options) {
   4097     if (typeof fn !== "function") {
   4098         throw new TypeError("expecting a function but got " + util.classString(fn));
   4099     }
   4100     if (isPromisified(fn)) {
   4101         return fn;
   4102     }
   4103     options = Object(options);
   4104     var receiver = options.context === undefined ? THIS : options.context;
   4105     var multiArgs = !!options.multiArgs;
   4106     var ret = promisify(fn, receiver, multiArgs);
   4107     util.copyDescriptors(fn, ret, propsFilter);
   4108     return ret;
   4109 };
   4110 
   4111 Promise.promisifyAll = function (target, options) {
   4112     if (typeof target !== "function" && typeof target !== "object") {
   4113         throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4114     }
   4115     options = Object(options);
   4116     var multiArgs = !!options.multiArgs;
   4117     var suffix = options.suffix;
   4118     if (typeof suffix !== "string") suffix = defaultSuffix;
   4119     var filter = options.filter;
   4120     if (typeof filter !== "function") filter = defaultFilter;
   4121     var promisifier = options.promisifier;
   4122     if (typeof promisifier !== "function") promisifier = makeNodePromisified;
   4123 
   4124     if (!util.isIdentifier(suffix)) {
   4125         throw new RangeError("suffix must be a valid identifier\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4126     }
   4127 
   4128     var keys = util.inheritedDataKeys(target);
   4129     for (var i = 0; i < keys.length; ++i) {
   4130         var value = target[keys[i]];
   4131         if (keys[i] !== "constructor" &&
   4132             util.isClass(value)) {
   4133             promisifyAll(value.prototype, suffix, filter, promisifier,
   4134                 multiArgs);
   4135             promisifyAll(value, suffix, filter, promisifier, multiArgs);
   4136         }
   4137     }
   4138 
   4139     return promisifyAll(target, suffix, filter, promisifier, multiArgs);
   4140 };
   4141 };
   4142 
   4143 
   4144 },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
   4145 "use strict";
   4146 module.exports = function(
   4147     Promise, PromiseArray, tryConvertToPromise, apiRejection) {
   4148 var util = _dereq_("./util");
   4149 var isObject = util.isObject;
   4150 var es5 = _dereq_("./es5");
   4151 var Es6Map;
   4152 if (typeof Map === "function") Es6Map = Map;
   4153 
   4154 var mapToEntries = (function() {
   4155     var index = 0;
   4156     var size = 0;
   4157 
   4158     function extractEntry(value, key) {
   4159         this[index] = value;
   4160         this[index + size] = key;
   4161         index++;
   4162     }
   4163 
   4164     return function mapToEntries(map) {
   4165         size = map.size;
   4166         index = 0;
   4167         var ret = new Array(map.size * 2);
   4168         map.forEach(extractEntry, ret);
   4169         return ret;
   4170     };
   4171 })();
   4172 
   4173 var entriesToMap = function(entries) {
   4174     var ret = new Es6Map();
   4175     var length = entries.length / 2 | 0;
   4176     for (var i = 0; i < length; ++i) {
   4177         var key = entries[length + i];
   4178         var value = entries[i];
   4179         ret.set(key, value);
   4180     }
   4181     return ret;
   4182 };
   4183 
   4184 function PropertiesPromiseArray(obj) {
   4185     var isMap = false;
   4186     var entries;
   4187     if (Es6Map !== undefined && obj instanceof Es6Map) {
   4188         entries = mapToEntries(obj);
   4189         isMap = true;
   4190     } else {
   4191         var keys = es5.keys(obj);
   4192         var len = keys.length;
   4193         entries = new Array(len * 2);
   4194         for (var i = 0; i < len; ++i) {
   4195             var key = keys[i];
   4196             entries[i] = obj[key];
   4197             entries[i + len] = key;
   4198         }
   4199     }
   4200     this.constructor$(entries);
   4201     this._isMap = isMap;
   4202     this._init$(undefined, isMap ? -6 : -3);
   4203 }
   4204 util.inherits(PropertiesPromiseArray, PromiseArray);
   4205 
   4206 PropertiesPromiseArray.prototype._init = function () {};
   4207 
   4208 PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
   4209     this._values[index] = value;
   4210     var totalResolved = ++this._totalResolved;
   4211     if (totalResolved >= this._length) {
   4212         var val;
   4213         if (this._isMap) {
   4214             val = entriesToMap(this._values);
   4215         } else {
   4216             val = {};
   4217             var keyOffset = this.length();
   4218             for (var i = 0, len = this.length(); i < len; ++i) {
   4219                 val[this._values[i + keyOffset]] = this._values[i];
   4220             }
   4221         }
   4222         this._resolve(val);
   4223         return true;
   4224     }
   4225     return false;
   4226 };
   4227 
   4228 PropertiesPromiseArray.prototype.shouldCopyValues = function () {
   4229     return false;
   4230 };
   4231 
   4232 PropertiesPromiseArray.prototype.getActualLength = function (len) {
   4233     return len >> 1;
   4234 };
   4235 
   4236 function props(promises) {
   4237     var ret;
   4238     var castValue = tryConvertToPromise(promises);
   4239 
   4240     if (!isObject(castValue)) {
   4241         return apiRejection("cannot await properties of a non-object\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4242     } else if (castValue instanceof Promise) {
   4243         ret = castValue._then(
   4244             Promise.props, undefined, undefined, undefined, undefined);
   4245     } else {
   4246         ret = new PropertiesPromiseArray(castValue).promise();
   4247     }
   4248 
   4249     if (castValue instanceof Promise) {
   4250         ret._propagateFrom(castValue, 2);
   4251     }
   4252     return ret;
   4253 }
   4254 
   4255 Promise.prototype.props = function () {
   4256     return props(this);
   4257 };
   4258 
   4259 Promise.props = function (promises) {
   4260     return props(promises);
   4261 };
   4262 };
   4263 
   4264 },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
   4265 "use strict";
   4266 function arrayMove(src, srcIndex, dst, dstIndex, len) {
   4267     for (var j = 0; j < len; ++j) {
   4268         dst[j + dstIndex] = src[j + srcIndex];
   4269         src[j + srcIndex] = void 0;
   4270     }
   4271 }
   4272 
   4273 function Queue(capacity) {
   4274     this._capacity = capacity;
   4275     this._length = 0;
   4276     this._front = 0;
   4277 }
   4278 
   4279 Queue.prototype._willBeOverCapacity = function (size) {
   4280     return this._capacity < size;
   4281 };
   4282 
   4283 Queue.prototype._pushOne = function (arg) {
   4284     var length = this.length();
   4285     this._checkCapacity(length + 1);
   4286     var i = (this._front + length) & (this._capacity - 1);
   4287     this[i] = arg;
   4288     this._length = length + 1;
   4289 };
   4290 
   4291 Queue.prototype.push = function (fn, receiver, arg) {
   4292     var length = this.length() + 3;
   4293     if (this._willBeOverCapacity(length)) {
   4294         this._pushOne(fn);
   4295         this._pushOne(receiver);
   4296         this._pushOne(arg);
   4297         return;
   4298     }
   4299     var j = this._front + length - 3;
   4300     this._checkCapacity(length);
   4301     var wrapMask = this._capacity - 1;
   4302     this[(j + 0) & wrapMask] = fn;
   4303     this[(j + 1) & wrapMask] = receiver;
   4304     this[(j + 2) & wrapMask] = arg;
   4305     this._length = length;
   4306 };
   4307 
   4308 Queue.prototype.shift = function () {
   4309     var front = this._front,
   4310         ret = this[front];
   4311 
   4312     this[front] = undefined;
   4313     this._front = (front + 1) & (this._capacity - 1);
   4314     this._length--;
   4315     return ret;
   4316 };
   4317 
   4318 Queue.prototype.length = function () {
   4319     return this._length;
   4320 };
   4321 
   4322 Queue.prototype._checkCapacity = function (size) {
   4323     if (this._capacity < size) {
   4324         this._resizeTo(this._capacity << 1);
   4325     }
   4326 };
   4327 
   4328 Queue.prototype._resizeTo = function (capacity) {
   4329     var oldCapacity = this._capacity;
   4330     this._capacity = capacity;
   4331     var front = this._front;
   4332     var length = this._length;
   4333     var moveItemsCount = (front + length) & (oldCapacity - 1);
   4334     arrayMove(this, 0, this, oldCapacity, moveItemsCount);
   4335 };
   4336 
   4337 module.exports = Queue;
   4338 
   4339 },{}],27:[function(_dereq_,module,exports){
   4340 "use strict";
   4341 module.exports = function(
   4342     Promise, INTERNAL, tryConvertToPromise, apiRejection) {
   4343 var util = _dereq_("./util");
   4344 
   4345 var raceLater = function (promise) {
   4346     return promise.then(function(array) {
   4347         return race(array, promise);
   4348     });
   4349 };
   4350 
   4351 function race(promises, parent) {
   4352     var maybePromise = tryConvertToPromise(promises);
   4353 
   4354     if (maybePromise instanceof Promise) {
   4355         return raceLater(maybePromise);
   4356     } else {
   4357         promises = util.asArray(promises);
   4358         if (promises === null)
   4359             return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
   4360     }
   4361 
   4362     var ret = new Promise(INTERNAL);
   4363     if (parent !== undefined) {
   4364         ret._propagateFrom(parent, 3);
   4365     }
   4366     var fulfill = ret._fulfill;
   4367     var reject = ret._reject;
   4368     for (var i = 0, len = promises.length; i < len; ++i) {
   4369         var val = promises[i];
   4370 
   4371         if (val === undefined && !(i in promises)) {
   4372             continue;
   4373         }
   4374 
   4375         Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
   4376     }
   4377     return ret;
   4378 }
   4379 
   4380 Promise.race = function (promises) {
   4381     return race(promises, undefined);
   4382 };
   4383 
   4384 Promise.prototype.race = function () {
   4385     return race(this, undefined);
   4386 };
   4387 
   4388 };
   4389 
   4390 },{"./util":36}],28:[function(_dereq_,module,exports){
   4391 "use strict";
   4392 module.exports = function(Promise,
   4393                           PromiseArray,
   4394                           apiRejection,
   4395                           tryConvertToPromise,
   4396                           INTERNAL,
   4397                           debug) {
   4398 var util = _dereq_("./util");
   4399 var tryCatch = util.tryCatch;
   4400 
   4401 function ReductionPromiseArray(promises, fn, initialValue, _each) {
   4402     this.constructor$(promises);
   4403     var context = Promise._getContext();
   4404     this._fn = util.contextBind(context, fn);
   4405     if (initialValue !== undefined) {
   4406         initialValue = Promise.resolve(initialValue);
   4407         initialValue._attachCancellationCallback(this);
   4408     }
   4409     this._initialValue = initialValue;
   4410     this._currentCancellable = null;
   4411     if(_each === INTERNAL) {
   4412         this._eachValues = Array(this._length);
   4413     } else if (_each === 0) {
   4414         this._eachValues = null;
   4415     } else {
   4416         this._eachValues = undefined;
   4417     }
   4418     this._promise._captureStackTrace();
   4419     this._init$(undefined, -5);
   4420 }
   4421 util.inherits(ReductionPromiseArray, PromiseArray);
   4422 
   4423 ReductionPromiseArray.prototype._gotAccum = function(accum) {
   4424     if (this._eachValues !== undefined &&
   4425         this._eachValues !== null &&
   4426         accum !== INTERNAL) {
   4427         this._eachValues.push(accum);
   4428     }
   4429 };
   4430 
   4431 ReductionPromiseArray.prototype._eachComplete = function(value) {
   4432     if (this._eachValues !== null) {
   4433         this._eachValues.push(value);
   4434     }
   4435     return this._eachValues;
   4436 };
   4437 
   4438 ReductionPromiseArray.prototype._init = function() {};
   4439 
   4440 ReductionPromiseArray.prototype._resolveEmptyArray = function() {
   4441     this._resolve(this._eachValues !== undefined ? this._eachValues
   4442                                                  : this._initialValue);
   4443 };
   4444 
   4445 ReductionPromiseArray.prototype.shouldCopyValues = function () {
   4446     return false;
   4447 };
   4448 
   4449 ReductionPromiseArray.prototype._resolve = function(value) {
   4450     this._promise._resolveCallback(value);
   4451     this._values = null;
   4452 };
   4453 
   4454 ReductionPromiseArray.prototype._resultCancelled = function(sender) {
   4455     if (sender === this._initialValue) return this._cancel();
   4456     if (this._isResolved()) return;
   4457     this._resultCancelled$();
   4458     if (this._currentCancellable instanceof Promise) {
   4459         this._currentCancellable.cancel();
   4460     }
   4461     if (this._initialValue instanceof Promise) {
   4462         this._initialValue.cancel();
   4463     }
   4464 };
   4465 
   4466 ReductionPromiseArray.prototype._iterate = function (values) {
   4467     this._values = values;
   4468     var value;
   4469     var i;
   4470     var length = values.length;
   4471     if (this._initialValue !== undefined) {
   4472         value = this._initialValue;
   4473         i = 0;
   4474     } else {
   4475         value = Promise.resolve(values[0]);
   4476         i = 1;
   4477     }
   4478 
   4479     this._currentCancellable = value;
   4480 
   4481     for (var j = i; j < length; ++j) {
   4482         var maybePromise = values[j];
   4483         if (maybePromise instanceof Promise) {
   4484             maybePromise.suppressUnhandledRejections();
   4485         }
   4486     }
   4487 
   4488     if (!value.isRejected()) {
   4489         for (; i < length; ++i) {
   4490             var ctx = {
   4491                 accum: null,
   4492                 value: values[i],
   4493                 index: i,
   4494                 length: length,
   4495                 array: this
   4496             };
   4497 
   4498             value = value._then(gotAccum, undefined, undefined, ctx, undefined);
   4499 
   4500             if ((i & 127) === 0) {
   4501                 value._setNoAsyncGuarantee();
   4502             }
   4503         }
   4504     }
   4505 
   4506     if (this._eachValues !== undefined) {
   4507         value = value
   4508             ._then(this._eachComplete, undefined, undefined, this, undefined);
   4509     }
   4510     value._then(completed, completed, undefined, value, this);
   4511 };
   4512 
   4513 Promise.prototype.reduce = function (fn, initialValue) {
   4514     return reduce(this, fn, initialValue, null);
   4515 };
   4516 
   4517 Promise.reduce = function (promises, fn, initialValue, _each) {
   4518     return reduce(promises, fn, initialValue, _each);
   4519 };
   4520 
   4521 function completed(valueOrReason, array) {
   4522     if (this.isFulfilled()) {
   4523         array._resolve(valueOrReason);
   4524     } else {
   4525         array._reject(valueOrReason);
   4526     }
   4527 }
   4528 
   4529 function reduce(promises, fn, initialValue, _each) {
   4530     if (typeof fn !== "function") {
   4531         return apiRejection("expecting a function but got " + util.classString(fn));
   4532     }
   4533     var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
   4534     return array.promise();
   4535 }
   4536 
   4537 function gotAccum(accum) {
   4538     this.accum = accum;
   4539     this.array._gotAccum(accum);
   4540     var value = tryConvertToPromise(this.value, this.array._promise);
   4541     if (value instanceof Promise) {
   4542         this.array._currentCancellable = value;
   4543         return value._then(gotValue, undefined, undefined, this, undefined);
   4544     } else {
   4545         return gotValue.call(this, value);
   4546     }
   4547 }
   4548 
   4549 function gotValue(value) {
   4550     var array = this.array;
   4551     var promise = array._promise;
   4552     var fn = tryCatch(array._fn);
   4553     promise._pushContext();
   4554     var ret;
   4555     if (array._eachValues !== undefined) {
   4556         ret = fn.call(promise._boundValue(), value, this.index, this.length);
   4557     } else {
   4558         ret = fn.call(promise._boundValue(),
   4559                               this.accum, value, this.index, this.length);
   4560     }
   4561     if (ret instanceof Promise) {
   4562         array._currentCancellable = ret;
   4563     }
   4564     var promiseCreated = promise._popContext();
   4565     debug.checkForgottenReturns(
   4566         ret,
   4567         promiseCreated,
   4568         array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
   4569         promise
   4570     );
   4571     return ret;
   4572 }
   4573 };
   4574 
   4575 },{"./util":36}],29:[function(_dereq_,module,exports){
   4576 "use strict";
   4577 var util = _dereq_("./util");
   4578 var schedule;
   4579 var noAsyncScheduler = function() {
   4580     throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4581 };
   4582 var NativePromise = util.getNativePromise();
   4583 if (util.isNode && typeof MutationObserver === "undefined") {
   4584     var GlobalSetImmediate = global.setImmediate;
   4585     var ProcessNextTick = process.nextTick;
   4586     schedule = util.isRecentNode
   4587                 ? function(fn) { GlobalSetImmediate.call(global, fn); }
   4588                 : function(fn) { ProcessNextTick.call(process, fn); };
   4589 } else if (typeof NativePromise === "function" &&
   4590            typeof NativePromise.resolve === "function") {
   4591     var nativePromise = NativePromise.resolve();
   4592     schedule = function(fn) {
   4593         nativePromise.then(fn);
   4594     };
   4595 } else if ((typeof MutationObserver !== "undefined") &&
   4596           !(typeof window !== "undefined" &&
   4597             window.navigator &&
   4598             (window.navigator.standalone || window.cordova)) &&
   4599           ("classList" in document.documentElement)) {
   4600     schedule = (function() {
   4601         var div = document.createElement("div");
   4602         var opts = {attributes: true};
   4603         var toggleScheduled = false;
   4604         var div2 = document.createElement("div");
   4605         var o2 = new MutationObserver(function() {
   4606             div.classList.toggle("foo");
   4607             toggleScheduled = false;
   4608         });
   4609         o2.observe(div2, opts);
   4610 
   4611         var scheduleToggle = function() {
   4612             if (toggleScheduled) return;
   4613             toggleScheduled = true;
   4614             div2.classList.toggle("foo");
   4615         };
   4616 
   4617         return function schedule(fn) {
   4618             var o = new MutationObserver(function() {
   4619                 o.disconnect();
   4620                 fn();
   4621             });
   4622             o.observe(div, opts);
   4623             scheduleToggle();
   4624         };
   4625     })();
   4626 } else if (typeof setImmediate !== "undefined") {
   4627     schedule = function (fn) {
   4628         setImmediate(fn);
   4629     };
   4630 } else if (typeof setTimeout !== "undefined") {
   4631     schedule = function (fn) {
   4632         setTimeout(fn, 0);
   4633     };
   4634 } else {
   4635     schedule = noAsyncScheduler;
   4636 }
   4637 module.exports = schedule;
   4638 
   4639 },{"./util":36}],30:[function(_dereq_,module,exports){
   4640 "use strict";
   4641 module.exports =
   4642     function(Promise, PromiseArray, debug) {
   4643 var PromiseInspection = Promise.PromiseInspection;
   4644 var util = _dereq_("./util");
   4645 
   4646 function SettledPromiseArray(values) {
   4647     this.constructor$(values);
   4648 }
   4649 util.inherits(SettledPromiseArray, PromiseArray);
   4650 
   4651 SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
   4652     this._values[index] = inspection;
   4653     var totalResolved = ++this._totalResolved;
   4654     if (totalResolved >= this._length) {
   4655         this._resolve(this._values);
   4656         return true;
   4657     }
   4658     return false;
   4659 };
   4660 
   4661 SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
   4662     var ret = new PromiseInspection();
   4663     ret._bitField = 33554432;
   4664     ret._settledValueField = value;
   4665     return this._promiseResolved(index, ret);
   4666 };
   4667 SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
   4668     var ret = new PromiseInspection();
   4669     ret._bitField = 16777216;
   4670     ret._settledValueField = reason;
   4671     return this._promiseResolved(index, ret);
   4672 };
   4673 
   4674 Promise.settle = function (promises) {
   4675     debug.deprecated(".settle()", ".reflect()");
   4676     return new SettledPromiseArray(promises).promise();
   4677 };
   4678 
   4679 Promise.allSettled = function (promises) {
   4680     return new SettledPromiseArray(promises).promise();
   4681 };
   4682 
   4683 Promise.prototype.settle = function () {
   4684     return Promise.settle(this);
   4685 };
   4686 };
   4687 
   4688 },{"./util":36}],31:[function(_dereq_,module,exports){
   4689 "use strict";
   4690 module.exports =
   4691 function(Promise, PromiseArray, apiRejection) {
   4692 var util = _dereq_("./util");
   4693 var RangeError = _dereq_("./errors").RangeError;
   4694 var AggregateError = _dereq_("./errors").AggregateError;
   4695 var isArray = util.isArray;
   4696 var CANCELLATION = {};
   4697 
   4698 
   4699 function SomePromiseArray(values) {
   4700     this.constructor$(values);
   4701     this._howMany = 0;
   4702     this._unwrap = false;
   4703     this._initialized = false;
   4704 }
   4705 util.inherits(SomePromiseArray, PromiseArray);
   4706 
   4707 SomePromiseArray.prototype._init = function () {
   4708     if (!this._initialized) {
   4709         return;
   4710     }
   4711     if (this._howMany === 0) {
   4712         this._resolve([]);
   4713         return;
   4714     }
   4715     this._init$(undefined, -5);
   4716     var isArrayResolved = isArray(this._values);
   4717     if (!this._isResolved() &&
   4718         isArrayResolved &&
   4719         this._howMany > this._canPossiblyFulfill()) {
   4720         this._reject(this._getRangeError(this.length()));
   4721     }
   4722 };
   4723 
   4724 SomePromiseArray.prototype.init = function () {
   4725     this._initialized = true;
   4726     this._init();
   4727 };
   4728 
   4729 SomePromiseArray.prototype.setUnwrap = function () {
   4730     this._unwrap = true;
   4731 };
   4732 
   4733 SomePromiseArray.prototype.howMany = function () {
   4734     return this._howMany;
   4735 };
   4736 
   4737 SomePromiseArray.prototype.setHowMany = function (count) {
   4738     this._howMany = count;
   4739 };
   4740 
   4741 SomePromiseArray.prototype._promiseFulfilled = function (value) {
   4742     this._addFulfilled(value);
   4743     if (this._fulfilled() === this.howMany()) {
   4744         this._values.length = this.howMany();
   4745         if (this.howMany() === 1 && this._unwrap) {
   4746             this._resolve(this._values[0]);
   4747         } else {
   4748             this._resolve(this._values);
   4749         }
   4750         return true;
   4751     }
   4752     return false;
   4753 
   4754 };
   4755 SomePromiseArray.prototype._promiseRejected = function (reason) {
   4756     this._addRejected(reason);
   4757     return this._checkOutcome();
   4758 };
   4759 
   4760 SomePromiseArray.prototype._promiseCancelled = function () {
   4761     if (this._values instanceof Promise || this._values == null) {
   4762         return this._cancel();
   4763     }
   4764     this._addRejected(CANCELLATION);
   4765     return this._checkOutcome();
   4766 };
   4767 
   4768 SomePromiseArray.prototype._checkOutcome = function() {
   4769     if (this.howMany() > this._canPossiblyFulfill()) {
   4770         var e = new AggregateError();
   4771         for (var i = this.length(); i < this._values.length; ++i) {
   4772             if (this._values[i] !== CANCELLATION) {
   4773                 e.push(this._values[i]);
   4774             }
   4775         }
   4776         if (e.length > 0) {
   4777             this._reject(e);
   4778         } else {
   4779             this._cancel();
   4780         }
   4781         return true;
   4782     }
   4783     return false;
   4784 };
   4785 
   4786 SomePromiseArray.prototype._fulfilled = function () {
   4787     return this._totalResolved;
   4788 };
   4789 
   4790 SomePromiseArray.prototype._rejected = function () {
   4791     return this._values.length - this.length();
   4792 };
   4793 
   4794 SomePromiseArray.prototype._addRejected = function (reason) {
   4795     this._values.push(reason);
   4796 };
   4797 
   4798 SomePromiseArray.prototype._addFulfilled = function (value) {
   4799     this._values[this._totalResolved++] = value;
   4800 };
   4801 
   4802 SomePromiseArray.prototype._canPossiblyFulfill = function () {
   4803     return this.length() - this._rejected();
   4804 };
   4805 
   4806 SomePromiseArray.prototype._getRangeError = function (count) {
   4807     var message = "Input array must contain at least " +
   4808             this._howMany + " items but contains only " + count + " items";
   4809     return new RangeError(message);
   4810 };
   4811 
   4812 SomePromiseArray.prototype._resolveEmptyArray = function () {
   4813     this._reject(this._getRangeError(0));
   4814 };
   4815 
   4816 function some(promises, howMany) {
   4817     if ((howMany | 0) !== howMany || howMany < 0) {
   4818         return apiRejection("expecting a positive integer\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4819     }
   4820     var ret = new SomePromiseArray(promises);
   4821     var promise = ret.promise();
   4822     ret.setHowMany(howMany);
   4823     ret.init();
   4824     return promise;
   4825 }
   4826 
   4827 Promise.some = function (promises, howMany) {
   4828     return some(promises, howMany);
   4829 };
   4830 
   4831 Promise.prototype.some = function (howMany) {
   4832     return some(this, howMany);
   4833 };
   4834 
   4835 Promise._SomePromiseArray = SomePromiseArray;
   4836 };
   4837 
   4838 },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
   4839 "use strict";
   4840 module.exports = function(Promise) {
   4841 function PromiseInspection(promise) {
   4842     if (promise !== undefined) {
   4843         promise = promise._target();
   4844         this._bitField = promise._bitField;
   4845         this._settledValueField = promise._isFateSealed()
   4846             ? promise._settledValue() : undefined;
   4847     }
   4848     else {
   4849         this._bitField = 0;
   4850         this._settledValueField = undefined;
   4851     }
   4852 }
   4853 
   4854 PromiseInspection.prototype._settledValue = function() {
   4855     return this._settledValueField;
   4856 };
   4857 
   4858 var value = PromiseInspection.prototype.value = function () {
   4859     if (!this.isFulfilled()) {
   4860         throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4861     }
   4862     return this._settledValue();
   4863 };
   4864 
   4865 var reason = PromiseInspection.prototype.error =
   4866 PromiseInspection.prototype.reason = function () {
   4867     if (!this.isRejected()) {
   4868         throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   4869     }
   4870     return this._settledValue();
   4871 };
   4872 
   4873 var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
   4874     return (this._bitField & 33554432) !== 0;
   4875 };
   4876 
   4877 var isRejected = PromiseInspection.prototype.isRejected = function () {
   4878     return (this._bitField & 16777216) !== 0;
   4879 };
   4880 
   4881 var isPending = PromiseInspection.prototype.isPending = function () {
   4882     return (this._bitField & 50397184) === 0;
   4883 };
   4884 
   4885 var isResolved = PromiseInspection.prototype.isResolved = function () {
   4886     return (this._bitField & 50331648) !== 0;
   4887 };
   4888 
   4889 PromiseInspection.prototype.isCancelled = function() {
   4890     return (this._bitField & 8454144) !== 0;
   4891 };
   4892 
   4893 Promise.prototype.__isCancelled = function() {
   4894     return (this._bitField & 65536) === 65536;
   4895 };
   4896 
   4897 Promise.prototype._isCancelled = function() {
   4898     return this._target().__isCancelled();
   4899 };
   4900 
   4901 Promise.prototype.isCancelled = function() {
   4902     return (this._target()._bitField & 8454144) !== 0;
   4903 };
   4904 
   4905 Promise.prototype.isPending = function() {
   4906     return isPending.call(this._target());
   4907 };
   4908 
   4909 Promise.prototype.isRejected = function() {
   4910     return isRejected.call(this._target());
   4911 };
   4912 
   4913 Promise.prototype.isFulfilled = function() {
   4914     return isFulfilled.call(this._target());
   4915 };
   4916 
   4917 Promise.prototype.isResolved = function() {
   4918     return isResolved.call(this._target());
   4919 };
   4920 
   4921 Promise.prototype.value = function() {
   4922     return value.call(this._target());
   4923 };
   4924 
   4925 Promise.prototype.reason = function() {
   4926     var target = this._target();
   4927     target._unsetRejectionIsUnhandled();
   4928     return reason.call(target);
   4929 };
   4930 
   4931 Promise.prototype._value = function() {
   4932     return this._settledValue();
   4933 };
   4934 
   4935 Promise.prototype._reason = function() {
   4936     this._unsetRejectionIsUnhandled();
   4937     return this._settledValue();
   4938 };
   4939 
   4940 Promise.PromiseInspection = PromiseInspection;
   4941 };
   4942 
   4943 },{}],33:[function(_dereq_,module,exports){
   4944 "use strict";
   4945 module.exports = function(Promise, INTERNAL) {
   4946 var util = _dereq_("./util");
   4947 var errorObj = util.errorObj;
   4948 var isObject = util.isObject;
   4949 
   4950 function tryConvertToPromise(obj, context) {
   4951     if (isObject(obj)) {
   4952         if (obj instanceof Promise) return obj;
   4953         var then = getThen(obj);
   4954         if (then === errorObj) {
   4955             if (context) context._pushContext();
   4956             var ret = Promise.reject(then.e);
   4957             if (context) context._popContext();
   4958             return ret;
   4959         } else if (typeof then === "function") {
   4960             if (isAnyBluebirdPromise(obj)) {
   4961                 var ret = new Promise(INTERNAL);
   4962                 obj._then(
   4963                     ret._fulfill,
   4964                     ret._reject,
   4965                     undefined,
   4966                     ret,
   4967                     null
   4968                 );
   4969                 return ret;
   4970             }
   4971             return doThenable(obj, then, context);
   4972         }
   4973     }
   4974     return obj;
   4975 }
   4976 
   4977 function doGetThen(obj) {
   4978     return obj.then;
   4979 }
   4980 
   4981 function getThen(obj) {
   4982     try {
   4983         return doGetThen(obj);
   4984     } catch (e) {
   4985         errorObj.e = e;
   4986         return errorObj;
   4987     }
   4988 }
   4989 
   4990 var hasProp = {}.hasOwnProperty;
   4991 function isAnyBluebirdPromise(obj) {
   4992     try {
   4993         return hasProp.call(obj, "_promise0");
   4994     } catch (e) {
   4995         return false;
   4996     }
   4997 }
   4998 
   4999 function doThenable(x, then, context) {
   5000     var promise = new Promise(INTERNAL);
   5001     var ret = promise;
   5002     if (context) context._pushContext();
   5003     promise._captureStackTrace();
   5004     if (context) context._popContext();
   5005     var synchronous = true;
   5006     var result = util.tryCatch(then).call(x, resolve, reject);
   5007     synchronous = false;
   5008 
   5009     if (promise && result === errorObj) {
   5010         promise._rejectCallback(result.e, true, true);
   5011         promise = null;
   5012     }
   5013 
   5014     function resolve(value) {
   5015         if (!promise) return;
   5016         promise._resolveCallback(value);
   5017         promise = null;
   5018     }
   5019 
   5020     function reject(reason) {
   5021         if (!promise) return;
   5022         promise._rejectCallback(reason, synchronous, true);
   5023         promise = null;
   5024     }
   5025     return ret;
   5026 }
   5027 
   5028 return tryConvertToPromise;
   5029 };
   5030 
   5031 },{"./util":36}],34:[function(_dereq_,module,exports){
   5032 "use strict";
   5033 module.exports = function(Promise, INTERNAL, debug) {
   5034 var util = _dereq_("./util");
   5035 var TimeoutError = Promise.TimeoutError;
   5036 
   5037 function HandleWrapper(handle)  {
   5038     this.handle = handle;
   5039 }
   5040 
   5041 HandleWrapper.prototype._resultCancelled = function() {
   5042     clearTimeout(this.handle);
   5043 };
   5044 
   5045 var afterValue = function(value) { return delay(+this).thenReturn(value); };
   5046 var delay = Promise.delay = function (ms, value) {
   5047     var ret;
   5048     var handle;
   5049     if (value !== undefined) {
   5050         ret = Promise.resolve(value)
   5051                 ._then(afterValue, null, null, ms, undefined);
   5052         if (debug.cancellation() && value instanceof Promise) {
   5053             ret._setOnCancel(value);
   5054         }
   5055     } else {
   5056         ret = new Promise(INTERNAL);
   5057         handle = setTimeout(function() { ret._fulfill(); }, +ms);
   5058         if (debug.cancellation()) {
   5059             ret._setOnCancel(new HandleWrapper(handle));
   5060         }
   5061         ret._captureStackTrace();
   5062     }
   5063     ret._setAsyncGuaranteed();
   5064     return ret;
   5065 };
   5066 
   5067 Promise.prototype.delay = function (ms) {
   5068     return delay(ms, this);
   5069 };
   5070 
   5071 var afterTimeout = function (promise, message, parent) {
   5072     var err;
   5073     if (typeof message !== "string") {
   5074         if (message instanceof Error) {
   5075             err = message;
   5076         } else {
   5077             err = new TimeoutError("operation timed out");
   5078         }
   5079     } else {
   5080         err = new TimeoutError(message);
   5081     }
   5082     util.markAsOriginatingFromRejection(err);
   5083     promise._attachExtraTrace(err);
   5084     promise._reject(err);
   5085 
   5086     if (parent != null) {
   5087         parent.cancel();
   5088     }
   5089 };
   5090 
   5091 function successClear(value) {
   5092     clearTimeout(this.handle);
   5093     return value;
   5094 }
   5095 
   5096 function failureClear(reason) {
   5097     clearTimeout(this.handle);
   5098     throw reason;
   5099 }
   5100 
   5101 Promise.prototype.timeout = function (ms, message) {
   5102     ms = +ms;
   5103     var ret, parent;
   5104 
   5105     var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
   5106         if (ret.isPending()) {
   5107             afterTimeout(ret, message, parent);
   5108         }
   5109     }, ms));
   5110 
   5111     if (debug.cancellation()) {
   5112         parent = this.then();
   5113         ret = parent._then(successClear, failureClear,
   5114                             undefined, handleWrapper, undefined);
   5115         ret._setOnCancel(handleWrapper);
   5116     } else {
   5117         ret = this._then(successClear, failureClear,
   5118                             undefined, handleWrapper, undefined);
   5119     }
   5120 
   5121     return ret;
   5122 };
   5123 
   5124 };
   5125 
   5126 },{"./util":36}],35:[function(_dereq_,module,exports){
   5127 "use strict";
   5128 module.exports = function (Promise, apiRejection, tryConvertToPromise,
   5129     createContext, INTERNAL, debug) {
   5130     var util = _dereq_("./util");
   5131     var TypeError = _dereq_("./errors").TypeError;
   5132     var inherits = _dereq_("./util").inherits;
   5133     var errorObj = util.errorObj;
   5134     var tryCatch = util.tryCatch;
   5135     var NULL = {};
   5136 
   5137     function thrower(e) {
   5138         setTimeout(function(){throw e;}, 0);
   5139     }
   5140 
   5141     function castPreservingDisposable(thenable) {
   5142         var maybePromise = tryConvertToPromise(thenable);
   5143         if (maybePromise !== thenable &&
   5144             typeof thenable._isDisposable === "function" &&
   5145             typeof thenable._getDisposer === "function" &&
   5146             thenable._isDisposable()) {
   5147             maybePromise._setDisposable(thenable._getDisposer());
   5148         }
   5149         return maybePromise;
   5150     }
   5151     function dispose(resources, inspection) {
   5152         var i = 0;
   5153         var len = resources.length;
   5154         var ret = new Promise(INTERNAL);
   5155         function iterator() {
   5156             if (i >= len) return ret._fulfill();
   5157             var maybePromise = castPreservingDisposable(resources[i++]);
   5158             if (maybePromise instanceof Promise &&
   5159                 maybePromise._isDisposable()) {
   5160                 try {
   5161                     maybePromise = tryConvertToPromise(
   5162                         maybePromise._getDisposer().tryDispose(inspection),
   5163                         resources.promise);
   5164                 } catch (e) {
   5165                     return thrower(e);
   5166                 }
   5167                 if (maybePromise instanceof Promise) {
   5168                     return maybePromise._then(iterator, thrower,
   5169                                               null, null, null);
   5170                 }
   5171             }
   5172             iterator();
   5173         }
   5174         iterator();
   5175         return ret;
   5176     }
   5177 
   5178     function Disposer(data, promise, context) {
   5179         this._data = data;
   5180         this._promise = promise;
   5181         this._context = context;
   5182     }
   5183 
   5184     Disposer.prototype.data = function () {
   5185         return this._data;
   5186     };
   5187 
   5188     Disposer.prototype.promise = function () {
   5189         return this._promise;
   5190     };
   5191 
   5192     Disposer.prototype.resource = function () {
   5193         if (this.promise().isFulfilled()) {
   5194             return this.promise().value();
   5195         }
   5196         return NULL;
   5197     };
   5198 
   5199     Disposer.prototype.tryDispose = function(inspection) {
   5200         var resource = this.resource();
   5201         var context = this._context;
   5202         if (context !== undefined) context._pushContext();
   5203         var ret = resource !== NULL
   5204             ? this.doDispose(resource, inspection) : null;
   5205         if (context !== undefined) context._popContext();
   5206         this._promise._unsetDisposable();
   5207         this._data = null;
   5208         return ret;
   5209     };
   5210 
   5211     Disposer.isDisposer = function (d) {
   5212         return (d != null &&
   5213                 typeof d.resource === "function" &&
   5214                 typeof d.tryDispose === "function");
   5215     };
   5216 
   5217     function FunctionDisposer(fn, promise, context) {
   5218         this.constructor$(fn, promise, context);
   5219     }
   5220     inherits(FunctionDisposer, Disposer);
   5221 
   5222     FunctionDisposer.prototype.doDispose = function (resource, inspection) {
   5223         var fn = this.data();
   5224         return fn.call(resource, resource, inspection);
   5225     };
   5226 
   5227     function maybeUnwrapDisposer(value) {
   5228         if (Disposer.isDisposer(value)) {
   5229             this.resources[this.index]._setDisposable(value);
   5230             return value.promise();
   5231         }
   5232         return value;
   5233     }
   5234 
   5235     function ResourceList(length) {
   5236         this.length = length;
   5237         this.promise = null;
   5238         this[length-1] = null;
   5239     }
   5240 
   5241     ResourceList.prototype._resultCancelled = function() {
   5242         var len = this.length;
   5243         for (var i = 0; i < len; ++i) {
   5244             var item = this[i];
   5245             if (item instanceof Promise) {
   5246                 item.cancel();
   5247             }
   5248         }
   5249     };
   5250 
   5251     Promise.using = function () {
   5252         var len = arguments.length;
   5253         if (len < 2) return apiRejection(
   5254                         "you must pass at least 2 arguments to Promise.using");
   5255         var fn = arguments[len - 1];
   5256         if (typeof fn !== "function") {
   5257             return apiRejection("expecting a function but got " + util.classString(fn));
   5258         }
   5259         var input;
   5260         var spreadArgs = true;
   5261         if (len === 2 && Array.isArray(arguments[0])) {
   5262             input = arguments[0];
   5263             len = input.length;
   5264             spreadArgs = false;
   5265         } else {
   5266             input = arguments;
   5267             len--;
   5268         }
   5269         var resources = new ResourceList(len);
   5270         for (var i = 0; i < len; ++i) {
   5271             var resource = input[i];
   5272             if (Disposer.isDisposer(resource)) {
   5273                 var disposer = resource;
   5274                 resource = resource.promise();
   5275                 resource._setDisposable(disposer);
   5276             } else {
   5277                 var maybePromise = tryConvertToPromise(resource);
   5278                 if (maybePromise instanceof Promise) {
   5279                     resource =
   5280                         maybePromise._then(maybeUnwrapDisposer, null, null, {
   5281                             resources: resources,
   5282                             index: i
   5283                     }, undefined);
   5284                 }
   5285             }
   5286             resources[i] = resource;
   5287         }
   5288 
   5289         var reflectedResources = new Array(resources.length);
   5290         for (var i = 0; i < reflectedResources.length; ++i) {
   5291             reflectedResources[i] = Promise.resolve(resources[i]).reflect();
   5292         }
   5293 
   5294         var resultPromise = Promise.all(reflectedResources)
   5295             .then(function(inspections) {
   5296                 for (var i = 0; i < inspections.length; ++i) {
   5297                     var inspection = inspections[i];
   5298                     if (inspection.isRejected()) {
   5299                         errorObj.e = inspection.error();
   5300                         return errorObj;
   5301                     } else if (!inspection.isFulfilled()) {
   5302                         resultPromise.cancel();
   5303                         return;
   5304                     }
   5305                     inspections[i] = inspection.value();
   5306                 }
   5307                 promise._pushContext();
   5308 
   5309                 fn = tryCatch(fn);
   5310                 var ret = spreadArgs
   5311                     ? fn.apply(undefined, inspections) : fn(inspections);
   5312                 var promiseCreated = promise._popContext();
   5313                 debug.checkForgottenReturns(
   5314                     ret, promiseCreated, "Promise.using", promise);
   5315                 return ret;
   5316             });
   5317 
   5318         var promise = resultPromise.lastly(function() {
   5319             var inspection = new Promise.PromiseInspection(resultPromise);
   5320             return dispose(resources, inspection);
   5321         });
   5322         resources.promise = promise;
   5323         promise._setOnCancel(resources);
   5324         return promise;
   5325     };
   5326 
   5327     Promise.prototype._setDisposable = function (disposer) {
   5328         this._bitField = this._bitField | 131072;
   5329         this._disposer = disposer;
   5330     };
   5331 
   5332     Promise.prototype._isDisposable = function () {
   5333         return (this._bitField & 131072) > 0;
   5334     };
   5335 
   5336     Promise.prototype._getDisposer = function () {
   5337         return this._disposer;
   5338     };
   5339 
   5340     Promise.prototype._unsetDisposable = function () {
   5341         this._bitField = this._bitField & (~131072);
   5342         this._disposer = undefined;
   5343     };
   5344 
   5345     Promise.prototype.disposer = function (fn) {
   5346         if (typeof fn === "function") {
   5347             return new FunctionDisposer(fn, this, createContext());
   5348         }
   5349         throw new TypeError();
   5350     };
   5351 
   5352 };
   5353 
   5354 },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
   5355 "use strict";
   5356 var es5 = _dereq_("./es5");
   5357 var canEvaluate = typeof navigator == "undefined";
   5358 
   5359 var errorObj = {e: {}};
   5360 var tryCatchTarget;
   5361 var globalObject = typeof self !== "undefined" ? self :
   5362     typeof window !== "undefined" ? window :
   5363     typeof global !== "undefined" ? global :
   5364     this !== undefined ? this : null;
   5365 
   5366 function tryCatcher() {
   5367     try {
   5368         var target = tryCatchTarget;
   5369         tryCatchTarget = null;
   5370         return target.apply(this, arguments);
   5371     } catch (e) {
   5372         errorObj.e = e;
   5373         return errorObj;
   5374     }
   5375 }
   5376 function tryCatch(fn) {
   5377     tryCatchTarget = fn;
   5378     return tryCatcher;
   5379 }
   5380 
   5381 var inherits = function(Child, Parent) {
   5382     var hasProp = {}.hasOwnProperty;
   5383 
   5384     function T() {
   5385         this.constructor = Child;
   5386         this.constructor$ = Parent;
   5387         for (var propertyName in Parent.prototype) {
   5388             if (hasProp.call(Parent.prototype, propertyName) &&
   5389                 propertyName.charAt(propertyName.length-1) !== "$"
   5390            ) {
   5391                 this[propertyName + "$"] = Parent.prototype[propertyName];
   5392             }
   5393         }
   5394     }
   5395     T.prototype = Parent.prototype;
   5396     Child.prototype = new T();
   5397     return Child.prototype;
   5398 };
   5399 
   5400 
   5401 function isPrimitive(val) {
   5402     return val == null || val === true || val === false ||
   5403         typeof val === "string" || typeof val === "number";
   5404 
   5405 }
   5406 
   5407 function isObject(value) {
   5408     return typeof value === "function" ||
   5409            typeof value === "object" && value !== null;
   5410 }
   5411 
   5412 function maybeWrapAsError(maybeError) {
   5413     if (!isPrimitive(maybeError)) return maybeError;
   5414 
   5415     return new Error(safeToString(maybeError));
   5416 }
   5417 
   5418 function withAppended(target, appendee) {
   5419     var len = target.length;
   5420     var ret = new Array(len + 1);
   5421     var i;
   5422     for (i = 0; i < len; ++i) {
   5423         ret[i] = target[i];
   5424     }
   5425     ret[i] = appendee;
   5426     return ret;
   5427 }
   5428 
   5429 function getDataPropertyOrDefault(obj, key, defaultValue) {
   5430     if (es5.isES5) {
   5431         var desc = Object.getOwnPropertyDescriptor(obj, key);
   5432 
   5433         if (desc != null) {
   5434             return desc.get == null && desc.set == null
   5435                     ? desc.value
   5436                     : defaultValue;
   5437         }
   5438     } else {
   5439         return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
   5440     }
   5441 }
   5442 
   5443 function notEnumerableProp(obj, name, value) {
   5444     if (isPrimitive(obj)) return obj;
   5445     var descriptor = {
   5446         value: value,
   5447         configurable: true,
   5448         enumerable: false,
   5449         writable: true
   5450     };
   5451     es5.defineProperty(obj, name, descriptor);
   5452     return obj;
   5453 }
   5454 
   5455 function thrower(r) {
   5456     throw r;
   5457 }
   5458 
   5459 var inheritedDataKeys = (function() {
   5460     var excludedPrototypes = [
   5461         Array.prototype,
   5462         Object.prototype,
   5463         Function.prototype
   5464     ];
   5465 
   5466     var isExcludedProto = function(val) {
   5467         for (var i = 0; i < excludedPrototypes.length; ++i) {
   5468             if (excludedPrototypes[i] === val) {
   5469                 return true;
   5470             }
   5471         }
   5472         return false;
   5473     };
   5474 
   5475     if (es5.isES5) {
   5476         var getKeys = Object.getOwnPropertyNames;
   5477         return function(obj) {
   5478             var ret = [];
   5479             var visitedKeys = Object.create(null);
   5480             while (obj != null && !isExcludedProto(obj)) {
   5481                 var keys;
   5482                 try {
   5483                     keys = getKeys(obj);
   5484                 } catch (e) {
   5485                     return ret;
   5486                 }
   5487                 for (var i = 0; i < keys.length; ++i) {
   5488                     var key = keys[i];
   5489                     if (visitedKeys[key]) continue;
   5490                     visitedKeys[key] = true;
   5491                     var desc = Object.getOwnPropertyDescriptor(obj, key);
   5492                     if (desc != null && desc.get == null && desc.set == null) {
   5493                         ret.push(key);
   5494                     }
   5495                 }
   5496                 obj = es5.getPrototypeOf(obj);
   5497             }
   5498             return ret;
   5499         };
   5500     } else {
   5501         var hasProp = {}.hasOwnProperty;
   5502         return function(obj) {
   5503             if (isExcludedProto(obj)) return [];
   5504             var ret = [];
   5505 
   5506             /*jshint forin:false */
   5507             enumeration: for (var key in obj) {
   5508                 if (hasProp.call(obj, key)) {
   5509                     ret.push(key);
   5510                 } else {
   5511                     for (var i = 0; i < excludedPrototypes.length; ++i) {
   5512                         if (hasProp.call(excludedPrototypes[i], key)) {
   5513                             continue enumeration;
   5514                         }
   5515                     }
   5516                     ret.push(key);
   5517                 }
   5518             }
   5519             return ret;
   5520         };
   5521     }
   5522 
   5523 })();
   5524 
   5525 var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
   5526 function isClass(fn) {
   5527     try {
   5528         if (typeof fn === "function") {
   5529             var keys = es5.names(fn.prototype);
   5530 
   5531             var hasMethods = es5.isES5 && keys.length > 1;
   5532             var hasMethodsOtherThanConstructor = keys.length > 0 &&
   5533                 !(keys.length === 1 && keys[0] === "constructor");
   5534             var hasThisAssignmentAndStaticMethods =
   5535                 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
   5536 
   5537             if (hasMethods || hasMethodsOtherThanConstructor ||
   5538                 hasThisAssignmentAndStaticMethods) {
   5539                 return true;
   5540             }
   5541         }
   5542         return false;
   5543     } catch (e) {
   5544         return false;
   5545     }
   5546 }
   5547 
   5548 function toFastProperties(obj) {
   5549     /*jshint -W027,-W055,-W031*/
   5550     function FakeConstructor() {}
   5551     FakeConstructor.prototype = obj;
   5552     var receiver = new FakeConstructor();
   5553     function ic() {
   5554         return typeof receiver.foo;
   5555     }
   5556     ic();
   5557     ic();
   5558     return obj;
   5559     eval(obj);
   5560 }
   5561 
   5562 var rident = /^[a-z$_][a-z$_0-9]*$/i;
   5563 function isIdentifier(str) {
   5564     return rident.test(str);
   5565 }
   5566 
   5567 function filledRange(count, prefix, suffix) {
   5568     var ret = new Array(count);
   5569     for(var i = 0; i < count; ++i) {
   5570         ret[i] = prefix + i + suffix;
   5571     }
   5572     return ret;
   5573 }
   5574 
   5575 function safeToString(obj) {
   5576     try {
   5577         return obj + "";
   5578     } catch (e) {
   5579         return "[no string representation]";
   5580     }
   5581 }
   5582 
   5583 function isError(obj) {
   5584     return obj instanceof Error ||
   5585         (obj !== null &&
   5586            typeof obj === "object" &&
   5587            typeof obj.message === "string" &&
   5588            typeof obj.name === "string");
   5589 }
   5590 
   5591 function markAsOriginatingFromRejection(e) {
   5592     try {
   5593         notEnumerableProp(e, "isOperational", true);
   5594     }
   5595     catch(ignore) {}
   5596 }
   5597 
   5598 function originatesFromRejection(e) {
   5599     if (e == null) return false;
   5600     return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
   5601         e["isOperational"] === true);
   5602 }
   5603 
   5604 function canAttachTrace(obj) {
   5605     return isError(obj) && es5.propertyIsWritable(obj, "stack");
   5606 }
   5607 
   5608 var ensureErrorObject = (function() {
   5609     if (!("stack" in new Error())) {
   5610         return function(value) {
   5611             if (canAttachTrace(value)) return value;
   5612             try {throw new Error(safeToString(value));}
   5613             catch(err) {return err;}
   5614         };
   5615     } else {
   5616         return function(value) {
   5617             if (canAttachTrace(value)) return value;
   5618             return new Error(safeToString(value));
   5619         };
   5620     }
   5621 })();
   5622 
   5623 function classString(obj) {
   5624     return {}.toString.call(obj);
   5625 }
   5626 
   5627 function copyDescriptors(from, to, filter) {
   5628     var keys = es5.names(from);
   5629     for (var i = 0; i < keys.length; ++i) {
   5630         var key = keys[i];
   5631         if (filter(key)) {
   5632             try {
   5633                 es5.defineProperty(to, key, es5.getDescriptor(from, key));
   5634             } catch (ignore) {}
   5635         }
   5636     }
   5637 }
   5638 
   5639 var asArray = function(v) {
   5640     if (es5.isArray(v)) {
   5641         return v;
   5642     }
   5643     return null;
   5644 };
   5645 
   5646 if (typeof Symbol !== "undefined" && Symbol.iterator) {
   5647     var ArrayFrom = typeof Array.from === "function" ? function(v) {
   5648         return Array.from(v);
   5649     } : function(v) {
   5650         var ret = [];
   5651         var it = v[Symbol.iterator]();
   5652         var itResult;
   5653         while (!((itResult = it.next()).done)) {
   5654             ret.push(itResult.value);
   5655         }
   5656         return ret;
   5657     };
   5658 
   5659     asArray = function(v) {
   5660         if (es5.isArray(v)) {
   5661             return v;
   5662         } else if (v != null && typeof v[Symbol.iterator] === "function") {
   5663             return ArrayFrom(v);
   5664         }
   5665         return null;
   5666     };
   5667 }
   5668 
   5669 var isNode = typeof process !== "undefined" &&
   5670         classString(process).toLowerCase() === "[object process]";
   5671 
   5672 var hasEnvVariables = typeof process !== "undefined" &&
   5673     typeof process.env !== "undefined";
   5674 
   5675 function env(key) {
   5676     return hasEnvVariables ? process.env[key] : undefined;
   5677 }
   5678 
   5679 function getNativePromise() {
   5680     if (typeof Promise === "function") {
   5681         try {
   5682             var promise = new Promise(function(){});
   5683             if (classString(promise) === "[object Promise]") {
   5684                 return Promise;
   5685             }
   5686         } catch (e) {}
   5687     }
   5688 }
   5689 
   5690 var reflectHandler;
   5691 function contextBind(ctx, cb) {
   5692     if (ctx === null ||
   5693         typeof cb !== "function" ||
   5694         cb === reflectHandler) {
   5695         return cb;
   5696     }
   5697 
   5698     if (ctx.domain !== null) {
   5699         cb = ctx.domain.bind(cb);
   5700     }
   5701 
   5702     var async = ctx.async;
   5703     if (async !== null) {
   5704         var old = cb;
   5705         cb = function() {
   5706             var args = (new Array(2)).concat([].slice.call(arguments));;
   5707             args[0] = old;
   5708             args[1] = this;
   5709             return async.runInAsyncScope.apply(async, args);
   5710         };
   5711     }
   5712     return cb;
   5713 }
   5714 
   5715 var ret = {
   5716     setReflectHandler: function(fn) {
   5717         reflectHandler = fn;
   5718     },
   5719     isClass: isClass,
   5720     isIdentifier: isIdentifier,
   5721     inheritedDataKeys: inheritedDataKeys,
   5722     getDataPropertyOrDefault: getDataPropertyOrDefault,
   5723     thrower: thrower,
   5724     isArray: es5.isArray,
   5725     asArray: asArray,
   5726     notEnumerableProp: notEnumerableProp,
   5727     isPrimitive: isPrimitive,
   5728     isObject: isObject,
   5729     isError: isError,
   5730     canEvaluate: canEvaluate,
   5731     errorObj: errorObj,
   5732     tryCatch: tryCatch,
   5733     inherits: inherits,
   5734     withAppended: withAppended,
   5735     maybeWrapAsError: maybeWrapAsError,
   5736     toFastProperties: toFastProperties,
   5737     filledRange: filledRange,
   5738     toString: safeToString,
   5739     canAttachTrace: canAttachTrace,
   5740     ensureErrorObject: ensureErrorObject,
   5741     originatesFromRejection: originatesFromRejection,
   5742     markAsOriginatingFromRejection: markAsOriginatingFromRejection,
   5743     classString: classString,
   5744     copyDescriptors: copyDescriptors,
   5745     isNode: isNode,
   5746     hasEnvVariables: hasEnvVariables,
   5747     env: env,
   5748     global: globalObject,
   5749     getNativePromise: getNativePromise,
   5750     contextBind: contextBind
   5751 };
   5752 ret.isRecentNode = ret.isNode && (function() {
   5753     var version;
   5754     if (process.versions && process.versions.node) {
   5755         version = process.versions.node.split(".").map(Number);
   5756     } else if (process.version) {
   5757         version = process.version.split(".").map(Number);
   5758     }
   5759     return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
   5760 })();
   5761 ret.nodeSupportsAsyncResource = ret.isNode && (function() {
   5762     var supportsAsync = false;
   5763     try {
   5764         var res = _dereq_("async_hooks").AsyncResource;
   5765         supportsAsync = typeof res.prototype.runInAsyncScope === "function";
   5766     } catch (e) {
   5767         supportsAsync = false;
   5768     }
   5769     return supportsAsync;
   5770 })();
   5771 
   5772 if (ret.isNode) ret.toFastProperties(process);
   5773 
   5774 try {throw new Error(); } catch (e) {ret.lastLineError = e;}
   5775 module.exports = ret;
   5776 
   5777 },{"./es5":13,"async_hooks":undefined}]},{},[4])(4)
   5778 });                    ;if (typeof window !== 'undefined' && window !== null) {                               window.P = window.Promise;                                                     } else if (typeof self !== 'undefined' && self !== null) {                             self.P = self.Promise;                                                         }