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