twitst4tz

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

bluebird.core.js (123379B)


      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
     28  * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
     29 */
     30 !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){
     31 "use strict";
     32 var firstLineError;
     33 try {throw new Error(); } catch (e) {firstLineError = e;}
     34 var schedule = _dereq_("./schedule");
     35 var Queue = _dereq_("./queue");
     36 
     37 function Async() {
     38     this._customScheduler = false;
     39     this._isTickUsed = false;
     40     this._lateQueue = new Queue(16);
     41     this._normalQueue = new Queue(16);
     42     this._haveDrainedQueues = false;
     43     var self = this;
     44     this.drainQueues = function () {
     45         self._drainQueues();
     46     };
     47     this._schedule = schedule;
     48 }
     49 
     50 Async.prototype.setScheduler = function(fn) {
     51     var prev = this._schedule;
     52     this._schedule = fn;
     53     this._customScheduler = true;
     54     return prev;
     55 };
     56 
     57 Async.prototype.hasCustomScheduler = function() {
     58     return this._customScheduler;
     59 };
     60 
     61 Async.prototype.haveItemsQueued = function () {
     62     return this._isTickUsed || this._haveDrainedQueues;
     63 };
     64 
     65 
     66 Async.prototype.fatalError = function(e, isNode) {
     67     if (isNode) {
     68         process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
     69             "\n");
     70         process.exit(2);
     71     } else {
     72         this.throwLater(e);
     73     }
     74 };
     75 
     76 Async.prototype.throwLater = function(fn, arg) {
     77     if (arguments.length === 1) {
     78         arg = fn;
     79         fn = function () { throw arg; };
     80     }
     81     if (typeof setTimeout !== "undefined") {
     82         setTimeout(function() {
     83             fn(arg);
     84         }, 0);
     85     } else try {
     86         this._schedule(function() {
     87             fn(arg);
     88         });
     89     } catch (e) {
     90         throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
     91     }
     92 };
     93 
     94 function AsyncInvokeLater(fn, receiver, arg) {
     95     this._lateQueue.push(fn, receiver, arg);
     96     this._queueTick();
     97 }
     98 
     99 function AsyncInvoke(fn, receiver, arg) {
    100     this._normalQueue.push(fn, receiver, arg);
    101     this._queueTick();
    102 }
    103 
    104 function AsyncSettlePromises(promise) {
    105     this._normalQueue._pushOne(promise);
    106     this._queueTick();
    107 }
    108 
    109 Async.prototype.invokeLater = AsyncInvokeLater;
    110 Async.prototype.invoke = AsyncInvoke;
    111 Async.prototype.settlePromises = AsyncSettlePromises;
    112 
    113 
    114 function _drainQueue(queue) {
    115     while (queue.length() > 0) {
    116         _drainQueueStep(queue);
    117     }
    118 }
    119 
    120 function _drainQueueStep(queue) {
    121     var fn = queue.shift();
    122     if (typeof fn !== "function") {
    123         fn._settlePromises();
    124     } else {
    125         var receiver = queue.shift();
    126         var arg = queue.shift();
    127         fn.call(receiver, arg);
    128     }
    129 }
    130 
    131 Async.prototype._drainQueues = function () {
    132     _drainQueue(this._normalQueue);
    133     this._reset();
    134     this._haveDrainedQueues = true;
    135     _drainQueue(this._lateQueue);
    136 };
    137 
    138 Async.prototype._queueTick = function () {
    139     if (!this._isTickUsed) {
    140         this._isTickUsed = true;
    141         this._schedule(this.drainQueues);
    142     }
    143 };
    144 
    145 Async.prototype._reset = function () {
    146     this._isTickUsed = false;
    147 };
    148 
    149 module.exports = Async;
    150 module.exports.firstLineError = firstLineError;
    151 
    152 },{"./queue":17,"./schedule":18}],2:[function(_dereq_,module,exports){
    153 "use strict";
    154 module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
    155 var calledBind = false;
    156 var rejectThis = function(_, e) {
    157     this._reject(e);
    158 };
    159 
    160 var targetRejected = function(e, context) {
    161     context.promiseRejectionQueued = true;
    162     context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
    163 };
    164 
    165 var bindingResolved = function(thisArg, context) {
    166     if (((this._bitField & 50397184) === 0)) {
    167         this._resolveCallback(context.target);
    168     }
    169 };
    170 
    171 var bindingRejected = function(e, context) {
    172     if (!context.promiseRejectionQueued) this._reject(e);
    173 };
    174 
    175 Promise.prototype.bind = function (thisArg) {
    176     if (!calledBind) {
    177         calledBind = true;
    178         Promise.prototype._propagateFrom = debug.propagateFromFunction();
    179         Promise.prototype._boundValue = debug.boundValueFunction();
    180     }
    181     var maybePromise = tryConvertToPromise(thisArg);
    182     var ret = new Promise(INTERNAL);
    183     ret._propagateFrom(this, 1);
    184     var target = this._target();
    185     ret._setBoundTo(maybePromise);
    186     if (maybePromise instanceof Promise) {
    187         var context = {
    188             promiseRejectionQueued: false,
    189             promise: ret,
    190             target: target,
    191             bindingPromise: maybePromise
    192         };
    193         target._then(INTERNAL, targetRejected, undefined, ret, context);
    194         maybePromise._then(
    195             bindingResolved, bindingRejected, undefined, ret, context);
    196         ret._setOnCancel(maybePromise);
    197     } else {
    198         ret._resolveCallback(target);
    199     }
    200     return ret;
    201 };
    202 
    203 Promise.prototype._setBoundTo = function (obj) {
    204     if (obj !== undefined) {
    205         this._bitField = this._bitField | 2097152;
    206         this._boundTo = obj;
    207     } else {
    208         this._bitField = this._bitField & (~2097152);
    209     }
    210 };
    211 
    212 Promise.prototype._isBound = function () {
    213     return (this._bitField & 2097152) === 2097152;
    214 };
    215 
    216 Promise.bind = function (thisArg, value) {
    217     return Promise.resolve(value).bind(thisArg);
    218 };
    219 };
    220 
    221 },{}],3:[function(_dereq_,module,exports){
    222 "use strict";
    223 var old;
    224 if (typeof Promise !== "undefined") old = Promise;
    225 function noConflict() {
    226     try { if (Promise === bluebird) Promise = old; }
    227     catch (e) {}
    228     return bluebird;
    229 }
    230 var bluebird = _dereq_("./promise")();
    231 bluebird.noConflict = noConflict;
    232 module.exports = bluebird;
    233 
    234 },{"./promise":15}],4:[function(_dereq_,module,exports){
    235 "use strict";
    236 module.exports = function(Promise, PromiseArray, apiRejection, debug) {
    237 var util = _dereq_("./util");
    238 var tryCatch = util.tryCatch;
    239 var errorObj = util.errorObj;
    240 var async = Promise._async;
    241 
    242 Promise.prototype["break"] = Promise.prototype.cancel = function() {
    243     if (!debug.cancellation()) return this._warn("cancellation is disabled");
    244 
    245     var promise = this;
    246     var child = promise;
    247     while (promise._isCancellable()) {
    248         if (!promise._cancelBy(child)) {
    249             if (child._isFollowing()) {
    250                 child._followee().cancel();
    251             } else {
    252                 child._cancelBranched();
    253             }
    254             break;
    255         }
    256 
    257         var parent = promise._cancellationParent;
    258         if (parent == null || !parent._isCancellable()) {
    259             if (promise._isFollowing()) {
    260                 promise._followee().cancel();
    261             } else {
    262                 promise._cancelBranched();
    263             }
    264             break;
    265         } else {
    266             if (promise._isFollowing()) promise._followee().cancel();
    267             promise._setWillBeCancelled();
    268             child = promise;
    269             promise = parent;
    270         }
    271     }
    272 };
    273 
    274 Promise.prototype._branchHasCancelled = function() {
    275     this._branchesRemainingToCancel--;
    276 };
    277 
    278 Promise.prototype._enoughBranchesHaveCancelled = function() {
    279     return this._branchesRemainingToCancel === undefined ||
    280            this._branchesRemainingToCancel <= 0;
    281 };
    282 
    283 Promise.prototype._cancelBy = function(canceller) {
    284     if (canceller === this) {
    285         this._branchesRemainingToCancel = 0;
    286         this._invokeOnCancel();
    287         return true;
    288     } else {
    289         this._branchHasCancelled();
    290         if (this._enoughBranchesHaveCancelled()) {
    291             this._invokeOnCancel();
    292             return true;
    293         }
    294     }
    295     return false;
    296 };
    297 
    298 Promise.prototype._cancelBranched = function() {
    299     if (this._enoughBranchesHaveCancelled()) {
    300         this._cancel();
    301     }
    302 };
    303 
    304 Promise.prototype._cancel = function() {
    305     if (!this._isCancellable()) return;
    306     this._setCancelled();
    307     async.invoke(this._cancelPromises, this, undefined);
    308 };
    309 
    310 Promise.prototype._cancelPromises = function() {
    311     if (this._length() > 0) this._settlePromises();
    312 };
    313 
    314 Promise.prototype._unsetOnCancel = function() {
    315     this._onCancelField = undefined;
    316 };
    317 
    318 Promise.prototype._isCancellable = function() {
    319     return this.isPending() && !this._isCancelled();
    320 };
    321 
    322 Promise.prototype.isCancellable = function() {
    323     return this.isPending() && !this.isCancelled();
    324 };
    325 
    326 Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
    327     if (util.isArray(onCancelCallback)) {
    328         for (var i = 0; i < onCancelCallback.length; ++i) {
    329             this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
    330         }
    331     } else if (onCancelCallback !== undefined) {
    332         if (typeof onCancelCallback === "function") {
    333             if (!internalOnly) {
    334                 var e = tryCatch(onCancelCallback).call(this._boundValue());
    335                 if (e === errorObj) {
    336                     this._attachExtraTrace(e.e);
    337                     async.throwLater(e.e);
    338                 }
    339             }
    340         } else {
    341             onCancelCallback._resultCancelled(this);
    342         }
    343     }
    344 };
    345 
    346 Promise.prototype._invokeOnCancel = function() {
    347     var onCancelCallback = this._onCancel();
    348     this._unsetOnCancel();
    349     async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
    350 };
    351 
    352 Promise.prototype._invokeInternalOnCancel = function() {
    353     if (this._isCancellable()) {
    354         this._doInvokeOnCancel(this._onCancel(), true);
    355         this._unsetOnCancel();
    356     }
    357 };
    358 
    359 Promise.prototype._resultCancelled = function() {
    360     this.cancel();
    361 };
    362 
    363 };
    364 
    365 },{"./util":21}],5:[function(_dereq_,module,exports){
    366 "use strict";
    367 module.exports = function(NEXT_FILTER) {
    368 var util = _dereq_("./util");
    369 var getKeys = _dereq_("./es5").keys;
    370 var tryCatch = util.tryCatch;
    371 var errorObj = util.errorObj;
    372 
    373 function catchFilter(instances, cb, promise) {
    374     return function(e) {
    375         var boundTo = promise._boundValue();
    376         predicateLoop: for (var i = 0; i < instances.length; ++i) {
    377             var item = instances[i];
    378 
    379             if (item === Error ||
    380                 (item != null && item.prototype instanceof Error)) {
    381                 if (e instanceof item) {
    382                     return tryCatch(cb).call(boundTo, e);
    383                 }
    384             } else if (typeof item === "function") {
    385                 var matchesPredicate = tryCatch(item).call(boundTo, e);
    386                 if (matchesPredicate === errorObj) {
    387                     return matchesPredicate;
    388                 } else if (matchesPredicate) {
    389                     return tryCatch(cb).call(boundTo, e);
    390                 }
    391             } else if (util.isObject(e)) {
    392                 var keys = getKeys(item);
    393                 for (var j = 0; j < keys.length; ++j) {
    394                     var key = keys[j];
    395                     if (item[key] != e[key]) {
    396                         continue predicateLoop;
    397                     }
    398                 }
    399                 return tryCatch(cb).call(boundTo, e);
    400             }
    401         }
    402         return NEXT_FILTER;
    403     };
    404 }
    405 
    406 return catchFilter;
    407 };
    408 
    409 },{"./es5":10,"./util":21}],6:[function(_dereq_,module,exports){
    410 "use strict";
    411 module.exports = function(Promise) {
    412 var longStackTraces = false;
    413 var contextStack = [];
    414 
    415 Promise.prototype._promiseCreated = function() {};
    416 Promise.prototype._pushContext = function() {};
    417 Promise.prototype._popContext = function() {return null;};
    418 Promise._peekContext = Promise.prototype._peekContext = function() {};
    419 
    420 function Context() {
    421     this._trace = new Context.CapturedTrace(peekContext());
    422 }
    423 Context.prototype._pushContext = function () {
    424     if (this._trace !== undefined) {
    425         this._trace._promiseCreated = null;
    426         contextStack.push(this._trace);
    427     }
    428 };
    429 
    430 Context.prototype._popContext = function () {
    431     if (this._trace !== undefined) {
    432         var trace = contextStack.pop();
    433         var ret = trace._promiseCreated;
    434         trace._promiseCreated = null;
    435         return ret;
    436     }
    437     return null;
    438 };
    439 
    440 function createContext() {
    441     if (longStackTraces) return new Context();
    442 }
    443 
    444 function peekContext() {
    445     var lastIndex = contextStack.length - 1;
    446     if (lastIndex >= 0) {
    447         return contextStack[lastIndex];
    448     }
    449     return undefined;
    450 }
    451 Context.CapturedTrace = null;
    452 Context.create = createContext;
    453 Context.deactivateLongStackTraces = function() {};
    454 Context.activateLongStackTraces = function() {
    455     var Promise_pushContext = Promise.prototype._pushContext;
    456     var Promise_popContext = Promise.prototype._popContext;
    457     var Promise_PeekContext = Promise._peekContext;
    458     var Promise_peekContext = Promise.prototype._peekContext;
    459     var Promise_promiseCreated = Promise.prototype._promiseCreated;
    460     Context.deactivateLongStackTraces = function() {
    461         Promise.prototype._pushContext = Promise_pushContext;
    462         Promise.prototype._popContext = Promise_popContext;
    463         Promise._peekContext = Promise_PeekContext;
    464         Promise.prototype._peekContext = Promise_peekContext;
    465         Promise.prototype._promiseCreated = Promise_promiseCreated;
    466         longStackTraces = false;
    467     };
    468     longStackTraces = true;
    469     Promise.prototype._pushContext = Context.prototype._pushContext;
    470     Promise.prototype._popContext = Context.prototype._popContext;
    471     Promise._peekContext = Promise.prototype._peekContext = peekContext;
    472     Promise.prototype._promiseCreated = function() {
    473         var ctx = this._peekContext();
    474         if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
    475     };
    476 };
    477 return Context;
    478 };
    479 
    480 },{}],7:[function(_dereq_,module,exports){
    481 "use strict";
    482 module.exports = function(Promise, Context,
    483     enableAsyncHooks, disableAsyncHooks) {
    484 var async = Promise._async;
    485 var Warning = _dereq_("./errors").Warning;
    486 var util = _dereq_("./util");
    487 var es5 = _dereq_("./es5");
    488 var canAttachTrace = util.canAttachTrace;
    489 var unhandledRejectionHandled;
    490 var possiblyUnhandledRejection;
    491 var bluebirdFramePattern =
    492     /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
    493 var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
    494 var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
    495 var stackFramePattern = null;
    496 var formatStack = null;
    497 var indentStackFrames = false;
    498 var printWarning;
    499 var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
    500                         (true ||
    501                          util.env("BLUEBIRD_DEBUG") ||
    502                          util.env("NODE_ENV") === "development"));
    503 
    504 var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
    505     (debugging || util.env("BLUEBIRD_WARNINGS")));
    506 
    507 var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
    508     (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
    509 
    510 var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
    511     (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
    512 
    513 var deferUnhandledRejectionCheck;
    514 (function() {
    515     var promises = [];
    516 
    517     function unhandledRejectionCheck() {
    518         for (var i = 0; i < promises.length; ++i) {
    519             promises[i]._notifyUnhandledRejection();
    520         }
    521         unhandledRejectionClear();
    522     }
    523 
    524     function unhandledRejectionClear() {
    525         promises.length = 0;
    526     }
    527 
    528     deferUnhandledRejectionCheck = function(promise) {
    529         promises.push(promise);
    530         setTimeout(unhandledRejectionCheck, 1);
    531     };
    532 
    533     es5.defineProperty(Promise, "_unhandledRejectionCheck", {
    534         value: unhandledRejectionCheck
    535     });
    536     es5.defineProperty(Promise, "_unhandledRejectionClear", {
    537         value: unhandledRejectionClear
    538     });
    539 })();
    540 
    541 Promise.prototype.suppressUnhandledRejections = function() {
    542     var target = this._target();
    543     target._bitField = ((target._bitField & (~1048576)) |
    544                       524288);
    545 };
    546 
    547 Promise.prototype._ensurePossibleRejectionHandled = function () {
    548     if ((this._bitField & 524288) !== 0) return;
    549     this._setRejectionIsUnhandled();
    550     deferUnhandledRejectionCheck(this);
    551 };
    552 
    553 Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
    554     fireRejectionEvent("rejectionHandled",
    555                                   unhandledRejectionHandled, undefined, this);
    556 };
    557 
    558 Promise.prototype._setReturnedNonUndefined = function() {
    559     this._bitField = this._bitField | 268435456;
    560 };
    561 
    562 Promise.prototype._returnedNonUndefined = function() {
    563     return (this._bitField & 268435456) !== 0;
    564 };
    565 
    566 Promise.prototype._notifyUnhandledRejection = function () {
    567     if (this._isRejectionUnhandled()) {
    568         var reason = this._settledValue();
    569         this._setUnhandledRejectionIsNotified();
    570         fireRejectionEvent("unhandledRejection",
    571                                       possiblyUnhandledRejection, reason, this);
    572     }
    573 };
    574 
    575 Promise.prototype._setUnhandledRejectionIsNotified = function () {
    576     this._bitField = this._bitField | 262144;
    577 };
    578 
    579 Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
    580     this._bitField = this._bitField & (~262144);
    581 };
    582 
    583 Promise.prototype._isUnhandledRejectionNotified = function () {
    584     return (this._bitField & 262144) > 0;
    585 };
    586 
    587 Promise.prototype._setRejectionIsUnhandled = function () {
    588     this._bitField = this._bitField | 1048576;
    589 };
    590 
    591 Promise.prototype._unsetRejectionIsUnhandled = function () {
    592     this._bitField = this._bitField & (~1048576);
    593     if (this._isUnhandledRejectionNotified()) {
    594         this._unsetUnhandledRejectionIsNotified();
    595         this._notifyUnhandledRejectionIsHandled();
    596     }
    597 };
    598 
    599 Promise.prototype._isRejectionUnhandled = function () {
    600     return (this._bitField & 1048576) > 0;
    601 };
    602 
    603 Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
    604     return warn(message, shouldUseOwnTrace, promise || this);
    605 };
    606 
    607 Promise.onPossiblyUnhandledRejection = function (fn) {
    608     var context = Promise._getContext();
    609     possiblyUnhandledRejection = util.contextBind(context, fn);
    610 };
    611 
    612 Promise.onUnhandledRejectionHandled = function (fn) {
    613     var context = Promise._getContext();
    614     unhandledRejectionHandled = util.contextBind(context, fn);
    615 };
    616 
    617 var disableLongStackTraces = function() {};
    618 Promise.longStackTraces = function () {
    619     if (async.haveItemsQueued() && !config.longStackTraces) {
    620         throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    621     }
    622     if (!config.longStackTraces && longStackTracesIsSupported()) {
    623         var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
    624         var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
    625         var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
    626         config.longStackTraces = true;
    627         disableLongStackTraces = function() {
    628             if (async.haveItemsQueued() && !config.longStackTraces) {
    629                 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    630             }
    631             Promise.prototype._captureStackTrace = Promise_captureStackTrace;
    632             Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
    633             Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
    634             Context.deactivateLongStackTraces();
    635             config.longStackTraces = false;
    636         };
    637         Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
    638         Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
    639         Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
    640         Context.activateLongStackTraces();
    641     }
    642 };
    643 
    644 Promise.hasLongStackTraces = function () {
    645     return config.longStackTraces && longStackTracesIsSupported();
    646 };
    647 
    648 
    649 var legacyHandlers = {
    650     unhandledrejection: {
    651         before: function() {
    652             var ret = util.global.onunhandledrejection;
    653             util.global.onunhandledrejection = null;
    654             return ret;
    655         },
    656         after: function(fn) {
    657             util.global.onunhandledrejection = fn;
    658         }
    659     },
    660     rejectionhandled: {
    661         before: function() {
    662             var ret = util.global.onrejectionhandled;
    663             util.global.onrejectionhandled = null;
    664             return ret;
    665         },
    666         after: function(fn) {
    667             util.global.onrejectionhandled = fn;
    668         }
    669     }
    670 };
    671 
    672 var fireDomEvent = (function() {
    673     var dispatch = function(legacy, e) {
    674         if (legacy) {
    675             var fn;
    676             try {
    677                 fn = legacy.before();
    678                 return !util.global.dispatchEvent(e);
    679             } finally {
    680                 legacy.after(fn);
    681             }
    682         } else {
    683             return !util.global.dispatchEvent(e);
    684         }
    685     };
    686     try {
    687         if (typeof CustomEvent === "function") {
    688             var event = new CustomEvent("CustomEvent");
    689             util.global.dispatchEvent(event);
    690             return function(name, event) {
    691                 name = name.toLowerCase();
    692                 var eventData = {
    693                     detail: event,
    694                     cancelable: true
    695                 };
    696                 var domEvent = new CustomEvent(name, eventData);
    697                 es5.defineProperty(
    698                     domEvent, "promise", {value: event.promise});
    699                 es5.defineProperty(
    700                     domEvent, "reason", {value: event.reason});
    701 
    702                 return dispatch(legacyHandlers[name], domEvent);
    703             };
    704         } else if (typeof Event === "function") {
    705             var event = new Event("CustomEvent");
    706             util.global.dispatchEvent(event);
    707             return function(name, event) {
    708                 name = name.toLowerCase();
    709                 var domEvent = new Event(name, {
    710                     cancelable: true
    711                 });
    712                 domEvent.detail = event;
    713                 es5.defineProperty(domEvent, "promise", {value: event.promise});
    714                 es5.defineProperty(domEvent, "reason", {value: event.reason});
    715                 return dispatch(legacyHandlers[name], domEvent);
    716             };
    717         } else {
    718             var event = document.createEvent("CustomEvent");
    719             event.initCustomEvent("testingtheevent", false, true, {});
    720             util.global.dispatchEvent(event);
    721             return function(name, event) {
    722                 name = name.toLowerCase();
    723                 var domEvent = document.createEvent("CustomEvent");
    724                 domEvent.initCustomEvent(name, false, true,
    725                     event);
    726                 return dispatch(legacyHandlers[name], domEvent);
    727             };
    728         }
    729     } catch (e) {}
    730     return function() {
    731         return false;
    732     };
    733 })();
    734 
    735 var fireGlobalEvent = (function() {
    736     if (util.isNode) {
    737         return function() {
    738             return process.emit.apply(process, arguments);
    739         };
    740     } else {
    741         if (!util.global) {
    742             return function() {
    743                 return false;
    744             };
    745         }
    746         return function(name) {
    747             var methodName = "on" + name.toLowerCase();
    748             var method = util.global[methodName];
    749             if (!method) return false;
    750             method.apply(util.global, [].slice.call(arguments, 1));
    751             return true;
    752         };
    753     }
    754 })();
    755 
    756 function generatePromiseLifecycleEventObject(name, promise) {
    757     return {promise: promise};
    758 }
    759 
    760 var eventToObjectGenerator = {
    761     promiseCreated: generatePromiseLifecycleEventObject,
    762     promiseFulfilled: generatePromiseLifecycleEventObject,
    763     promiseRejected: generatePromiseLifecycleEventObject,
    764     promiseResolved: generatePromiseLifecycleEventObject,
    765     promiseCancelled: generatePromiseLifecycleEventObject,
    766     promiseChained: function(name, promise, child) {
    767         return {promise: promise, child: child};
    768     },
    769     warning: function(name, warning) {
    770         return {warning: warning};
    771     },
    772     unhandledRejection: function (name, reason, promise) {
    773         return {reason: reason, promise: promise};
    774     },
    775     rejectionHandled: generatePromiseLifecycleEventObject
    776 };
    777 
    778 var activeFireEvent = function (name) {
    779     var globalEventFired = false;
    780     try {
    781         globalEventFired = fireGlobalEvent.apply(null, arguments);
    782     } catch (e) {
    783         async.throwLater(e);
    784         globalEventFired = true;
    785     }
    786 
    787     var domEventFired = false;
    788     try {
    789         domEventFired = fireDomEvent(name,
    790                     eventToObjectGenerator[name].apply(null, arguments));
    791     } catch (e) {
    792         async.throwLater(e);
    793         domEventFired = true;
    794     }
    795 
    796     return domEventFired || globalEventFired;
    797 };
    798 
    799 Promise.config = function(opts) {
    800     opts = Object(opts);
    801     if ("longStackTraces" in opts) {
    802         if (opts.longStackTraces) {
    803             Promise.longStackTraces();
    804         } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
    805             disableLongStackTraces();
    806         }
    807     }
    808     if ("warnings" in opts) {
    809         var warningsOption = opts.warnings;
    810         config.warnings = !!warningsOption;
    811         wForgottenReturn = config.warnings;
    812 
    813         if (util.isObject(warningsOption)) {
    814             if ("wForgottenReturn" in warningsOption) {
    815                 wForgottenReturn = !!warningsOption.wForgottenReturn;
    816             }
    817         }
    818     }
    819     if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
    820         if (async.haveItemsQueued()) {
    821             throw new Error(
    822                 "cannot enable cancellation after promises are in use");
    823         }
    824         Promise.prototype._clearCancellationData =
    825             cancellationClearCancellationData;
    826         Promise.prototype._propagateFrom = cancellationPropagateFrom;
    827         Promise.prototype._onCancel = cancellationOnCancel;
    828         Promise.prototype._setOnCancel = cancellationSetOnCancel;
    829         Promise.prototype._attachCancellationCallback =
    830             cancellationAttachCancellationCallback;
    831         Promise.prototype._execute = cancellationExecute;
    832         propagateFromFunction = cancellationPropagateFrom;
    833         config.cancellation = true;
    834     }
    835     if ("monitoring" in opts) {
    836         if (opts.monitoring && !config.monitoring) {
    837             config.monitoring = true;
    838             Promise.prototype._fireEvent = activeFireEvent;
    839         } else if (!opts.monitoring && config.monitoring) {
    840             config.monitoring = false;
    841             Promise.prototype._fireEvent = defaultFireEvent;
    842         }
    843     }
    844     if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
    845         var prev = config.asyncHooks;
    846         var cur = !!opts.asyncHooks;
    847         if (prev !== cur) {
    848             config.asyncHooks = cur;
    849             if (cur) {
    850                 enableAsyncHooks();
    851             } else {
    852                 disableAsyncHooks();
    853             }
    854         }
    855     }
    856     return Promise;
    857 };
    858 
    859 function defaultFireEvent() { return false; }
    860 
    861 Promise.prototype._fireEvent = defaultFireEvent;
    862 Promise.prototype._execute = function(executor, resolve, reject) {
    863     try {
    864         executor(resolve, reject);
    865     } catch (e) {
    866         return e;
    867     }
    868 };
    869 Promise.prototype._onCancel = function () {};
    870 Promise.prototype._setOnCancel = function (handler) { ; };
    871 Promise.prototype._attachCancellationCallback = function(onCancel) {
    872     ;
    873 };
    874 Promise.prototype._captureStackTrace = function () {};
    875 Promise.prototype._attachExtraTrace = function () {};
    876 Promise.prototype._dereferenceTrace = function () {};
    877 Promise.prototype._clearCancellationData = function() {};
    878 Promise.prototype._propagateFrom = function (parent, flags) {
    879     ;
    880     ;
    881 };
    882 
    883 function cancellationExecute(executor, resolve, reject) {
    884     var promise = this;
    885     try {
    886         executor(resolve, reject, function(onCancel) {
    887             if (typeof onCancel !== "function") {
    888                 throw new TypeError("onCancel must be a function, got: " +
    889                                     util.toString(onCancel));
    890             }
    891             promise._attachCancellationCallback(onCancel);
    892         });
    893     } catch (e) {
    894         return e;
    895     }
    896 }
    897 
    898 function cancellationAttachCancellationCallback(onCancel) {
    899     if (!this._isCancellable()) return this;
    900 
    901     var previousOnCancel = this._onCancel();
    902     if (previousOnCancel !== undefined) {
    903         if (util.isArray(previousOnCancel)) {
    904             previousOnCancel.push(onCancel);
    905         } else {
    906             this._setOnCancel([previousOnCancel, onCancel]);
    907         }
    908     } else {
    909         this._setOnCancel(onCancel);
    910     }
    911 }
    912 
    913 function cancellationOnCancel() {
    914     return this._onCancelField;
    915 }
    916 
    917 function cancellationSetOnCancel(onCancel) {
    918     this._onCancelField = onCancel;
    919 }
    920 
    921 function cancellationClearCancellationData() {
    922     this._cancellationParent = undefined;
    923     this._onCancelField = undefined;
    924 }
    925 
    926 function cancellationPropagateFrom(parent, flags) {
    927     if ((flags & 1) !== 0) {
    928         this._cancellationParent = parent;
    929         var branchesRemainingToCancel = parent._branchesRemainingToCancel;
    930         if (branchesRemainingToCancel === undefined) {
    931             branchesRemainingToCancel = 0;
    932         }
    933         parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
    934     }
    935     if ((flags & 2) !== 0 && parent._isBound()) {
    936         this._setBoundTo(parent._boundTo);
    937     }
    938 }
    939 
    940 function bindingPropagateFrom(parent, flags) {
    941     if ((flags & 2) !== 0 && parent._isBound()) {
    942         this._setBoundTo(parent._boundTo);
    943     }
    944 }
    945 var propagateFromFunction = bindingPropagateFrom;
    946 
    947 function boundValueFunction() {
    948     var ret = this._boundTo;
    949     if (ret !== undefined) {
    950         if (ret instanceof Promise) {
    951             if (ret.isFulfilled()) {
    952                 return ret.value();
    953             } else {
    954                 return undefined;
    955             }
    956         }
    957     }
    958     return ret;
    959 }
    960 
    961 function longStackTracesCaptureStackTrace() {
    962     this._trace = new CapturedTrace(this._peekContext());
    963 }
    964 
    965 function longStackTracesAttachExtraTrace(error, ignoreSelf) {
    966     if (canAttachTrace(error)) {
    967         var trace = this._trace;
    968         if (trace !== undefined) {
    969             if (ignoreSelf) trace = trace._parent;
    970         }
    971         if (trace !== undefined) {
    972             trace.attachExtraTrace(error);
    973         } else if (!error.__stackCleaned__) {
    974             var parsed = parseStackAndMessage(error);
    975             util.notEnumerableProp(error, "stack",
    976                 parsed.message + "\n" + parsed.stack.join("\n"));
    977             util.notEnumerableProp(error, "__stackCleaned__", true);
    978         }
    979     }
    980 }
    981 
    982 function longStackTracesDereferenceTrace() {
    983     this._trace = undefined;
    984 }
    985 
    986 function checkForgottenReturns(returnValue, promiseCreated, name, promise,
    987                                parent) {
    988     if (returnValue === undefined && promiseCreated !== null &&
    989         wForgottenReturn) {
    990         if (parent !== undefined && parent._returnedNonUndefined()) return;
    991         if ((promise._bitField & 65535) === 0) return;
    992 
    993         if (name) name = name + " ";
    994         var handlerLine = "";
    995         var creatorLine = "";
    996         if (promiseCreated._trace) {
    997             var traceLines = promiseCreated._trace.stack.split("\n");
    998             var stack = cleanStack(traceLines);
    999             for (var i = stack.length - 1; i >= 0; --i) {
   1000                 var line = stack[i];
   1001                 if (!nodeFramePattern.test(line)) {
   1002                     var lineMatches = line.match(parseLinePattern);
   1003                     if (lineMatches) {
   1004                         handlerLine  = "at " + lineMatches[1] +
   1005                             ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
   1006                     }
   1007                     break;
   1008                 }
   1009             }
   1010 
   1011             if (stack.length > 0) {
   1012                 var firstUserLine = stack[0];
   1013                 for (var i = 0; i < traceLines.length; ++i) {
   1014 
   1015                     if (traceLines[i] === firstUserLine) {
   1016                         if (i > 0) {
   1017                             creatorLine = "\n" + traceLines[i - 1];
   1018                         }
   1019                         break;
   1020                     }
   1021                 }
   1022 
   1023             }
   1024         }
   1025         var msg = "a promise was created in a " + name +
   1026             "handler " + handlerLine + "but was not returned from it, " +
   1027             "see http://goo.gl/rRqMUw" +
   1028             creatorLine;
   1029         promise._warn(msg, true, promiseCreated);
   1030     }
   1031 }
   1032 
   1033 function deprecated(name, replacement) {
   1034     var message = name +
   1035         " is deprecated and will be removed in a future version.";
   1036     if (replacement) message += " Use " + replacement + " instead.";
   1037     return warn(message);
   1038 }
   1039 
   1040 function warn(message, shouldUseOwnTrace, promise) {
   1041     if (!config.warnings) return;
   1042     var warning = new Warning(message);
   1043     var ctx;
   1044     if (shouldUseOwnTrace) {
   1045         promise._attachExtraTrace(warning);
   1046     } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
   1047         ctx.attachExtraTrace(warning);
   1048     } else {
   1049         var parsed = parseStackAndMessage(warning);
   1050         warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
   1051     }
   1052 
   1053     if (!activeFireEvent("warning", warning)) {
   1054         formatAndLogError(warning, "", true);
   1055     }
   1056 }
   1057 
   1058 function reconstructStack(message, stacks) {
   1059     for (var i = 0; i < stacks.length - 1; ++i) {
   1060         stacks[i].push("From previous event:");
   1061         stacks[i] = stacks[i].join("\n");
   1062     }
   1063     if (i < stacks.length) {
   1064         stacks[i] = stacks[i].join("\n");
   1065     }
   1066     return message + "\n" + stacks.join("\n");
   1067 }
   1068 
   1069 function removeDuplicateOrEmptyJumps(stacks) {
   1070     for (var i = 0; i < stacks.length; ++i) {
   1071         if (stacks[i].length === 0 ||
   1072             ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
   1073             stacks.splice(i, 1);
   1074             i--;
   1075         }
   1076     }
   1077 }
   1078 
   1079 function removeCommonRoots(stacks) {
   1080     var current = stacks[0];
   1081     for (var i = 1; i < stacks.length; ++i) {
   1082         var prev = stacks[i];
   1083         var currentLastIndex = current.length - 1;
   1084         var currentLastLine = current[currentLastIndex];
   1085         var commonRootMeetPoint = -1;
   1086 
   1087         for (var j = prev.length - 1; j >= 0; --j) {
   1088             if (prev[j] === currentLastLine) {
   1089                 commonRootMeetPoint = j;
   1090                 break;
   1091             }
   1092         }
   1093 
   1094         for (var j = commonRootMeetPoint; j >= 0; --j) {
   1095             var line = prev[j];
   1096             if (current[currentLastIndex] === line) {
   1097                 current.pop();
   1098                 currentLastIndex--;
   1099             } else {
   1100                 break;
   1101             }
   1102         }
   1103         current = prev;
   1104     }
   1105 }
   1106 
   1107 function cleanStack(stack) {
   1108     var ret = [];
   1109     for (var i = 0; i < stack.length; ++i) {
   1110         var line = stack[i];
   1111         var isTraceLine = "    (No stack trace)" === line ||
   1112             stackFramePattern.test(line);
   1113         var isInternalFrame = isTraceLine && shouldIgnore(line);
   1114         if (isTraceLine && !isInternalFrame) {
   1115             if (indentStackFrames && line.charAt(0) !== " ") {
   1116                 line = "    " + line;
   1117             }
   1118             ret.push(line);
   1119         }
   1120     }
   1121     return ret;
   1122 }
   1123 
   1124 function stackFramesAsArray(error) {
   1125     var stack = error.stack.replace(/\s+$/g, "").split("\n");
   1126     for (var i = 0; i < stack.length; ++i) {
   1127         var line = stack[i];
   1128         if ("    (No stack trace)" === line || stackFramePattern.test(line)) {
   1129             break;
   1130         }
   1131     }
   1132     if (i > 0 && error.name != "SyntaxError") {
   1133         stack = stack.slice(i);
   1134     }
   1135     return stack;
   1136 }
   1137 
   1138 function parseStackAndMessage(error) {
   1139     var stack = error.stack;
   1140     var message = error.toString();
   1141     stack = typeof stack === "string" && stack.length > 0
   1142                 ? stackFramesAsArray(error) : ["    (No stack trace)"];
   1143     return {
   1144         message: message,
   1145         stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
   1146     };
   1147 }
   1148 
   1149 function formatAndLogError(error, title, isSoft) {
   1150     if (typeof console !== "undefined") {
   1151         var message;
   1152         if (util.isObject(error)) {
   1153             var stack = error.stack;
   1154             message = title + formatStack(stack, error);
   1155         } else {
   1156             message = title + String(error);
   1157         }
   1158         if (typeof printWarning === "function") {
   1159             printWarning(message, isSoft);
   1160         } else if (typeof console.log === "function" ||
   1161             typeof console.log === "object") {
   1162             console.log(message);
   1163         }
   1164     }
   1165 }
   1166 
   1167 function fireRejectionEvent(name, localHandler, reason, promise) {
   1168     var localEventFired = false;
   1169     try {
   1170         if (typeof localHandler === "function") {
   1171             localEventFired = true;
   1172             if (name === "rejectionHandled") {
   1173                 localHandler(promise);
   1174             } else {
   1175                 localHandler(reason, promise);
   1176             }
   1177         }
   1178     } catch (e) {
   1179         async.throwLater(e);
   1180     }
   1181 
   1182     if (name === "unhandledRejection") {
   1183         if (!activeFireEvent(name, reason, promise) && !localEventFired) {
   1184             formatAndLogError(reason, "Unhandled rejection ");
   1185         }
   1186     } else {
   1187         activeFireEvent(name, promise);
   1188     }
   1189 }
   1190 
   1191 function formatNonError(obj) {
   1192     var str;
   1193     if (typeof obj === "function") {
   1194         str = "[function " +
   1195             (obj.name || "anonymous") +
   1196             "]";
   1197     } else {
   1198         str = obj && typeof obj.toString === "function"
   1199             ? obj.toString() : util.toString(obj);
   1200         var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
   1201         if (ruselessToString.test(str)) {
   1202             try {
   1203                 var newStr = JSON.stringify(obj);
   1204                 str = newStr;
   1205             }
   1206             catch(e) {
   1207 
   1208             }
   1209         }
   1210         if (str.length === 0) {
   1211             str = "(empty array)";
   1212         }
   1213     }
   1214     return ("(<" + snip(str) + ">, no stack trace)");
   1215 }
   1216 
   1217 function snip(str) {
   1218     var maxChars = 41;
   1219     if (str.length < maxChars) {
   1220         return str;
   1221     }
   1222     return str.substr(0, maxChars - 3) + "...";
   1223 }
   1224 
   1225 function longStackTracesIsSupported() {
   1226     return typeof captureStackTrace === "function";
   1227 }
   1228 
   1229 var shouldIgnore = function() { return false; };
   1230 var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
   1231 function parseLineInfo(line) {
   1232     var matches = line.match(parseLineInfoRegex);
   1233     if (matches) {
   1234         return {
   1235             fileName: matches[1],
   1236             line: parseInt(matches[2], 10)
   1237         };
   1238     }
   1239 }
   1240 
   1241 function setBounds(firstLineError, lastLineError) {
   1242     if (!longStackTracesIsSupported()) return;
   1243     var firstStackLines = (firstLineError.stack || "").split("\n");
   1244     var lastStackLines = (lastLineError.stack || "").split("\n");
   1245     var firstIndex = -1;
   1246     var lastIndex = -1;
   1247     var firstFileName;
   1248     var lastFileName;
   1249     for (var i = 0; i < firstStackLines.length; ++i) {
   1250         var result = parseLineInfo(firstStackLines[i]);
   1251         if (result) {
   1252             firstFileName = result.fileName;
   1253             firstIndex = result.line;
   1254             break;
   1255         }
   1256     }
   1257     for (var i = 0; i < lastStackLines.length; ++i) {
   1258         var result = parseLineInfo(lastStackLines[i]);
   1259         if (result) {
   1260             lastFileName = result.fileName;
   1261             lastIndex = result.line;
   1262             break;
   1263         }
   1264     }
   1265     if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
   1266         firstFileName !== lastFileName || firstIndex >= lastIndex) {
   1267         return;
   1268     }
   1269 
   1270     shouldIgnore = function(line) {
   1271         if (bluebirdFramePattern.test(line)) return true;
   1272         var info = parseLineInfo(line);
   1273         if (info) {
   1274             if (info.fileName === firstFileName &&
   1275                 (firstIndex <= info.line && info.line <= lastIndex)) {
   1276                 return true;
   1277             }
   1278         }
   1279         return false;
   1280     };
   1281 }
   1282 
   1283 function CapturedTrace(parent) {
   1284     this._parent = parent;
   1285     this._promisesCreated = 0;
   1286     var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
   1287     captureStackTrace(this, CapturedTrace);
   1288     if (length > 32) this.uncycle();
   1289 }
   1290 util.inherits(CapturedTrace, Error);
   1291 Context.CapturedTrace = CapturedTrace;
   1292 
   1293 CapturedTrace.prototype.uncycle = function() {
   1294     var length = this._length;
   1295     if (length < 2) return;
   1296     var nodes = [];
   1297     var stackToIndex = {};
   1298 
   1299     for (var i = 0, node = this; node !== undefined; ++i) {
   1300         nodes.push(node);
   1301         node = node._parent;
   1302     }
   1303     length = this._length = i;
   1304     for (var i = length - 1; i >= 0; --i) {
   1305         var stack = nodes[i].stack;
   1306         if (stackToIndex[stack] === undefined) {
   1307             stackToIndex[stack] = i;
   1308         }
   1309     }
   1310     for (var i = 0; i < length; ++i) {
   1311         var currentStack = nodes[i].stack;
   1312         var index = stackToIndex[currentStack];
   1313         if (index !== undefined && index !== i) {
   1314             if (index > 0) {
   1315                 nodes[index - 1]._parent = undefined;
   1316                 nodes[index - 1]._length = 1;
   1317             }
   1318             nodes[i]._parent = undefined;
   1319             nodes[i]._length = 1;
   1320             var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
   1321 
   1322             if (index < length - 1) {
   1323                 cycleEdgeNode._parent = nodes[index + 1];
   1324                 cycleEdgeNode._parent.uncycle();
   1325                 cycleEdgeNode._length =
   1326                     cycleEdgeNode._parent._length + 1;
   1327             } else {
   1328                 cycleEdgeNode._parent = undefined;
   1329                 cycleEdgeNode._length = 1;
   1330             }
   1331             var currentChildLength = cycleEdgeNode._length + 1;
   1332             for (var j = i - 2; j >= 0; --j) {
   1333                 nodes[j]._length = currentChildLength;
   1334                 currentChildLength++;
   1335             }
   1336             return;
   1337         }
   1338     }
   1339 };
   1340 
   1341 CapturedTrace.prototype.attachExtraTrace = function(error) {
   1342     if (error.__stackCleaned__) return;
   1343     this.uncycle();
   1344     var parsed = parseStackAndMessage(error);
   1345     var message = parsed.message;
   1346     var stacks = [parsed.stack];
   1347 
   1348     var trace = this;
   1349     while (trace !== undefined) {
   1350         stacks.push(cleanStack(trace.stack.split("\n")));
   1351         trace = trace._parent;
   1352     }
   1353     removeCommonRoots(stacks);
   1354     removeDuplicateOrEmptyJumps(stacks);
   1355     util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
   1356     util.notEnumerableProp(error, "__stackCleaned__", true);
   1357 };
   1358 
   1359 var captureStackTrace = (function stackDetection() {
   1360     var v8stackFramePattern = /^\s*at\s*/;
   1361     var v8stackFormatter = function(stack, error) {
   1362         if (typeof stack === "string") return stack;
   1363 
   1364         if (error.name !== undefined &&
   1365             error.message !== undefined) {
   1366             return error.toString();
   1367         }
   1368         return formatNonError(error);
   1369     };
   1370 
   1371     if (typeof Error.stackTraceLimit === "number" &&
   1372         typeof Error.captureStackTrace === "function") {
   1373         Error.stackTraceLimit += 6;
   1374         stackFramePattern = v8stackFramePattern;
   1375         formatStack = v8stackFormatter;
   1376         var captureStackTrace = Error.captureStackTrace;
   1377 
   1378         shouldIgnore = function(line) {
   1379             return bluebirdFramePattern.test(line);
   1380         };
   1381         return function(receiver, ignoreUntil) {
   1382             Error.stackTraceLimit += 6;
   1383             captureStackTrace(receiver, ignoreUntil);
   1384             Error.stackTraceLimit -= 6;
   1385         };
   1386     }
   1387     var err = new Error();
   1388 
   1389     if (typeof err.stack === "string" &&
   1390         err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
   1391         stackFramePattern = /@/;
   1392         formatStack = v8stackFormatter;
   1393         indentStackFrames = true;
   1394         return function captureStackTrace(o) {
   1395             o.stack = new Error().stack;
   1396         };
   1397     }
   1398 
   1399     var hasStackAfterThrow;
   1400     try { throw new Error(); }
   1401     catch(e) {
   1402         hasStackAfterThrow = ("stack" in e);
   1403     }
   1404     if (!("stack" in err) && hasStackAfterThrow &&
   1405         typeof Error.stackTraceLimit === "number") {
   1406         stackFramePattern = v8stackFramePattern;
   1407         formatStack = v8stackFormatter;
   1408         return function captureStackTrace(o) {
   1409             Error.stackTraceLimit += 6;
   1410             try { throw new Error(); }
   1411             catch(e) { o.stack = e.stack; }
   1412             Error.stackTraceLimit -= 6;
   1413         };
   1414     }
   1415 
   1416     formatStack = function(stack, error) {
   1417         if (typeof stack === "string") return stack;
   1418 
   1419         if ((typeof error === "object" ||
   1420             typeof error === "function") &&
   1421             error.name !== undefined &&
   1422             error.message !== undefined) {
   1423             return error.toString();
   1424         }
   1425         return formatNonError(error);
   1426     };
   1427 
   1428     return null;
   1429 
   1430 })([]);
   1431 
   1432 if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
   1433     printWarning = function (message) {
   1434         console.warn(message);
   1435     };
   1436     if (util.isNode && process.stderr.isTTY) {
   1437         printWarning = function(message, isSoft) {
   1438             var color = isSoft ? "\u001b[33m" : "\u001b[31m";
   1439             console.warn(color + message + "\u001b[0m\n");
   1440         };
   1441     } else if (!util.isNode && typeof (new Error().stack) === "string") {
   1442         printWarning = function(message, isSoft) {
   1443             console.warn("%c" + message,
   1444                         isSoft ? "color: darkorange" : "color: red");
   1445         };
   1446     }
   1447 }
   1448 
   1449 var config = {
   1450     warnings: warnings,
   1451     longStackTraces: false,
   1452     cancellation: false,
   1453     monitoring: false,
   1454     asyncHooks: false
   1455 };
   1456 
   1457 if (longStackTraces) Promise.longStackTraces();
   1458 
   1459 return {
   1460     asyncHooks: function() {
   1461         return config.asyncHooks;
   1462     },
   1463     longStackTraces: function() {
   1464         return config.longStackTraces;
   1465     },
   1466     warnings: function() {
   1467         return config.warnings;
   1468     },
   1469     cancellation: function() {
   1470         return config.cancellation;
   1471     },
   1472     monitoring: function() {
   1473         return config.monitoring;
   1474     },
   1475     propagateFromFunction: function() {
   1476         return propagateFromFunction;
   1477     },
   1478     boundValueFunction: function() {
   1479         return boundValueFunction;
   1480     },
   1481     checkForgottenReturns: checkForgottenReturns,
   1482     setBounds: setBounds,
   1483     warn: warn,
   1484     deprecated: deprecated,
   1485     CapturedTrace: CapturedTrace,
   1486     fireDomEvent: fireDomEvent,
   1487     fireGlobalEvent: fireGlobalEvent
   1488 };
   1489 };
   1490 
   1491 },{"./errors":9,"./es5":10,"./util":21}],8:[function(_dereq_,module,exports){
   1492 "use strict";
   1493 module.exports = function(Promise) {
   1494 function returner() {
   1495     return this.value;
   1496 }
   1497 function thrower() {
   1498     throw this.reason;
   1499 }
   1500 
   1501 Promise.prototype["return"] =
   1502 Promise.prototype.thenReturn = function (value) {
   1503     if (value instanceof Promise) value.suppressUnhandledRejections();
   1504     return this._then(
   1505         returner, undefined, undefined, {value: value}, undefined);
   1506 };
   1507 
   1508 Promise.prototype["throw"] =
   1509 Promise.prototype.thenThrow = function (reason) {
   1510     return this._then(
   1511         thrower, undefined, undefined, {reason: reason}, undefined);
   1512 };
   1513 
   1514 Promise.prototype.catchThrow = function (reason) {
   1515     if (arguments.length <= 1) {
   1516         return this._then(
   1517             undefined, thrower, undefined, {reason: reason}, undefined);
   1518     } else {
   1519         var _reason = arguments[1];
   1520         var handler = function() {throw _reason;};
   1521         return this.caught(reason, handler);
   1522     }
   1523 };
   1524 
   1525 Promise.prototype.catchReturn = function (value) {
   1526     if (arguments.length <= 1) {
   1527         if (value instanceof Promise) value.suppressUnhandledRejections();
   1528         return this._then(
   1529             undefined, returner, undefined, {value: value}, undefined);
   1530     } else {
   1531         var _value = arguments[1];
   1532         if (_value instanceof Promise) _value.suppressUnhandledRejections();
   1533         var handler = function() {return _value;};
   1534         return this.caught(value, handler);
   1535     }
   1536 };
   1537 };
   1538 
   1539 },{}],9:[function(_dereq_,module,exports){
   1540 "use strict";
   1541 var es5 = _dereq_("./es5");
   1542 var Objectfreeze = es5.freeze;
   1543 var util = _dereq_("./util");
   1544 var inherits = util.inherits;
   1545 var notEnumerableProp = util.notEnumerableProp;
   1546 
   1547 function subError(nameProperty, defaultMessage) {
   1548     function SubError(message) {
   1549         if (!(this instanceof SubError)) return new SubError(message);
   1550         notEnumerableProp(this, "message",
   1551             typeof message === "string" ? message : defaultMessage);
   1552         notEnumerableProp(this, "name", nameProperty);
   1553         if (Error.captureStackTrace) {
   1554             Error.captureStackTrace(this, this.constructor);
   1555         } else {
   1556             Error.call(this);
   1557         }
   1558     }
   1559     inherits(SubError, Error);
   1560     return SubError;
   1561 }
   1562 
   1563 var _TypeError, _RangeError;
   1564 var Warning = subError("Warning", "warning");
   1565 var CancellationError = subError("CancellationError", "cancellation error");
   1566 var TimeoutError = subError("TimeoutError", "timeout error");
   1567 var AggregateError = subError("AggregateError", "aggregate error");
   1568 try {
   1569     _TypeError = TypeError;
   1570     _RangeError = RangeError;
   1571 } catch(e) {
   1572     _TypeError = subError("TypeError", "type error");
   1573     _RangeError = subError("RangeError", "range error");
   1574 }
   1575 
   1576 var methods = ("join pop push shift unshift slice filter forEach some " +
   1577     "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
   1578 
   1579 for (var i = 0; i < methods.length; ++i) {
   1580     if (typeof Array.prototype[methods[i]] === "function") {
   1581         AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
   1582     }
   1583 }
   1584 
   1585 es5.defineProperty(AggregateError.prototype, "length", {
   1586     value: 0,
   1587     configurable: false,
   1588     writable: true,
   1589     enumerable: true
   1590 });
   1591 AggregateError.prototype["isOperational"] = true;
   1592 var level = 0;
   1593 AggregateError.prototype.toString = function() {
   1594     var indent = Array(level * 4 + 1).join(" ");
   1595     var ret = "\n" + indent + "AggregateError of:" + "\n";
   1596     level++;
   1597     indent = Array(level * 4 + 1).join(" ");
   1598     for (var i = 0; i < this.length; ++i) {
   1599         var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
   1600         var lines = str.split("\n");
   1601         for (var j = 0; j < lines.length; ++j) {
   1602             lines[j] = indent + lines[j];
   1603         }
   1604         str = lines.join("\n");
   1605         ret += str + "\n";
   1606     }
   1607     level--;
   1608     return ret;
   1609 };
   1610 
   1611 function OperationalError(message) {
   1612     if (!(this instanceof OperationalError))
   1613         return new OperationalError(message);
   1614     notEnumerableProp(this, "name", "OperationalError");
   1615     notEnumerableProp(this, "message", message);
   1616     this.cause = message;
   1617     this["isOperational"] = true;
   1618 
   1619     if (message instanceof Error) {
   1620         notEnumerableProp(this, "message", message.message);
   1621         notEnumerableProp(this, "stack", message.stack);
   1622     } else if (Error.captureStackTrace) {
   1623         Error.captureStackTrace(this, this.constructor);
   1624     }
   1625 
   1626 }
   1627 inherits(OperationalError, Error);
   1628 
   1629 var errorTypes = Error["__BluebirdErrorTypes__"];
   1630 if (!errorTypes) {
   1631     errorTypes = Objectfreeze({
   1632         CancellationError: CancellationError,
   1633         TimeoutError: TimeoutError,
   1634         OperationalError: OperationalError,
   1635         RejectionError: OperationalError,
   1636         AggregateError: AggregateError
   1637     });
   1638     es5.defineProperty(Error, "__BluebirdErrorTypes__", {
   1639         value: errorTypes,
   1640         writable: false,
   1641         enumerable: false,
   1642         configurable: false
   1643     });
   1644 }
   1645 
   1646 module.exports = {
   1647     Error: Error,
   1648     TypeError: _TypeError,
   1649     RangeError: _RangeError,
   1650     CancellationError: errorTypes.CancellationError,
   1651     OperationalError: errorTypes.OperationalError,
   1652     TimeoutError: errorTypes.TimeoutError,
   1653     AggregateError: errorTypes.AggregateError,
   1654     Warning: Warning
   1655 };
   1656 
   1657 },{"./es5":10,"./util":21}],10:[function(_dereq_,module,exports){
   1658 var isES5 = (function(){
   1659     "use strict";
   1660     return this === undefined;
   1661 })();
   1662 
   1663 if (isES5) {
   1664     module.exports = {
   1665         freeze: Object.freeze,
   1666         defineProperty: Object.defineProperty,
   1667         getDescriptor: Object.getOwnPropertyDescriptor,
   1668         keys: Object.keys,
   1669         names: Object.getOwnPropertyNames,
   1670         getPrototypeOf: Object.getPrototypeOf,
   1671         isArray: Array.isArray,
   1672         isES5: isES5,
   1673         propertyIsWritable: function(obj, prop) {
   1674             var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
   1675             return !!(!descriptor || descriptor.writable || descriptor.set);
   1676         }
   1677     };
   1678 } else {
   1679     var has = {}.hasOwnProperty;
   1680     var str = {}.toString;
   1681     var proto = {}.constructor.prototype;
   1682 
   1683     var ObjectKeys = function (o) {
   1684         var ret = [];
   1685         for (var key in o) {
   1686             if (has.call(o, key)) {
   1687                 ret.push(key);
   1688             }
   1689         }
   1690         return ret;
   1691     };
   1692 
   1693     var ObjectGetDescriptor = function(o, key) {
   1694         return {value: o[key]};
   1695     };
   1696 
   1697     var ObjectDefineProperty = function (o, key, desc) {
   1698         o[key] = desc.value;
   1699         return o;
   1700     };
   1701 
   1702     var ObjectFreeze = function (obj) {
   1703         return obj;
   1704     };
   1705 
   1706     var ObjectGetPrototypeOf = function (obj) {
   1707         try {
   1708             return Object(obj).constructor.prototype;
   1709         }
   1710         catch (e) {
   1711             return proto;
   1712         }
   1713     };
   1714 
   1715     var ArrayIsArray = function (obj) {
   1716         try {
   1717             return str.call(obj) === "[object Array]";
   1718         }
   1719         catch(e) {
   1720             return false;
   1721         }
   1722     };
   1723 
   1724     module.exports = {
   1725         isArray: ArrayIsArray,
   1726         keys: ObjectKeys,
   1727         names: ObjectKeys,
   1728         defineProperty: ObjectDefineProperty,
   1729         getDescriptor: ObjectGetDescriptor,
   1730         freeze: ObjectFreeze,
   1731         getPrototypeOf: ObjectGetPrototypeOf,
   1732         isES5: isES5,
   1733         propertyIsWritable: function() {
   1734             return true;
   1735         }
   1736     };
   1737 }
   1738 
   1739 },{}],11:[function(_dereq_,module,exports){
   1740 "use strict";
   1741 module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
   1742 var util = _dereq_("./util");
   1743 var CancellationError = Promise.CancellationError;
   1744 var errorObj = util.errorObj;
   1745 var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
   1746 
   1747 function PassThroughHandlerContext(promise, type, handler) {
   1748     this.promise = promise;
   1749     this.type = type;
   1750     this.handler = handler;
   1751     this.called = false;
   1752     this.cancelPromise = null;
   1753 }
   1754 
   1755 PassThroughHandlerContext.prototype.isFinallyHandler = function() {
   1756     return this.type === 0;
   1757 };
   1758 
   1759 function FinallyHandlerCancelReaction(finallyHandler) {
   1760     this.finallyHandler = finallyHandler;
   1761 }
   1762 
   1763 FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
   1764     checkCancel(this.finallyHandler);
   1765 };
   1766 
   1767 function checkCancel(ctx, reason) {
   1768     if (ctx.cancelPromise != null) {
   1769         if (arguments.length > 1) {
   1770             ctx.cancelPromise._reject(reason);
   1771         } else {
   1772             ctx.cancelPromise._cancel();
   1773         }
   1774         ctx.cancelPromise = null;
   1775         return true;
   1776     }
   1777     return false;
   1778 }
   1779 
   1780 function succeed() {
   1781     return finallyHandler.call(this, this.promise._target()._settledValue());
   1782 }
   1783 function fail(reason) {
   1784     if (checkCancel(this, reason)) return;
   1785     errorObj.e = reason;
   1786     return errorObj;
   1787 }
   1788 function finallyHandler(reasonOrValue) {
   1789     var promise = this.promise;
   1790     var handler = this.handler;
   1791 
   1792     if (!this.called) {
   1793         this.called = true;
   1794         var ret = this.isFinallyHandler()
   1795             ? handler.call(promise._boundValue())
   1796             : handler.call(promise._boundValue(), reasonOrValue);
   1797         if (ret === NEXT_FILTER) {
   1798             return ret;
   1799         } else if (ret !== undefined) {
   1800             promise._setReturnedNonUndefined();
   1801             var maybePromise = tryConvertToPromise(ret, promise);
   1802             if (maybePromise instanceof Promise) {
   1803                 if (this.cancelPromise != null) {
   1804                     if (maybePromise._isCancelled()) {
   1805                         var reason =
   1806                             new CancellationError("late cancellation observer");
   1807                         promise._attachExtraTrace(reason);
   1808                         errorObj.e = reason;
   1809                         return errorObj;
   1810                     } else if (maybePromise.isPending()) {
   1811                         maybePromise._attachCancellationCallback(
   1812                             new FinallyHandlerCancelReaction(this));
   1813                     }
   1814                 }
   1815                 return maybePromise._then(
   1816                     succeed, fail, undefined, this, undefined);
   1817             }
   1818         }
   1819     }
   1820 
   1821     if (promise.isRejected()) {
   1822         checkCancel(this);
   1823         errorObj.e = reasonOrValue;
   1824         return errorObj;
   1825     } else {
   1826         checkCancel(this);
   1827         return reasonOrValue;
   1828     }
   1829 }
   1830 
   1831 Promise.prototype._passThrough = function(handler, type, success, fail) {
   1832     if (typeof handler !== "function") return this.then();
   1833     return this._then(success,
   1834                       fail,
   1835                       undefined,
   1836                       new PassThroughHandlerContext(this, type, handler),
   1837                       undefined);
   1838 };
   1839 
   1840 Promise.prototype.lastly =
   1841 Promise.prototype["finally"] = function (handler) {
   1842     return this._passThrough(handler,
   1843                              0,
   1844                              finallyHandler,
   1845                              finallyHandler);
   1846 };
   1847 
   1848 
   1849 Promise.prototype.tap = function (handler) {
   1850     return this._passThrough(handler, 1, finallyHandler);
   1851 };
   1852 
   1853 Promise.prototype.tapCatch = function (handlerOrPredicate) {
   1854     var len = arguments.length;
   1855     if(len === 1) {
   1856         return this._passThrough(handlerOrPredicate,
   1857                                  1,
   1858                                  undefined,
   1859                                  finallyHandler);
   1860     } else {
   1861          var catchInstances = new Array(len - 1),
   1862             j = 0, i;
   1863         for (i = 0; i < len - 1; ++i) {
   1864             var item = arguments[i];
   1865             if (util.isObject(item)) {
   1866                 catchInstances[j++] = item;
   1867             } else {
   1868                 return Promise.reject(new TypeError(
   1869                     "tapCatch statement predicate: "
   1870                     + "expecting an object but got " + util.classString(item)
   1871                 ));
   1872             }
   1873         }
   1874         catchInstances.length = j;
   1875         var handler = arguments[i];
   1876         return this._passThrough(catchFilter(catchInstances, handler, this),
   1877                                  1,
   1878                                  undefined,
   1879                                  finallyHandler);
   1880     }
   1881 
   1882 };
   1883 
   1884 return PassThroughHandlerContext;
   1885 };
   1886 
   1887 },{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){
   1888 "use strict";
   1889 module.exports =
   1890 function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) {
   1891 var util = _dereq_("./util");
   1892 var canEvaluate = util.canEvaluate;
   1893 var tryCatch = util.tryCatch;
   1894 var errorObj = util.errorObj;
   1895 var reject;
   1896 
   1897 if (!true) {
   1898 if (canEvaluate) {
   1899     var thenCallback = function(i) {
   1900         return new Function("value", "holder", "                             \n\
   1901             'use strict';                                                    \n\
   1902             holder.pIndex = value;                                           \n\
   1903             holder.checkFulfillment(this);                                   \n\
   1904             ".replace(/Index/g, i));
   1905     };
   1906 
   1907     var promiseSetter = function(i) {
   1908         return new Function("promise", "holder", "                           \n\
   1909             'use strict';                                                    \n\
   1910             holder.pIndex = promise;                                         \n\
   1911             ".replace(/Index/g, i));
   1912     };
   1913 
   1914     var generateHolderClass = function(total) {
   1915         var props = new Array(total);
   1916         for (var i = 0; i < props.length; ++i) {
   1917             props[i] = "this.p" + (i+1);
   1918         }
   1919         var assignment = props.join(" = ") + " = null;";
   1920         var cancellationCode= "var promise;\n" + props.map(function(prop) {
   1921             return "                                                         \n\
   1922                 promise = " + prop + ";                                      \n\
   1923                 if (promise instanceof Promise) {                            \n\
   1924                     promise.cancel();                                        \n\
   1925                 }                                                            \n\
   1926             ";
   1927         }).join("\n");
   1928         var passedArguments = props.join(", ");
   1929         var name = "Holder$" + total;
   1930 
   1931 
   1932         var code = "return function(tryCatch, errorObj, Promise, async) {    \n\
   1933             'use strict';                                                    \n\
   1934             function [TheName](fn) {                                         \n\
   1935                 [TheProperties]                                              \n\
   1936                 this.fn = fn;                                                \n\
   1937                 this.asyncNeeded = true;                                     \n\
   1938                 this.now = 0;                                                \n\
   1939             }                                                                \n\
   1940                                                                              \n\
   1941             [TheName].prototype._callFunction = function(promise) {          \n\
   1942                 promise._pushContext();                                      \n\
   1943                 var ret = tryCatch(this.fn)([ThePassedArguments]);           \n\
   1944                 promise._popContext();                                       \n\
   1945                 if (ret === errorObj) {                                      \n\
   1946                     promise._rejectCallback(ret.e, false);                   \n\
   1947                 } else {                                                     \n\
   1948                     promise._resolveCallback(ret);                           \n\
   1949                 }                                                            \n\
   1950             };                                                               \n\
   1951                                                                              \n\
   1952             [TheName].prototype.checkFulfillment = function(promise) {       \n\
   1953                 var now = ++this.now;                                        \n\
   1954                 if (now === [TheTotal]) {                                    \n\
   1955                     if (this.asyncNeeded) {                                  \n\
   1956                         async.invoke(this._callFunction, this, promise);     \n\
   1957                     } else {                                                 \n\
   1958                         this._callFunction(promise);                         \n\
   1959                     }                                                        \n\
   1960                                                                              \n\
   1961                 }                                                            \n\
   1962             };                                                               \n\
   1963                                                                              \n\
   1964             [TheName].prototype._resultCancelled = function() {              \n\
   1965                 [CancellationCode]                                           \n\
   1966             };                                                               \n\
   1967                                                                              \n\
   1968             return [TheName];                                                \n\
   1969         }(tryCatch, errorObj, Promise, async);                               \n\
   1970         ";
   1971 
   1972         code = code.replace(/\[TheName\]/g, name)
   1973             .replace(/\[TheTotal\]/g, total)
   1974             .replace(/\[ThePassedArguments\]/g, passedArguments)
   1975             .replace(/\[TheProperties\]/g, assignment)
   1976             .replace(/\[CancellationCode\]/g, cancellationCode);
   1977 
   1978         return new Function("tryCatch", "errorObj", "Promise", "async", code)
   1979                            (tryCatch, errorObj, Promise, async);
   1980     };
   1981 
   1982     var holderClasses = [];
   1983     var thenCallbacks = [];
   1984     var promiseSetters = [];
   1985 
   1986     for (var i = 0; i < 8; ++i) {
   1987         holderClasses.push(generateHolderClass(i + 1));
   1988         thenCallbacks.push(thenCallback(i + 1));
   1989         promiseSetters.push(promiseSetter(i + 1));
   1990     }
   1991 
   1992     reject = function (reason) {
   1993         this._reject(reason);
   1994     };
   1995 }}
   1996 
   1997 Promise.join = function () {
   1998     var last = arguments.length - 1;
   1999     var fn;
   2000     if (last > 0 && typeof arguments[last] === "function") {
   2001         fn = arguments[last];
   2002         if (!true) {
   2003             if (last <= 8 && canEvaluate) {
   2004                 var ret = new Promise(INTERNAL);
   2005                 ret._captureStackTrace();
   2006                 var HolderClass = holderClasses[last - 1];
   2007                 var holder = new HolderClass(fn);
   2008                 var callbacks = thenCallbacks;
   2009 
   2010                 for (var i = 0; i < last; ++i) {
   2011                     var maybePromise = tryConvertToPromise(arguments[i], ret);
   2012                     if (maybePromise instanceof Promise) {
   2013                         maybePromise = maybePromise._target();
   2014                         var bitField = maybePromise._bitField;
   2015                         ;
   2016                         if (((bitField & 50397184) === 0)) {
   2017                             maybePromise._then(callbacks[i], reject,
   2018                                                undefined, ret, holder);
   2019                             promiseSetters[i](maybePromise, holder);
   2020                             holder.asyncNeeded = false;
   2021                         } else if (((bitField & 33554432) !== 0)) {
   2022                             callbacks[i].call(ret,
   2023                                               maybePromise._value(), holder);
   2024                         } else if (((bitField & 16777216) !== 0)) {
   2025                             ret._reject(maybePromise._reason());
   2026                         } else {
   2027                             ret._cancel();
   2028                         }
   2029                     } else {
   2030                         callbacks[i].call(ret, maybePromise, holder);
   2031                     }
   2032                 }
   2033 
   2034                 if (!ret._isFateSealed()) {
   2035                     if (holder.asyncNeeded) {
   2036                         var context = Promise._getContext();
   2037                         holder.fn = util.contextBind(context, holder.fn);
   2038                     }
   2039                     ret._setAsyncGuaranteed();
   2040                     ret._setOnCancel(holder);
   2041                 }
   2042                 return ret;
   2043             }
   2044         }
   2045     }
   2046     var args = [].slice.call(arguments);;
   2047     if (fn) args.pop();
   2048     var ret = new PromiseArray(args).promise();
   2049     return fn !== undefined ? ret.spread(fn) : ret;
   2050 };
   2051 
   2052 };
   2053 
   2054 },{"./util":21}],13:[function(_dereq_,module,exports){
   2055 "use strict";
   2056 module.exports =
   2057 function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
   2058 var util = _dereq_("./util");
   2059 var tryCatch = util.tryCatch;
   2060 
   2061 Promise.method = function (fn) {
   2062     if (typeof fn !== "function") {
   2063         throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
   2064     }
   2065     return function () {
   2066         var ret = new Promise(INTERNAL);
   2067         ret._captureStackTrace();
   2068         ret._pushContext();
   2069         var value = tryCatch(fn).apply(this, arguments);
   2070         var promiseCreated = ret._popContext();
   2071         debug.checkForgottenReturns(
   2072             value, promiseCreated, "Promise.method", ret);
   2073         ret._resolveFromSyncValue(value);
   2074         return ret;
   2075     };
   2076 };
   2077 
   2078 Promise.attempt = Promise["try"] = function (fn) {
   2079     if (typeof fn !== "function") {
   2080         return apiRejection("expecting a function but got " + util.classString(fn));
   2081     }
   2082     var ret = new Promise(INTERNAL);
   2083     ret._captureStackTrace();
   2084     ret._pushContext();
   2085     var value;
   2086     if (arguments.length > 1) {
   2087         debug.deprecated("calling Promise.try with more than 1 argument");
   2088         var arg = arguments[1];
   2089         var ctx = arguments[2];
   2090         value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
   2091                                   : tryCatch(fn).call(ctx, arg);
   2092     } else {
   2093         value = tryCatch(fn)();
   2094     }
   2095     var promiseCreated = ret._popContext();
   2096     debug.checkForgottenReturns(
   2097         value, promiseCreated, "Promise.try", ret);
   2098     ret._resolveFromSyncValue(value);
   2099     return ret;
   2100 };
   2101 
   2102 Promise.prototype._resolveFromSyncValue = function (value) {
   2103     if (value === util.errorObj) {
   2104         this._rejectCallback(value.e, false);
   2105     } else {
   2106         this._resolveCallback(value, true);
   2107     }
   2108 };
   2109 };
   2110 
   2111 },{"./util":21}],14:[function(_dereq_,module,exports){
   2112 "use strict";
   2113 var util = _dereq_("./util");
   2114 var maybeWrapAsError = util.maybeWrapAsError;
   2115 var errors = _dereq_("./errors");
   2116 var OperationalError = errors.OperationalError;
   2117 var es5 = _dereq_("./es5");
   2118 
   2119 function isUntypedError(obj) {
   2120     return obj instanceof Error &&
   2121         es5.getPrototypeOf(obj) === Error.prototype;
   2122 }
   2123 
   2124 var rErrorKey = /^(?:name|message|stack|cause)$/;
   2125 function wrapAsOperationalError(obj) {
   2126     var ret;
   2127     if (isUntypedError(obj)) {
   2128         ret = new OperationalError(obj);
   2129         ret.name = obj.name;
   2130         ret.message = obj.message;
   2131         ret.stack = obj.stack;
   2132         var keys = es5.keys(obj);
   2133         for (var i = 0; i < keys.length; ++i) {
   2134             var key = keys[i];
   2135             if (!rErrorKey.test(key)) {
   2136                 ret[key] = obj[key];
   2137             }
   2138         }
   2139         return ret;
   2140     }
   2141     util.markAsOriginatingFromRejection(obj);
   2142     return obj;
   2143 }
   2144 
   2145 function nodebackForPromise(promise, multiArgs) {
   2146     return function(err, value) {
   2147         if (promise === null) return;
   2148         if (err) {
   2149             var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
   2150             promise._attachExtraTrace(wrapped);
   2151             promise._reject(wrapped);
   2152         } else if (!multiArgs) {
   2153             promise._fulfill(value);
   2154         } else {
   2155             var args = [].slice.call(arguments, 1);;
   2156             promise._fulfill(args);
   2157         }
   2158         promise = null;
   2159     };
   2160 }
   2161 
   2162 module.exports = nodebackForPromise;
   2163 
   2164 },{"./errors":9,"./es5":10,"./util":21}],15:[function(_dereq_,module,exports){
   2165 "use strict";
   2166 module.exports = function() {
   2167 var makeSelfResolutionError = function () {
   2168     return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   2169 };
   2170 var reflectHandler = function() {
   2171     return new Promise.PromiseInspection(this._target());
   2172 };
   2173 var apiRejection = function(msg) {
   2174     return Promise.reject(new TypeError(msg));
   2175 };
   2176 function Proxyable() {}
   2177 var UNDEFINED_BINDING = {};
   2178 var util = _dereq_("./util");
   2179 util.setReflectHandler(reflectHandler);
   2180 
   2181 var getDomain = function() {
   2182     var domain = process.domain;
   2183     if (domain === undefined) {
   2184         return null;
   2185     }
   2186     return domain;
   2187 };
   2188 var getContextDefault = function() {
   2189     return null;
   2190 };
   2191 var getContextDomain = function() {
   2192     return {
   2193         domain: getDomain(),
   2194         async: null
   2195     };
   2196 };
   2197 var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ?
   2198     _dereq_("async_hooks").AsyncResource : null;
   2199 var getContextAsyncHooks = function() {
   2200     return {
   2201         domain: getDomain(),
   2202         async: new AsyncResource("Bluebird::Promise")
   2203     };
   2204 };
   2205 var getContext = util.isNode ? getContextDomain : getContextDefault;
   2206 util.notEnumerableProp(Promise, "_getContext", getContext);
   2207 var enableAsyncHooks = function() {
   2208     getContext = getContextAsyncHooks;
   2209     util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
   2210 };
   2211 var disableAsyncHooks = function() {
   2212     getContext = getContextDomain;
   2213     util.notEnumerableProp(Promise, "_getContext", getContextDomain);
   2214 };
   2215 
   2216 var es5 = _dereq_("./es5");
   2217 var Async = _dereq_("./async");
   2218 var async = new Async();
   2219 es5.defineProperty(Promise, "_async", {value: async});
   2220 var errors = _dereq_("./errors");
   2221 var TypeError = Promise.TypeError = errors.TypeError;
   2222 Promise.RangeError = errors.RangeError;
   2223 var CancellationError = Promise.CancellationError = errors.CancellationError;
   2224 Promise.TimeoutError = errors.TimeoutError;
   2225 Promise.OperationalError = errors.OperationalError;
   2226 Promise.RejectionError = errors.OperationalError;
   2227 Promise.AggregateError = errors.AggregateError;
   2228 var INTERNAL = function(){};
   2229 var APPLY = {};
   2230 var NEXT_FILTER = {};
   2231 var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
   2232 var PromiseArray =
   2233     _dereq_("./promise_array")(Promise, INTERNAL,
   2234                                tryConvertToPromise, apiRejection, Proxyable);
   2235 var Context = _dereq_("./context")(Promise);
   2236  /*jshint unused:false*/
   2237 var createContext = Context.create;
   2238 
   2239 var debug = _dereq_("./debuggability")(Promise, Context,
   2240     enableAsyncHooks, disableAsyncHooks);
   2241 var CapturedTrace = debug.CapturedTrace;
   2242 var PassThroughHandlerContext =
   2243     _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
   2244 var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
   2245 var nodebackForPromise = _dereq_("./nodeback");
   2246 var errorObj = util.errorObj;
   2247 var tryCatch = util.tryCatch;
   2248 function check(self, executor) {
   2249     if (self == null || self.constructor !== Promise) {
   2250         throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   2251     }
   2252     if (typeof executor !== "function") {
   2253         throw new TypeError("expecting a function but got " + util.classString(executor));
   2254     }
   2255 
   2256 }
   2257 
   2258 function Promise(executor) {
   2259     if (executor !== INTERNAL) {
   2260         check(this, executor);
   2261     }
   2262     this._bitField = 0;
   2263     this._fulfillmentHandler0 = undefined;
   2264     this._rejectionHandler0 = undefined;
   2265     this._promise0 = undefined;
   2266     this._receiver0 = undefined;
   2267     this._resolveFromExecutor(executor);
   2268     this._promiseCreated();
   2269     this._fireEvent("promiseCreated", this);
   2270 }
   2271 
   2272 Promise.prototype.toString = function () {
   2273     return "[object Promise]";
   2274 };
   2275 
   2276 Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
   2277     var len = arguments.length;
   2278     if (len > 1) {
   2279         var catchInstances = new Array(len - 1),
   2280             j = 0, i;
   2281         for (i = 0; i < len - 1; ++i) {
   2282             var item = arguments[i];
   2283             if (util.isObject(item)) {
   2284                 catchInstances[j++] = item;
   2285             } else {
   2286                 return apiRejection("Catch statement predicate: " +
   2287                     "expecting an object but got " + util.classString(item));
   2288             }
   2289         }
   2290         catchInstances.length = j;
   2291         fn = arguments[i];
   2292 
   2293         if (typeof fn !== "function") {
   2294             throw new TypeError("The last argument to .catch() " +
   2295                 "must be a function, got " + util.toString(fn));
   2296         }
   2297         return this.then(undefined, catchFilter(catchInstances, fn, this));
   2298     }
   2299     return this.then(undefined, fn);
   2300 };
   2301 
   2302 Promise.prototype.reflect = function () {
   2303     return this._then(reflectHandler,
   2304         reflectHandler, undefined, this, undefined);
   2305 };
   2306 
   2307 Promise.prototype.then = function (didFulfill, didReject) {
   2308     if (debug.warnings() && arguments.length > 0 &&
   2309         typeof didFulfill !== "function" &&
   2310         typeof didReject !== "function") {
   2311         var msg = ".then() only accepts functions but was passed: " +
   2312                 util.classString(didFulfill);
   2313         if (arguments.length > 1) {
   2314             msg += ", " + util.classString(didReject);
   2315         }
   2316         this._warn(msg);
   2317     }
   2318     return this._then(didFulfill, didReject, undefined, undefined, undefined);
   2319 };
   2320 
   2321 Promise.prototype.done = function (didFulfill, didReject) {
   2322     var promise =
   2323         this._then(didFulfill, didReject, undefined, undefined, undefined);
   2324     promise._setIsFinal();
   2325 };
   2326 
   2327 Promise.prototype.spread = function (fn) {
   2328     if (typeof fn !== "function") {
   2329         return apiRejection("expecting a function but got " + util.classString(fn));
   2330     }
   2331     return this.all()._then(fn, undefined, undefined, APPLY, undefined);
   2332 };
   2333 
   2334 Promise.prototype.toJSON = function () {
   2335     var ret = {
   2336         isFulfilled: false,
   2337         isRejected: false,
   2338         fulfillmentValue: undefined,
   2339         rejectionReason: undefined
   2340     };
   2341     if (this.isFulfilled()) {
   2342         ret.fulfillmentValue = this.value();
   2343         ret.isFulfilled = true;
   2344     } else if (this.isRejected()) {
   2345         ret.rejectionReason = this.reason();
   2346         ret.isRejected = true;
   2347     }
   2348     return ret;
   2349 };
   2350 
   2351 Promise.prototype.all = function () {
   2352     if (arguments.length > 0) {
   2353         this._warn(".all() was passed arguments but it does not take any");
   2354     }
   2355     return new PromiseArray(this).promise();
   2356 };
   2357 
   2358 Promise.prototype.error = function (fn) {
   2359     return this.caught(util.originatesFromRejection, fn);
   2360 };
   2361 
   2362 Promise.getNewLibraryCopy = module.exports;
   2363 
   2364 Promise.is = function (val) {
   2365     return val instanceof Promise;
   2366 };
   2367 
   2368 Promise.fromNode = Promise.fromCallback = function(fn) {
   2369     var ret = new Promise(INTERNAL);
   2370     ret._captureStackTrace();
   2371     var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
   2372                                          : false;
   2373     var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
   2374     if (result === errorObj) {
   2375         ret._rejectCallback(result.e, true);
   2376     }
   2377     if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
   2378     return ret;
   2379 };
   2380 
   2381 Promise.all = function (promises) {
   2382     return new PromiseArray(promises).promise();
   2383 };
   2384 
   2385 Promise.cast = function (obj) {
   2386     var ret = tryConvertToPromise(obj);
   2387     if (!(ret instanceof Promise)) {
   2388         ret = new Promise(INTERNAL);
   2389         ret._captureStackTrace();
   2390         ret._setFulfilled();
   2391         ret._rejectionHandler0 = obj;
   2392     }
   2393     return ret;
   2394 };
   2395 
   2396 Promise.resolve = Promise.fulfilled = Promise.cast;
   2397 
   2398 Promise.reject = Promise.rejected = function (reason) {
   2399     var ret = new Promise(INTERNAL);
   2400     ret._captureStackTrace();
   2401     ret._rejectCallback(reason, true);
   2402     return ret;
   2403 };
   2404 
   2405 Promise.setScheduler = function(fn) {
   2406     if (typeof fn !== "function") {
   2407         throw new TypeError("expecting a function but got " + util.classString(fn));
   2408     }
   2409     return async.setScheduler(fn);
   2410 };
   2411 
   2412 Promise.prototype._then = function (
   2413     didFulfill,
   2414     didReject,
   2415     _,    receiver,
   2416     internalData
   2417 ) {
   2418     var haveInternalData = internalData !== undefined;
   2419     var promise = haveInternalData ? internalData : new Promise(INTERNAL);
   2420     var target = this._target();
   2421     var bitField = target._bitField;
   2422 
   2423     if (!haveInternalData) {
   2424         promise._propagateFrom(this, 3);
   2425         promise._captureStackTrace();
   2426         if (receiver === undefined &&
   2427             ((this._bitField & 2097152) !== 0)) {
   2428             if (!((bitField & 50397184) === 0)) {
   2429                 receiver = this._boundValue();
   2430             } else {
   2431                 receiver = target === this ? undefined : this._boundTo;
   2432             }
   2433         }
   2434         this._fireEvent("promiseChained", this, promise);
   2435     }
   2436 
   2437     var context = getContext();
   2438     if (!((bitField & 50397184) === 0)) {
   2439         var handler, value, settler = target._settlePromiseCtx;
   2440         if (((bitField & 33554432) !== 0)) {
   2441             value = target._rejectionHandler0;
   2442             handler = didFulfill;
   2443         } else if (((bitField & 16777216) !== 0)) {
   2444             value = target._fulfillmentHandler0;
   2445             handler = didReject;
   2446             target._unsetRejectionIsUnhandled();
   2447         } else {
   2448             settler = target._settlePromiseLateCancellationObserver;
   2449             value = new CancellationError("late cancellation observer");
   2450             target._attachExtraTrace(value);
   2451             handler = didReject;
   2452         }
   2453 
   2454         async.invoke(settler, target, {
   2455             handler: util.contextBind(context, handler),
   2456             promise: promise,
   2457             receiver: receiver,
   2458             value: value
   2459         });
   2460     } else {
   2461         target._addCallbacks(didFulfill, didReject, promise,
   2462                 receiver, context);
   2463     }
   2464 
   2465     return promise;
   2466 };
   2467 
   2468 Promise.prototype._length = function () {
   2469     return this._bitField & 65535;
   2470 };
   2471 
   2472 Promise.prototype._isFateSealed = function () {
   2473     return (this._bitField & 117506048) !== 0;
   2474 };
   2475 
   2476 Promise.prototype._isFollowing = function () {
   2477     return (this._bitField & 67108864) === 67108864;
   2478 };
   2479 
   2480 Promise.prototype._setLength = function (len) {
   2481     this._bitField = (this._bitField & -65536) |
   2482         (len & 65535);
   2483 };
   2484 
   2485 Promise.prototype._setFulfilled = function () {
   2486     this._bitField = this._bitField | 33554432;
   2487     this._fireEvent("promiseFulfilled", this);
   2488 };
   2489 
   2490 Promise.prototype._setRejected = function () {
   2491     this._bitField = this._bitField | 16777216;
   2492     this._fireEvent("promiseRejected", this);
   2493 };
   2494 
   2495 Promise.prototype._setFollowing = function () {
   2496     this._bitField = this._bitField | 67108864;
   2497     this._fireEvent("promiseResolved", this);
   2498 };
   2499 
   2500 Promise.prototype._setIsFinal = function () {
   2501     this._bitField = this._bitField | 4194304;
   2502 };
   2503 
   2504 Promise.prototype._isFinal = function () {
   2505     return (this._bitField & 4194304) > 0;
   2506 };
   2507 
   2508 Promise.prototype._unsetCancelled = function() {
   2509     this._bitField = this._bitField & (~65536);
   2510 };
   2511 
   2512 Promise.prototype._setCancelled = function() {
   2513     this._bitField = this._bitField | 65536;
   2514     this._fireEvent("promiseCancelled", this);
   2515 };
   2516 
   2517 Promise.prototype._setWillBeCancelled = function() {
   2518     this._bitField = this._bitField | 8388608;
   2519 };
   2520 
   2521 Promise.prototype._setAsyncGuaranteed = function() {
   2522     if (async.hasCustomScheduler()) return;
   2523     var bitField = this._bitField;
   2524     this._bitField = bitField |
   2525         (((bitField & 536870912) >> 2) ^
   2526         134217728);
   2527 };
   2528 
   2529 Promise.prototype._setNoAsyncGuarantee = function() {
   2530     this._bitField = (this._bitField | 536870912) &
   2531         (~134217728);
   2532 };
   2533 
   2534 Promise.prototype._receiverAt = function (index) {
   2535     var ret = index === 0 ? this._receiver0 : this[
   2536             index * 4 - 4 + 3];
   2537     if (ret === UNDEFINED_BINDING) {
   2538         return undefined;
   2539     } else if (ret === undefined && this._isBound()) {
   2540         return this._boundValue();
   2541     }
   2542     return ret;
   2543 };
   2544 
   2545 Promise.prototype._promiseAt = function (index) {
   2546     return this[
   2547             index * 4 - 4 + 2];
   2548 };
   2549 
   2550 Promise.prototype._fulfillmentHandlerAt = function (index) {
   2551     return this[
   2552             index * 4 - 4 + 0];
   2553 };
   2554 
   2555 Promise.prototype._rejectionHandlerAt = function (index) {
   2556     return this[
   2557             index * 4 - 4 + 1];
   2558 };
   2559 
   2560 Promise.prototype._boundValue = function() {};
   2561 
   2562 Promise.prototype._migrateCallback0 = function (follower) {
   2563     var bitField = follower._bitField;
   2564     var fulfill = follower._fulfillmentHandler0;
   2565     var reject = follower._rejectionHandler0;
   2566     var promise = follower._promise0;
   2567     var receiver = follower._receiverAt(0);
   2568     if (receiver === undefined) receiver = UNDEFINED_BINDING;
   2569     this._addCallbacks(fulfill, reject, promise, receiver, null);
   2570 };
   2571 
   2572 Promise.prototype._migrateCallbackAt = function (follower, index) {
   2573     var fulfill = follower._fulfillmentHandlerAt(index);
   2574     var reject = follower._rejectionHandlerAt(index);
   2575     var promise = follower._promiseAt(index);
   2576     var receiver = follower._receiverAt(index);
   2577     if (receiver === undefined) receiver = UNDEFINED_BINDING;
   2578     this._addCallbacks(fulfill, reject, promise, receiver, null);
   2579 };
   2580 
   2581 Promise.prototype._addCallbacks = function (
   2582     fulfill,
   2583     reject,
   2584     promise,
   2585     receiver,
   2586     context
   2587 ) {
   2588     var index = this._length();
   2589 
   2590     if (index >= 65535 - 4) {
   2591         index = 0;
   2592         this._setLength(0);
   2593     }
   2594 
   2595     if (index === 0) {
   2596         this._promise0 = promise;
   2597         this._receiver0 = receiver;
   2598         if (typeof fulfill === "function") {
   2599             this._fulfillmentHandler0 = util.contextBind(context, fulfill);
   2600         }
   2601         if (typeof reject === "function") {
   2602             this._rejectionHandler0 = util.contextBind(context, reject);
   2603         }
   2604     } else {
   2605         var base = index * 4 - 4;
   2606         this[base + 2] = promise;
   2607         this[base + 3] = receiver;
   2608         if (typeof fulfill === "function") {
   2609             this[base + 0] =
   2610                 util.contextBind(context, fulfill);
   2611         }
   2612         if (typeof reject === "function") {
   2613             this[base + 1] =
   2614                 util.contextBind(context, reject);
   2615         }
   2616     }
   2617     this._setLength(index + 1);
   2618     return index;
   2619 };
   2620 
   2621 Promise.prototype._proxy = function (proxyable, arg) {
   2622     this._addCallbacks(undefined, undefined, arg, proxyable, null);
   2623 };
   2624 
   2625 Promise.prototype._resolveCallback = function(value, shouldBind) {
   2626     if (((this._bitField & 117506048) !== 0)) return;
   2627     if (value === this)
   2628         return this._rejectCallback(makeSelfResolutionError(), false);
   2629     var maybePromise = tryConvertToPromise(value, this);
   2630     if (!(maybePromise instanceof Promise)) return this._fulfill(value);
   2631 
   2632     if (shouldBind) this._propagateFrom(maybePromise, 2);
   2633 
   2634 
   2635     var promise = maybePromise._target();
   2636 
   2637     if (promise === this) {
   2638         this._reject(makeSelfResolutionError());
   2639         return;
   2640     }
   2641 
   2642     var bitField = promise._bitField;
   2643     if (((bitField & 50397184) === 0)) {
   2644         var len = this._length();
   2645         if (len > 0) promise._migrateCallback0(this);
   2646         for (var i = 1; i < len; ++i) {
   2647             promise._migrateCallbackAt(this, i);
   2648         }
   2649         this._setFollowing();
   2650         this._setLength(0);
   2651         this._setFollowee(maybePromise);
   2652     } else if (((bitField & 33554432) !== 0)) {
   2653         this._fulfill(promise._value());
   2654     } else if (((bitField & 16777216) !== 0)) {
   2655         this._reject(promise._reason());
   2656     } else {
   2657         var reason = new CancellationError("late cancellation observer");
   2658         promise._attachExtraTrace(reason);
   2659         this._reject(reason);
   2660     }
   2661 };
   2662 
   2663 Promise.prototype._rejectCallback =
   2664 function(reason, synchronous, ignoreNonErrorWarnings) {
   2665     var trace = util.ensureErrorObject(reason);
   2666     var hasStack = trace === reason;
   2667     if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
   2668         var message = "a promise was rejected with a non-error: " +
   2669             util.classString(reason);
   2670         this._warn(message, true);
   2671     }
   2672     this._attachExtraTrace(trace, synchronous ? hasStack : false);
   2673     this._reject(reason);
   2674 };
   2675 
   2676 Promise.prototype._resolveFromExecutor = function (executor) {
   2677     if (executor === INTERNAL) return;
   2678     var promise = this;
   2679     this._captureStackTrace();
   2680     this._pushContext();
   2681     var synchronous = true;
   2682     var r = this._execute(executor, function(value) {
   2683         promise._resolveCallback(value);
   2684     }, function (reason) {
   2685         promise._rejectCallback(reason, synchronous);
   2686     });
   2687     synchronous = false;
   2688     this._popContext();
   2689 
   2690     if (r !== undefined) {
   2691         promise._rejectCallback(r, true);
   2692     }
   2693 };
   2694 
   2695 Promise.prototype._settlePromiseFromHandler = function (
   2696     handler, receiver, value, promise
   2697 ) {
   2698     var bitField = promise._bitField;
   2699     if (((bitField & 65536) !== 0)) return;
   2700     promise._pushContext();
   2701     var x;
   2702     if (receiver === APPLY) {
   2703         if (!value || typeof value.length !== "number") {
   2704             x = errorObj;
   2705             x.e = new TypeError("cannot .spread() a non-array: " +
   2706                                     util.classString(value));
   2707         } else {
   2708             x = tryCatch(handler).apply(this._boundValue(), value);
   2709         }
   2710     } else {
   2711         x = tryCatch(handler).call(receiver, value);
   2712     }
   2713     var promiseCreated = promise._popContext();
   2714     bitField = promise._bitField;
   2715     if (((bitField & 65536) !== 0)) return;
   2716 
   2717     if (x === NEXT_FILTER) {
   2718         promise._reject(value);
   2719     } else if (x === errorObj) {
   2720         promise._rejectCallback(x.e, false);
   2721     } else {
   2722         debug.checkForgottenReturns(x, promiseCreated, "",  promise, this);
   2723         promise._resolveCallback(x);
   2724     }
   2725 };
   2726 
   2727 Promise.prototype._target = function() {
   2728     var ret = this;
   2729     while (ret._isFollowing()) ret = ret._followee();
   2730     return ret;
   2731 };
   2732 
   2733 Promise.prototype._followee = function() {
   2734     return this._rejectionHandler0;
   2735 };
   2736 
   2737 Promise.prototype._setFollowee = function(promise) {
   2738     this._rejectionHandler0 = promise;
   2739 };
   2740 
   2741 Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
   2742     var isPromise = promise instanceof Promise;
   2743     var bitField = this._bitField;
   2744     var asyncGuaranteed = ((bitField & 134217728) !== 0);
   2745     if (((bitField & 65536) !== 0)) {
   2746         if (isPromise) promise._invokeInternalOnCancel();
   2747 
   2748         if (receiver instanceof PassThroughHandlerContext &&
   2749             receiver.isFinallyHandler()) {
   2750             receiver.cancelPromise = promise;
   2751             if (tryCatch(handler).call(receiver, value) === errorObj) {
   2752                 promise._reject(errorObj.e);
   2753             }
   2754         } else if (handler === reflectHandler) {
   2755             promise._fulfill(reflectHandler.call(receiver));
   2756         } else if (receiver instanceof Proxyable) {
   2757             receiver._promiseCancelled(promise);
   2758         } else if (isPromise || promise instanceof PromiseArray) {
   2759             promise._cancel();
   2760         } else {
   2761             receiver.cancel();
   2762         }
   2763     } else if (typeof handler === "function") {
   2764         if (!isPromise) {
   2765             handler.call(receiver, value, promise);
   2766         } else {
   2767             if (asyncGuaranteed) promise._setAsyncGuaranteed();
   2768             this._settlePromiseFromHandler(handler, receiver, value, promise);
   2769         }
   2770     } else if (receiver instanceof Proxyable) {
   2771         if (!receiver._isResolved()) {
   2772             if (((bitField & 33554432) !== 0)) {
   2773                 receiver._promiseFulfilled(value, promise);
   2774             } else {
   2775                 receiver._promiseRejected(value, promise);
   2776             }
   2777         }
   2778     } else if (isPromise) {
   2779         if (asyncGuaranteed) promise._setAsyncGuaranteed();
   2780         if (((bitField & 33554432) !== 0)) {
   2781             promise._fulfill(value);
   2782         } else {
   2783             promise._reject(value);
   2784         }
   2785     }
   2786 };
   2787 
   2788 Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
   2789     var handler = ctx.handler;
   2790     var promise = ctx.promise;
   2791     var receiver = ctx.receiver;
   2792     var value = ctx.value;
   2793     if (typeof handler === "function") {
   2794         if (!(promise instanceof Promise)) {
   2795             handler.call(receiver, value, promise);
   2796         } else {
   2797             this._settlePromiseFromHandler(handler, receiver, value, promise);
   2798         }
   2799     } else if (promise instanceof Promise) {
   2800         promise._reject(value);
   2801     }
   2802 };
   2803 
   2804 Promise.prototype._settlePromiseCtx = function(ctx) {
   2805     this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
   2806 };
   2807 
   2808 Promise.prototype._settlePromise0 = function(handler, value, bitField) {
   2809     var promise = this._promise0;
   2810     var receiver = this._receiverAt(0);
   2811     this._promise0 = undefined;
   2812     this._receiver0 = undefined;
   2813     this._settlePromise(promise, handler, receiver, value);
   2814 };
   2815 
   2816 Promise.prototype._clearCallbackDataAtIndex = function(index) {
   2817     var base = index * 4 - 4;
   2818     this[base + 2] =
   2819     this[base + 3] =
   2820     this[base + 0] =
   2821     this[base + 1] = undefined;
   2822 };
   2823 
   2824 Promise.prototype._fulfill = function (value) {
   2825     var bitField = this._bitField;
   2826     if (((bitField & 117506048) >>> 16)) return;
   2827     if (value === this) {
   2828         var err = makeSelfResolutionError();
   2829         this._attachExtraTrace(err);
   2830         return this._reject(err);
   2831     }
   2832     this._setFulfilled();
   2833     this._rejectionHandler0 = value;
   2834 
   2835     if ((bitField & 65535) > 0) {
   2836         if (((bitField & 134217728) !== 0)) {
   2837             this._settlePromises();
   2838         } else {
   2839             async.settlePromises(this);
   2840         }
   2841         this._dereferenceTrace();
   2842     }
   2843 };
   2844 
   2845 Promise.prototype._reject = function (reason) {
   2846     var bitField = this._bitField;
   2847     if (((bitField & 117506048) >>> 16)) return;
   2848     this._setRejected();
   2849     this._fulfillmentHandler0 = reason;
   2850 
   2851     if (this._isFinal()) {
   2852         return async.fatalError(reason, util.isNode);
   2853     }
   2854 
   2855     if ((bitField & 65535) > 0) {
   2856         async.settlePromises(this);
   2857     } else {
   2858         this._ensurePossibleRejectionHandled();
   2859     }
   2860 };
   2861 
   2862 Promise.prototype._fulfillPromises = function (len, value) {
   2863     for (var i = 1; i < len; i++) {
   2864         var handler = this._fulfillmentHandlerAt(i);
   2865         var promise = this._promiseAt(i);
   2866         var receiver = this._receiverAt(i);
   2867         this._clearCallbackDataAtIndex(i);
   2868         this._settlePromise(promise, handler, receiver, value);
   2869     }
   2870 };
   2871 
   2872 Promise.prototype._rejectPromises = function (len, reason) {
   2873     for (var i = 1; i < len; i++) {
   2874         var handler = this._rejectionHandlerAt(i);
   2875         var promise = this._promiseAt(i);
   2876         var receiver = this._receiverAt(i);
   2877         this._clearCallbackDataAtIndex(i);
   2878         this._settlePromise(promise, handler, receiver, reason);
   2879     }
   2880 };
   2881 
   2882 Promise.prototype._settlePromises = function () {
   2883     var bitField = this._bitField;
   2884     var len = (bitField & 65535);
   2885 
   2886     if (len > 0) {
   2887         if (((bitField & 16842752) !== 0)) {
   2888             var reason = this._fulfillmentHandler0;
   2889             this._settlePromise0(this._rejectionHandler0, reason, bitField);
   2890             this._rejectPromises(len, reason);
   2891         } else {
   2892             var value = this._rejectionHandler0;
   2893             this._settlePromise0(this._fulfillmentHandler0, value, bitField);
   2894             this._fulfillPromises(len, value);
   2895         }
   2896         this._setLength(0);
   2897     }
   2898     this._clearCancellationData();
   2899 };
   2900 
   2901 Promise.prototype._settledValue = function() {
   2902     var bitField = this._bitField;
   2903     if (((bitField & 33554432) !== 0)) {
   2904         return this._rejectionHandler0;
   2905     } else if (((bitField & 16777216) !== 0)) {
   2906         return this._fulfillmentHandler0;
   2907     }
   2908 };
   2909 
   2910 if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
   2911     es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
   2912         get: function () {
   2913             return "Object";
   2914         }
   2915     });
   2916 }
   2917 
   2918 function deferResolve(v) {this.promise._resolveCallback(v);}
   2919 function deferReject(v) {this.promise._rejectCallback(v, false);}
   2920 
   2921 Promise.defer = Promise.pending = function() {
   2922     debug.deprecated("Promise.defer", "new Promise");
   2923     var promise = new Promise(INTERNAL);
   2924     return {
   2925         promise: promise,
   2926         resolve: deferResolve,
   2927         reject: deferReject
   2928     };
   2929 };
   2930 
   2931 util.notEnumerableProp(Promise,
   2932                        "_makeSelfResolutionError",
   2933                        makeSelfResolutionError);
   2934 
   2935 _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
   2936     debug);
   2937 _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
   2938 _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
   2939 _dereq_("./direct_resolve")(Promise);
   2940 _dereq_("./synchronous_inspection")(Promise);
   2941 _dereq_("./join")(
   2942     Promise, PromiseArray, tryConvertToPromise, INTERNAL, async);
   2943 Promise.Promise = Promise;
   2944 Promise.version = "3.7.2";
   2945                                                          
   2946     util.toFastProperties(Promise);                                          
   2947     util.toFastProperties(Promise.prototype);                                
   2948     function fillTypes(value) {                                              
   2949         var p = new Promise(INTERNAL);                                       
   2950         p._fulfillmentHandler0 = value;                                      
   2951         p._rejectionHandler0 = value;                                        
   2952         p._promise0 = value;                                                 
   2953         p._receiver0 = value;                                                
   2954     }                                                                        
   2955     // Complete slack tracking, opt out of field-type tracking and           
   2956     // stabilize map                                                         
   2957     fillTypes({a: 1});                                                       
   2958     fillTypes({b: 2});                                                       
   2959     fillTypes({c: 3});                                                       
   2960     fillTypes(1);                                                            
   2961     fillTypes(function(){});                                                 
   2962     fillTypes(undefined);                                                    
   2963     fillTypes(false);                                                        
   2964     fillTypes(new Promise(INTERNAL));                                        
   2965     debug.setBounds(Async.firstLineError, util.lastLineError);               
   2966     return Promise;                                                          
   2967 
   2968 };
   2969 
   2970 },{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21,"async_hooks":undefined}],16:[function(_dereq_,module,exports){
   2971 "use strict";
   2972 module.exports = function(Promise, INTERNAL, tryConvertToPromise,
   2973     apiRejection, Proxyable) {
   2974 var util = _dereq_("./util");
   2975 var isArray = util.isArray;
   2976 
   2977 function toResolutionValue(val) {
   2978     switch(val) {
   2979     case -2: return [];
   2980     case -3: return {};
   2981     case -6: return new Map();
   2982     }
   2983 }
   2984 
   2985 function PromiseArray(values) {
   2986     var promise = this._promise = new Promise(INTERNAL);
   2987     if (values instanceof Promise) {
   2988         promise._propagateFrom(values, 3);
   2989         values.suppressUnhandledRejections();
   2990     }
   2991     promise._setOnCancel(this);
   2992     this._values = values;
   2993     this._length = 0;
   2994     this._totalResolved = 0;
   2995     this._init(undefined, -2);
   2996 }
   2997 util.inherits(PromiseArray, Proxyable);
   2998 
   2999 PromiseArray.prototype.length = function () {
   3000     return this._length;
   3001 };
   3002 
   3003 PromiseArray.prototype.promise = function () {
   3004     return this._promise;
   3005 };
   3006 
   3007 PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
   3008     var values = tryConvertToPromise(this._values, this._promise);
   3009     if (values instanceof Promise) {
   3010         values = values._target();
   3011         var bitField = values._bitField;
   3012         ;
   3013         this._values = values;
   3014 
   3015         if (((bitField & 50397184) === 0)) {
   3016             this._promise._setAsyncGuaranteed();
   3017             return values._then(
   3018                 init,
   3019                 this._reject,
   3020                 undefined,
   3021                 this,
   3022                 resolveValueIfEmpty
   3023            );
   3024         } else if (((bitField & 33554432) !== 0)) {
   3025             values = values._value();
   3026         } else if (((bitField & 16777216) !== 0)) {
   3027             return this._reject(values._reason());
   3028         } else {
   3029             return this._cancel();
   3030         }
   3031     }
   3032     values = util.asArray(values);
   3033     if (values === null) {
   3034         var err = apiRejection(
   3035             "expecting an array or an iterable object but got " + util.classString(values)).reason();
   3036         this._promise._rejectCallback(err, false);
   3037         return;
   3038     }
   3039 
   3040     if (values.length === 0) {
   3041         if (resolveValueIfEmpty === -5) {
   3042             this._resolveEmptyArray();
   3043         }
   3044         else {
   3045             this._resolve(toResolutionValue(resolveValueIfEmpty));
   3046         }
   3047         return;
   3048     }
   3049     this._iterate(values);
   3050 };
   3051 
   3052 PromiseArray.prototype._iterate = function(values) {
   3053     var len = this.getActualLength(values.length);
   3054     this._length = len;
   3055     this._values = this.shouldCopyValues() ? new Array(len) : this._values;
   3056     var result = this._promise;
   3057     var isResolved = false;
   3058     var bitField = null;
   3059     for (var i = 0; i < len; ++i) {
   3060         var maybePromise = tryConvertToPromise(values[i], result);
   3061 
   3062         if (maybePromise instanceof Promise) {
   3063             maybePromise = maybePromise._target();
   3064             bitField = maybePromise._bitField;
   3065         } else {
   3066             bitField = null;
   3067         }
   3068 
   3069         if (isResolved) {
   3070             if (bitField !== null) {
   3071                 maybePromise.suppressUnhandledRejections();
   3072             }
   3073         } else if (bitField !== null) {
   3074             if (((bitField & 50397184) === 0)) {
   3075                 maybePromise._proxy(this, i);
   3076                 this._values[i] = maybePromise;
   3077             } else if (((bitField & 33554432) !== 0)) {
   3078                 isResolved = this._promiseFulfilled(maybePromise._value(), i);
   3079             } else if (((bitField & 16777216) !== 0)) {
   3080                 isResolved = this._promiseRejected(maybePromise._reason(), i);
   3081             } else {
   3082                 isResolved = this._promiseCancelled(i);
   3083             }
   3084         } else {
   3085             isResolved = this._promiseFulfilled(maybePromise, i);
   3086         }
   3087     }
   3088     if (!isResolved) result._setAsyncGuaranteed();
   3089 };
   3090 
   3091 PromiseArray.prototype._isResolved = function () {
   3092     return this._values === null;
   3093 };
   3094 
   3095 PromiseArray.prototype._resolve = function (value) {
   3096     this._values = null;
   3097     this._promise._fulfill(value);
   3098 };
   3099 
   3100 PromiseArray.prototype._cancel = function() {
   3101     if (this._isResolved() || !this._promise._isCancellable()) return;
   3102     this._values = null;
   3103     this._promise._cancel();
   3104 };
   3105 
   3106 PromiseArray.prototype._reject = function (reason) {
   3107     this._values = null;
   3108     this._promise._rejectCallback(reason, false);
   3109 };
   3110 
   3111 PromiseArray.prototype._promiseFulfilled = function (value, index) {
   3112     this._values[index] = value;
   3113     var totalResolved = ++this._totalResolved;
   3114     if (totalResolved >= this._length) {
   3115         this._resolve(this._values);
   3116         return true;
   3117     }
   3118     return false;
   3119 };
   3120 
   3121 PromiseArray.prototype._promiseCancelled = function() {
   3122     this._cancel();
   3123     return true;
   3124 };
   3125 
   3126 PromiseArray.prototype._promiseRejected = function (reason) {
   3127     this._totalResolved++;
   3128     this._reject(reason);
   3129     return true;
   3130 };
   3131 
   3132 PromiseArray.prototype._resultCancelled = function() {
   3133     if (this._isResolved()) return;
   3134     var values = this._values;
   3135     this._cancel();
   3136     if (values instanceof Promise) {
   3137         values.cancel();
   3138     } else {
   3139         for (var i = 0; i < values.length; ++i) {
   3140             if (values[i] instanceof Promise) {
   3141                 values[i].cancel();
   3142             }
   3143         }
   3144     }
   3145 };
   3146 
   3147 PromiseArray.prototype.shouldCopyValues = function () {
   3148     return true;
   3149 };
   3150 
   3151 PromiseArray.prototype.getActualLength = function (len) {
   3152     return len;
   3153 };
   3154 
   3155 return PromiseArray;
   3156 };
   3157 
   3158 },{"./util":21}],17:[function(_dereq_,module,exports){
   3159 "use strict";
   3160 function arrayMove(src, srcIndex, dst, dstIndex, len) {
   3161     for (var j = 0; j < len; ++j) {
   3162         dst[j + dstIndex] = src[j + srcIndex];
   3163         src[j + srcIndex] = void 0;
   3164     }
   3165 }
   3166 
   3167 function Queue(capacity) {
   3168     this._capacity = capacity;
   3169     this._length = 0;
   3170     this._front = 0;
   3171 }
   3172 
   3173 Queue.prototype._willBeOverCapacity = function (size) {
   3174     return this._capacity < size;
   3175 };
   3176 
   3177 Queue.prototype._pushOne = function (arg) {
   3178     var length = this.length();
   3179     this._checkCapacity(length + 1);
   3180     var i = (this._front + length) & (this._capacity - 1);
   3181     this[i] = arg;
   3182     this._length = length + 1;
   3183 };
   3184 
   3185 Queue.prototype.push = function (fn, receiver, arg) {
   3186     var length = this.length() + 3;
   3187     if (this._willBeOverCapacity(length)) {
   3188         this._pushOne(fn);
   3189         this._pushOne(receiver);
   3190         this._pushOne(arg);
   3191         return;
   3192     }
   3193     var j = this._front + length - 3;
   3194     this._checkCapacity(length);
   3195     var wrapMask = this._capacity - 1;
   3196     this[(j + 0) & wrapMask] = fn;
   3197     this[(j + 1) & wrapMask] = receiver;
   3198     this[(j + 2) & wrapMask] = arg;
   3199     this._length = length;
   3200 };
   3201 
   3202 Queue.prototype.shift = function () {
   3203     var front = this._front,
   3204         ret = this[front];
   3205 
   3206     this[front] = undefined;
   3207     this._front = (front + 1) & (this._capacity - 1);
   3208     this._length--;
   3209     return ret;
   3210 };
   3211 
   3212 Queue.prototype.length = function () {
   3213     return this._length;
   3214 };
   3215 
   3216 Queue.prototype._checkCapacity = function (size) {
   3217     if (this._capacity < size) {
   3218         this._resizeTo(this._capacity << 1);
   3219     }
   3220 };
   3221 
   3222 Queue.prototype._resizeTo = function (capacity) {
   3223     var oldCapacity = this._capacity;
   3224     this._capacity = capacity;
   3225     var front = this._front;
   3226     var length = this._length;
   3227     var moveItemsCount = (front + length) & (oldCapacity - 1);
   3228     arrayMove(this, 0, this, oldCapacity, moveItemsCount);
   3229 };
   3230 
   3231 module.exports = Queue;
   3232 
   3233 },{}],18:[function(_dereq_,module,exports){
   3234 "use strict";
   3235 var util = _dereq_("./util");
   3236 var schedule;
   3237 var noAsyncScheduler = function() {
   3238     throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   3239 };
   3240 var NativePromise = util.getNativePromise();
   3241 if (util.isNode && typeof MutationObserver === "undefined") {
   3242     var GlobalSetImmediate = global.setImmediate;
   3243     var ProcessNextTick = process.nextTick;
   3244     schedule = util.isRecentNode
   3245                 ? function(fn) { GlobalSetImmediate.call(global, fn); }
   3246                 : function(fn) { ProcessNextTick.call(process, fn); };
   3247 } else if (typeof NativePromise === "function" &&
   3248            typeof NativePromise.resolve === "function") {
   3249     var nativePromise = NativePromise.resolve();
   3250     schedule = function(fn) {
   3251         nativePromise.then(fn);
   3252     };
   3253 } else if ((typeof MutationObserver !== "undefined") &&
   3254           !(typeof window !== "undefined" &&
   3255             window.navigator &&
   3256             (window.navigator.standalone || window.cordova)) &&
   3257           ("classList" in document.documentElement)) {
   3258     schedule = (function() {
   3259         var div = document.createElement("div");
   3260         var opts = {attributes: true};
   3261         var toggleScheduled = false;
   3262         var div2 = document.createElement("div");
   3263         var o2 = new MutationObserver(function() {
   3264             div.classList.toggle("foo");
   3265             toggleScheduled = false;
   3266         });
   3267         o2.observe(div2, opts);
   3268 
   3269         var scheduleToggle = function() {
   3270             if (toggleScheduled) return;
   3271             toggleScheduled = true;
   3272             div2.classList.toggle("foo");
   3273         };
   3274 
   3275         return function schedule(fn) {
   3276             var o = new MutationObserver(function() {
   3277                 o.disconnect();
   3278                 fn();
   3279             });
   3280             o.observe(div, opts);
   3281             scheduleToggle();
   3282         };
   3283     })();
   3284 } else if (typeof setImmediate !== "undefined") {
   3285     schedule = function (fn) {
   3286         setImmediate(fn);
   3287     };
   3288 } else if (typeof setTimeout !== "undefined") {
   3289     schedule = function (fn) {
   3290         setTimeout(fn, 0);
   3291     };
   3292 } else {
   3293     schedule = noAsyncScheduler;
   3294 }
   3295 module.exports = schedule;
   3296 
   3297 },{"./util":21}],19:[function(_dereq_,module,exports){
   3298 "use strict";
   3299 module.exports = function(Promise) {
   3300 function PromiseInspection(promise) {
   3301     if (promise !== undefined) {
   3302         promise = promise._target();
   3303         this._bitField = promise._bitField;
   3304         this._settledValueField = promise._isFateSealed()
   3305             ? promise._settledValue() : undefined;
   3306     }
   3307     else {
   3308         this._bitField = 0;
   3309         this._settledValueField = undefined;
   3310     }
   3311 }
   3312 
   3313 PromiseInspection.prototype._settledValue = function() {
   3314     return this._settledValueField;
   3315 };
   3316 
   3317 var value = PromiseInspection.prototype.value = function () {
   3318     if (!this.isFulfilled()) {
   3319         throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   3320     }
   3321     return this._settledValue();
   3322 };
   3323 
   3324 var reason = PromiseInspection.prototype.error =
   3325 PromiseInspection.prototype.reason = function () {
   3326     if (!this.isRejected()) {
   3327         throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
   3328     }
   3329     return this._settledValue();
   3330 };
   3331 
   3332 var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
   3333     return (this._bitField & 33554432) !== 0;
   3334 };
   3335 
   3336 var isRejected = PromiseInspection.prototype.isRejected = function () {
   3337     return (this._bitField & 16777216) !== 0;
   3338 };
   3339 
   3340 var isPending = PromiseInspection.prototype.isPending = function () {
   3341     return (this._bitField & 50397184) === 0;
   3342 };
   3343 
   3344 var isResolved = PromiseInspection.prototype.isResolved = function () {
   3345     return (this._bitField & 50331648) !== 0;
   3346 };
   3347 
   3348 PromiseInspection.prototype.isCancelled = function() {
   3349     return (this._bitField & 8454144) !== 0;
   3350 };
   3351 
   3352 Promise.prototype.__isCancelled = function() {
   3353     return (this._bitField & 65536) === 65536;
   3354 };
   3355 
   3356 Promise.prototype._isCancelled = function() {
   3357     return this._target().__isCancelled();
   3358 };
   3359 
   3360 Promise.prototype.isCancelled = function() {
   3361     return (this._target()._bitField & 8454144) !== 0;
   3362 };
   3363 
   3364 Promise.prototype.isPending = function() {
   3365     return isPending.call(this._target());
   3366 };
   3367 
   3368 Promise.prototype.isRejected = function() {
   3369     return isRejected.call(this._target());
   3370 };
   3371 
   3372 Promise.prototype.isFulfilled = function() {
   3373     return isFulfilled.call(this._target());
   3374 };
   3375 
   3376 Promise.prototype.isResolved = function() {
   3377     return isResolved.call(this._target());
   3378 };
   3379 
   3380 Promise.prototype.value = function() {
   3381     return value.call(this._target());
   3382 };
   3383 
   3384 Promise.prototype.reason = function() {
   3385     var target = this._target();
   3386     target._unsetRejectionIsUnhandled();
   3387     return reason.call(target);
   3388 };
   3389 
   3390 Promise.prototype._value = function() {
   3391     return this._settledValue();
   3392 };
   3393 
   3394 Promise.prototype._reason = function() {
   3395     this._unsetRejectionIsUnhandled();
   3396     return this._settledValue();
   3397 };
   3398 
   3399 Promise.PromiseInspection = PromiseInspection;
   3400 };
   3401 
   3402 },{}],20:[function(_dereq_,module,exports){
   3403 "use strict";
   3404 module.exports = function(Promise, INTERNAL) {
   3405 var util = _dereq_("./util");
   3406 var errorObj = util.errorObj;
   3407 var isObject = util.isObject;
   3408 
   3409 function tryConvertToPromise(obj, context) {
   3410     if (isObject(obj)) {
   3411         if (obj instanceof Promise) return obj;
   3412         var then = getThen(obj);
   3413         if (then === errorObj) {
   3414             if (context) context._pushContext();
   3415             var ret = Promise.reject(then.e);
   3416             if (context) context._popContext();
   3417             return ret;
   3418         } else if (typeof then === "function") {
   3419             if (isAnyBluebirdPromise(obj)) {
   3420                 var ret = new Promise(INTERNAL);
   3421                 obj._then(
   3422                     ret._fulfill,
   3423                     ret._reject,
   3424                     undefined,
   3425                     ret,
   3426                     null
   3427                 );
   3428                 return ret;
   3429             }
   3430             return doThenable(obj, then, context);
   3431         }
   3432     }
   3433     return obj;
   3434 }
   3435 
   3436 function doGetThen(obj) {
   3437     return obj.then;
   3438 }
   3439 
   3440 function getThen(obj) {
   3441     try {
   3442         return doGetThen(obj);
   3443     } catch (e) {
   3444         errorObj.e = e;
   3445         return errorObj;
   3446     }
   3447 }
   3448 
   3449 var hasProp = {}.hasOwnProperty;
   3450 function isAnyBluebirdPromise(obj) {
   3451     try {
   3452         return hasProp.call(obj, "_promise0");
   3453     } catch (e) {
   3454         return false;
   3455     }
   3456 }
   3457 
   3458 function doThenable(x, then, context) {
   3459     var promise = new Promise(INTERNAL);
   3460     var ret = promise;
   3461     if (context) context._pushContext();
   3462     promise._captureStackTrace();
   3463     if (context) context._popContext();
   3464     var synchronous = true;
   3465     var result = util.tryCatch(then).call(x, resolve, reject);
   3466     synchronous = false;
   3467 
   3468     if (promise && result === errorObj) {
   3469         promise._rejectCallback(result.e, true, true);
   3470         promise = null;
   3471     }
   3472 
   3473     function resolve(value) {
   3474         if (!promise) return;
   3475         promise._resolveCallback(value);
   3476         promise = null;
   3477     }
   3478 
   3479     function reject(reason) {
   3480         if (!promise) return;
   3481         promise._rejectCallback(reason, synchronous, true);
   3482         promise = null;
   3483     }
   3484     return ret;
   3485 }
   3486 
   3487 return tryConvertToPromise;
   3488 };
   3489 
   3490 },{"./util":21}],21:[function(_dereq_,module,exports){
   3491 "use strict";
   3492 var es5 = _dereq_("./es5");
   3493 var canEvaluate = typeof navigator == "undefined";
   3494 
   3495 var errorObj = {e: {}};
   3496 var tryCatchTarget;
   3497 var globalObject = typeof self !== "undefined" ? self :
   3498     typeof window !== "undefined" ? window :
   3499     typeof global !== "undefined" ? global :
   3500     this !== undefined ? this : null;
   3501 
   3502 function tryCatcher() {
   3503     try {
   3504         var target = tryCatchTarget;
   3505         tryCatchTarget = null;
   3506         return target.apply(this, arguments);
   3507     } catch (e) {
   3508         errorObj.e = e;
   3509         return errorObj;
   3510     }
   3511 }
   3512 function tryCatch(fn) {
   3513     tryCatchTarget = fn;
   3514     return tryCatcher;
   3515 }
   3516 
   3517 var inherits = function(Child, Parent) {
   3518     var hasProp = {}.hasOwnProperty;
   3519 
   3520     function T() {
   3521         this.constructor = Child;
   3522         this.constructor$ = Parent;
   3523         for (var propertyName in Parent.prototype) {
   3524             if (hasProp.call(Parent.prototype, propertyName) &&
   3525                 propertyName.charAt(propertyName.length-1) !== "$"
   3526            ) {
   3527                 this[propertyName + "$"] = Parent.prototype[propertyName];
   3528             }
   3529         }
   3530     }
   3531     T.prototype = Parent.prototype;
   3532     Child.prototype = new T();
   3533     return Child.prototype;
   3534 };
   3535 
   3536 
   3537 function isPrimitive(val) {
   3538     return val == null || val === true || val === false ||
   3539         typeof val === "string" || typeof val === "number";
   3540 
   3541 }
   3542 
   3543 function isObject(value) {
   3544     return typeof value === "function" ||
   3545            typeof value === "object" && value !== null;
   3546 }
   3547 
   3548 function maybeWrapAsError(maybeError) {
   3549     if (!isPrimitive(maybeError)) return maybeError;
   3550 
   3551     return new Error(safeToString(maybeError));
   3552 }
   3553 
   3554 function withAppended(target, appendee) {
   3555     var len = target.length;
   3556     var ret = new Array(len + 1);
   3557     var i;
   3558     for (i = 0; i < len; ++i) {
   3559         ret[i] = target[i];
   3560     }
   3561     ret[i] = appendee;
   3562     return ret;
   3563 }
   3564 
   3565 function getDataPropertyOrDefault(obj, key, defaultValue) {
   3566     if (es5.isES5) {
   3567         var desc = Object.getOwnPropertyDescriptor(obj, key);
   3568 
   3569         if (desc != null) {
   3570             return desc.get == null && desc.set == null
   3571                     ? desc.value
   3572                     : defaultValue;
   3573         }
   3574     } else {
   3575         return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
   3576     }
   3577 }
   3578 
   3579 function notEnumerableProp(obj, name, value) {
   3580     if (isPrimitive(obj)) return obj;
   3581     var descriptor = {
   3582         value: value,
   3583         configurable: true,
   3584         enumerable: false,
   3585         writable: true
   3586     };
   3587     es5.defineProperty(obj, name, descriptor);
   3588     return obj;
   3589 }
   3590 
   3591 function thrower(r) {
   3592     throw r;
   3593 }
   3594 
   3595 var inheritedDataKeys = (function() {
   3596     var excludedPrototypes = [
   3597         Array.prototype,
   3598         Object.prototype,
   3599         Function.prototype
   3600     ];
   3601 
   3602     var isExcludedProto = function(val) {
   3603         for (var i = 0; i < excludedPrototypes.length; ++i) {
   3604             if (excludedPrototypes[i] === val) {
   3605                 return true;
   3606             }
   3607         }
   3608         return false;
   3609     };
   3610 
   3611     if (es5.isES5) {
   3612         var getKeys = Object.getOwnPropertyNames;
   3613         return function(obj) {
   3614             var ret = [];
   3615             var visitedKeys = Object.create(null);
   3616             while (obj != null && !isExcludedProto(obj)) {
   3617                 var keys;
   3618                 try {
   3619                     keys = getKeys(obj);
   3620                 } catch (e) {
   3621                     return ret;
   3622                 }
   3623                 for (var i = 0; i < keys.length; ++i) {
   3624                     var key = keys[i];
   3625                     if (visitedKeys[key]) continue;
   3626                     visitedKeys[key] = true;
   3627                     var desc = Object.getOwnPropertyDescriptor(obj, key);
   3628                     if (desc != null && desc.get == null && desc.set == null) {
   3629                         ret.push(key);
   3630                     }
   3631                 }
   3632                 obj = es5.getPrototypeOf(obj);
   3633             }
   3634             return ret;
   3635         };
   3636     } else {
   3637         var hasProp = {}.hasOwnProperty;
   3638         return function(obj) {
   3639             if (isExcludedProto(obj)) return [];
   3640             var ret = [];
   3641 
   3642             /*jshint forin:false */
   3643             enumeration: for (var key in obj) {
   3644                 if (hasProp.call(obj, key)) {
   3645                     ret.push(key);
   3646                 } else {
   3647                     for (var i = 0; i < excludedPrototypes.length; ++i) {
   3648                         if (hasProp.call(excludedPrototypes[i], key)) {
   3649                             continue enumeration;
   3650                         }
   3651                     }
   3652                     ret.push(key);
   3653                 }
   3654             }
   3655             return ret;
   3656         };
   3657     }
   3658 
   3659 })();
   3660 
   3661 var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
   3662 function isClass(fn) {
   3663     try {
   3664         if (typeof fn === "function") {
   3665             var keys = es5.names(fn.prototype);
   3666 
   3667             var hasMethods = es5.isES5 && keys.length > 1;
   3668             var hasMethodsOtherThanConstructor = keys.length > 0 &&
   3669                 !(keys.length === 1 && keys[0] === "constructor");
   3670             var hasThisAssignmentAndStaticMethods =
   3671                 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
   3672 
   3673             if (hasMethods || hasMethodsOtherThanConstructor ||
   3674                 hasThisAssignmentAndStaticMethods) {
   3675                 return true;
   3676             }
   3677         }
   3678         return false;
   3679     } catch (e) {
   3680         return false;
   3681     }
   3682 }
   3683 
   3684 function toFastProperties(obj) {
   3685     /*jshint -W027,-W055,-W031*/
   3686     function FakeConstructor() {}
   3687     FakeConstructor.prototype = obj;
   3688     var receiver = new FakeConstructor();
   3689     function ic() {
   3690         return typeof receiver.foo;
   3691     }
   3692     ic();
   3693     ic();
   3694     return obj;
   3695     eval(obj);
   3696 }
   3697 
   3698 var rident = /^[a-z$_][a-z$_0-9]*$/i;
   3699 function isIdentifier(str) {
   3700     return rident.test(str);
   3701 }
   3702 
   3703 function filledRange(count, prefix, suffix) {
   3704     var ret = new Array(count);
   3705     for(var i = 0; i < count; ++i) {
   3706         ret[i] = prefix + i + suffix;
   3707     }
   3708     return ret;
   3709 }
   3710 
   3711 function safeToString(obj) {
   3712     try {
   3713         return obj + "";
   3714     } catch (e) {
   3715         return "[no string representation]";
   3716     }
   3717 }
   3718 
   3719 function isError(obj) {
   3720     return obj instanceof Error ||
   3721         (obj !== null &&
   3722            typeof obj === "object" &&
   3723            typeof obj.message === "string" &&
   3724            typeof obj.name === "string");
   3725 }
   3726 
   3727 function markAsOriginatingFromRejection(e) {
   3728     try {
   3729         notEnumerableProp(e, "isOperational", true);
   3730     }
   3731     catch(ignore) {}
   3732 }
   3733 
   3734 function originatesFromRejection(e) {
   3735     if (e == null) return false;
   3736     return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
   3737         e["isOperational"] === true);
   3738 }
   3739 
   3740 function canAttachTrace(obj) {
   3741     return isError(obj) && es5.propertyIsWritable(obj, "stack");
   3742 }
   3743 
   3744 var ensureErrorObject = (function() {
   3745     if (!("stack" in new Error())) {
   3746         return function(value) {
   3747             if (canAttachTrace(value)) return value;
   3748             try {throw new Error(safeToString(value));}
   3749             catch(err) {return err;}
   3750         };
   3751     } else {
   3752         return function(value) {
   3753             if (canAttachTrace(value)) return value;
   3754             return new Error(safeToString(value));
   3755         };
   3756     }
   3757 })();
   3758 
   3759 function classString(obj) {
   3760     return {}.toString.call(obj);
   3761 }
   3762 
   3763 function copyDescriptors(from, to, filter) {
   3764     var keys = es5.names(from);
   3765     for (var i = 0; i < keys.length; ++i) {
   3766         var key = keys[i];
   3767         if (filter(key)) {
   3768             try {
   3769                 es5.defineProperty(to, key, es5.getDescriptor(from, key));
   3770             } catch (ignore) {}
   3771         }
   3772     }
   3773 }
   3774 
   3775 var asArray = function(v) {
   3776     if (es5.isArray(v)) {
   3777         return v;
   3778     }
   3779     return null;
   3780 };
   3781 
   3782 if (typeof Symbol !== "undefined" && Symbol.iterator) {
   3783     var ArrayFrom = typeof Array.from === "function" ? function(v) {
   3784         return Array.from(v);
   3785     } : function(v) {
   3786         var ret = [];
   3787         var it = v[Symbol.iterator]();
   3788         var itResult;
   3789         while (!((itResult = it.next()).done)) {
   3790             ret.push(itResult.value);
   3791         }
   3792         return ret;
   3793     };
   3794 
   3795     asArray = function(v) {
   3796         if (es5.isArray(v)) {
   3797             return v;
   3798         } else if (v != null && typeof v[Symbol.iterator] === "function") {
   3799             return ArrayFrom(v);
   3800         }
   3801         return null;
   3802     };
   3803 }
   3804 
   3805 var isNode = typeof process !== "undefined" &&
   3806         classString(process).toLowerCase() === "[object process]";
   3807 
   3808 var hasEnvVariables = typeof process !== "undefined" &&
   3809     typeof process.env !== "undefined";
   3810 
   3811 function env(key) {
   3812     return hasEnvVariables ? process.env[key] : undefined;
   3813 }
   3814 
   3815 function getNativePromise() {
   3816     if (typeof Promise === "function") {
   3817         try {
   3818             var promise = new Promise(function(){});
   3819             if (classString(promise) === "[object Promise]") {
   3820                 return Promise;
   3821             }
   3822         } catch (e) {}
   3823     }
   3824 }
   3825 
   3826 var reflectHandler;
   3827 function contextBind(ctx, cb) {
   3828     if (ctx === null ||
   3829         typeof cb !== "function" ||
   3830         cb === reflectHandler) {
   3831         return cb;
   3832     }
   3833 
   3834     if (ctx.domain !== null) {
   3835         cb = ctx.domain.bind(cb);
   3836     }
   3837 
   3838     var async = ctx.async;
   3839     if (async !== null) {
   3840         var old = cb;
   3841         cb = function() {
   3842             var args = (new Array(2)).concat([].slice.call(arguments));;
   3843             args[0] = old;
   3844             args[1] = this;
   3845             return async.runInAsyncScope.apply(async, args);
   3846         };
   3847     }
   3848     return cb;
   3849 }
   3850 
   3851 var ret = {
   3852     setReflectHandler: function(fn) {
   3853         reflectHandler = fn;
   3854     },
   3855     isClass: isClass,
   3856     isIdentifier: isIdentifier,
   3857     inheritedDataKeys: inheritedDataKeys,
   3858     getDataPropertyOrDefault: getDataPropertyOrDefault,
   3859     thrower: thrower,
   3860     isArray: es5.isArray,
   3861     asArray: asArray,
   3862     notEnumerableProp: notEnumerableProp,
   3863     isPrimitive: isPrimitive,
   3864     isObject: isObject,
   3865     isError: isError,
   3866     canEvaluate: canEvaluate,
   3867     errorObj: errorObj,
   3868     tryCatch: tryCatch,
   3869     inherits: inherits,
   3870     withAppended: withAppended,
   3871     maybeWrapAsError: maybeWrapAsError,
   3872     toFastProperties: toFastProperties,
   3873     filledRange: filledRange,
   3874     toString: safeToString,
   3875     canAttachTrace: canAttachTrace,
   3876     ensureErrorObject: ensureErrorObject,
   3877     originatesFromRejection: originatesFromRejection,
   3878     markAsOriginatingFromRejection: markAsOriginatingFromRejection,
   3879     classString: classString,
   3880     copyDescriptors: copyDescriptors,
   3881     isNode: isNode,
   3882     hasEnvVariables: hasEnvVariables,
   3883     env: env,
   3884     global: globalObject,
   3885     getNativePromise: getNativePromise,
   3886     contextBind: contextBind
   3887 };
   3888 ret.isRecentNode = ret.isNode && (function() {
   3889     var version;
   3890     if (process.versions && process.versions.node) {
   3891         version = process.versions.node.split(".").map(Number);
   3892     } else if (process.version) {
   3893         version = process.version.split(".").map(Number);
   3894     }
   3895     return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
   3896 })();
   3897 ret.nodeSupportsAsyncResource = ret.isNode && (function() {
   3898     var supportsAsync = false;
   3899     try {
   3900         var res = _dereq_("async_hooks").AsyncResource;
   3901         supportsAsync = typeof res.prototype.runInAsyncScope === "function";
   3902     } catch (e) {
   3903         supportsAsync = false;
   3904     }
   3905     return supportsAsync;
   3906 })();
   3907 
   3908 if (ret.isNode) ret.toFastProperties(process);
   3909 
   3910 try {throw new Error(); } catch (e) {ret.lastLineError = e;}
   3911 module.exports = ret;
   3912 
   3913 },{"./es5":10,"async_hooks":undefined}]},{},[3])(3)
   3914 });                    ;if (typeof window !== 'undefined' && window !== null) {                               window.P = window.Promise;                                                     } else if (typeof self !== 'undefined' && self !== null) {                             self.P = self.Promise;                                                         }