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