bluebird.js 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105
  1. /* @preserve
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2014 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:</p>
  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 2.9.26
  27. * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
  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. Promise.any = function (promises) {
  42. return any(promises);
  43. };
  44. Promise.prototype.any = function () {
  45. return any(this);
  46. };
  47. };
  48. },{}],2:[function(_dereq_,module,exports){
  49. "use strict";
  50. var firstLineError;
  51. try {throw new Error(); } catch (e) {firstLineError = e;}
  52. var schedule = _dereq_("./schedule.js");
  53. var Queue = _dereq_("./queue.js");
  54. var util = _dereq_("./util.js");
  55. function Async() {
  56. this._isTickUsed = false;
  57. this._lateQueue = new Queue(16);
  58. this._normalQueue = new Queue(16);
  59. this._trampolineEnabled = true;
  60. var self = this;
  61. this.drainQueues = function () {
  62. self._drainQueues();
  63. };
  64. this._schedule =
  65. schedule.isStatic ? schedule(this.drainQueues) : schedule;
  66. }
  67. Async.prototype.disableTrampolineIfNecessary = function() {
  68. if (util.hasDevTools) {
  69. this._trampolineEnabled = false;
  70. }
  71. };
  72. Async.prototype.enableTrampoline = function() {
  73. if (!this._trampolineEnabled) {
  74. this._trampolineEnabled = true;
  75. this._schedule = function(fn) {
  76. setTimeout(fn, 0);
  77. };
  78. }
  79. };
  80. Async.prototype.haveItemsQueued = function () {
  81. return this._normalQueue.length() > 0;
  82. };
  83. Async.prototype.throwLater = function(fn, arg) {
  84. if (arguments.length === 1) {
  85. arg = fn;
  86. fn = function () { throw arg; };
  87. }
  88. var domain = this._getDomain();
  89. if (domain !== undefined) fn = domain.bind(fn);
  90. if (typeof setTimeout !== "undefined") {
  91. setTimeout(function() {
  92. fn(arg);
  93. }, 0);
  94. } else try {
  95. this._schedule(function() {
  96. fn(arg);
  97. });
  98. } catch (e) {
  99. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
  100. }
  101. };
  102. Async.prototype._getDomain = function() {};
  103. if (!true) {
  104. if (util.isNode) {
  105. var EventsModule = _dereq_("events");
  106. var domainGetter = function() {
  107. var domain = process.domain;
  108. if (domain === null) return undefined;
  109. return domain;
  110. };
  111. if (EventsModule.usingDomains) {
  112. Async.prototype._getDomain = domainGetter;
  113. } else {
  114. var descriptor =
  115. Object.getOwnPropertyDescriptor(EventsModule, "usingDomains");
  116. if (descriptor) {
  117. if (!descriptor.configurable) {
  118. process.on("domainsActivated", function() {
  119. Async.prototype._getDomain = domainGetter;
  120. });
  121. } else {
  122. var usingDomains = false;
  123. Object.defineProperty(EventsModule, "usingDomains", {
  124. configurable: false,
  125. enumerable: true,
  126. get: function() {
  127. return usingDomains;
  128. },
  129. set: function(value) {
  130. if (usingDomains || !value) return;
  131. usingDomains = true;
  132. Async.prototype._getDomain = domainGetter;
  133. util.toFastProperties(process);
  134. process.emit("domainsActivated");
  135. }
  136. });
  137. }
  138. }
  139. }
  140. }
  141. }
  142. function AsyncInvokeLater(fn, receiver, arg) {
  143. var domain = this._getDomain();
  144. if (domain !== undefined) fn = domain.bind(fn);
  145. this._lateQueue.push(fn, receiver, arg);
  146. this._queueTick();
  147. }
  148. function AsyncInvoke(fn, receiver, arg) {
  149. var domain = this._getDomain();
  150. if (domain !== undefined) fn = domain.bind(fn);
  151. this._normalQueue.push(fn, receiver, arg);
  152. this._queueTick();
  153. }
  154. function AsyncSettlePromises(promise) {
  155. var domain = this._getDomain();
  156. if (domain !== undefined) {
  157. var fn = domain.bind(promise._settlePromises);
  158. this._normalQueue.push(fn, promise, undefined);
  159. } else {
  160. this._normalQueue._pushOne(promise);
  161. }
  162. this._queueTick();
  163. }
  164. if (!util.hasDevTools) {
  165. Async.prototype.invokeLater = AsyncInvokeLater;
  166. Async.prototype.invoke = AsyncInvoke;
  167. Async.prototype.settlePromises = AsyncSettlePromises;
  168. } else {
  169. Async.prototype.invokeLater = function (fn, receiver, arg) {
  170. if (this._trampolineEnabled) {
  171. AsyncInvokeLater.call(this, fn, receiver, arg);
  172. } else {
  173. setTimeout(function() {
  174. fn.call(receiver, arg);
  175. }, 100);
  176. }
  177. };
  178. Async.prototype.invoke = function (fn, receiver, arg) {
  179. if (this._trampolineEnabled) {
  180. AsyncInvoke.call(this, fn, receiver, arg);
  181. } else {
  182. setTimeout(function() {
  183. fn.call(receiver, arg);
  184. }, 0);
  185. }
  186. };
  187. Async.prototype.settlePromises = function(promise) {
  188. if (this._trampolineEnabled) {
  189. AsyncSettlePromises.call(this, promise);
  190. } else {
  191. setTimeout(function() {
  192. promise._settlePromises();
  193. }, 0);
  194. }
  195. };
  196. }
  197. Async.prototype.invokeFirst = function (fn, receiver, arg) {
  198. var domain = this._getDomain();
  199. if (domain !== undefined) fn = domain.bind(fn);
  200. this._normalQueue.unshift(fn, receiver, arg);
  201. this._queueTick();
  202. };
  203. Async.prototype._drainQueue = function(queue) {
  204. while (queue.length() > 0) {
  205. var fn = queue.shift();
  206. if (typeof fn !== "function") {
  207. fn._settlePromises();
  208. continue;
  209. }
  210. var receiver = queue.shift();
  211. var arg = queue.shift();
  212. fn.call(receiver, arg);
  213. }
  214. };
  215. Async.prototype._drainQueues = function () {
  216. this._drainQueue(this._normalQueue);
  217. this._reset();
  218. this._drainQueue(this._lateQueue);
  219. };
  220. Async.prototype._queueTick = function () {
  221. if (!this._isTickUsed) {
  222. this._isTickUsed = true;
  223. this._schedule(this.drainQueues);
  224. }
  225. };
  226. Async.prototype._reset = function () {
  227. this._isTickUsed = false;
  228. };
  229. module.exports = new Async();
  230. module.exports.firstLineError = firstLineError;
  231. },{"./queue.js":28,"./schedule.js":31,"./util.js":38,"events":39}],3:[function(_dereq_,module,exports){
  232. "use strict";
  233. module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
  234. var rejectThis = function(_, e) {
  235. this._reject(e);
  236. };
  237. var targetRejected = function(e, context) {
  238. context.promiseRejectionQueued = true;
  239. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  240. };
  241. var bindingResolved = function(thisArg, context) {
  242. this._setBoundTo(thisArg);
  243. if (this._isPending()) {
  244. this._resolveCallback(context.target);
  245. }
  246. };
  247. var bindingRejected = function(e, context) {
  248. if (!context.promiseRejectionQueued) this._reject(e);
  249. };
  250. Promise.prototype.bind = function (thisArg) {
  251. var maybePromise = tryConvertToPromise(thisArg);
  252. var ret = new Promise(INTERNAL);
  253. ret._propagateFrom(this, 1);
  254. var target = this._target();
  255. if (maybePromise instanceof Promise) {
  256. var context = {
  257. promiseRejectionQueued: false,
  258. promise: ret,
  259. target: target,
  260. bindingPromise: maybePromise
  261. };
  262. target._then(INTERNAL, targetRejected, ret._progress, ret, context);
  263. maybePromise._then(
  264. bindingResolved, bindingRejected, ret._progress, ret, context);
  265. } else {
  266. ret._setBoundTo(thisArg);
  267. ret._resolveCallback(target);
  268. }
  269. return ret;
  270. };
  271. Promise.prototype._setBoundTo = function (obj) {
  272. if (obj !== undefined) {
  273. this._bitField = this._bitField | 131072;
  274. this._boundTo = obj;
  275. } else {
  276. this._bitField = this._bitField & (~131072);
  277. }
  278. };
  279. Promise.prototype._isBound = function () {
  280. return (this._bitField & 131072) === 131072;
  281. };
  282. Promise.bind = function (thisArg, value) {
  283. var maybePromise = tryConvertToPromise(thisArg);
  284. var ret = new Promise(INTERNAL);
  285. if (maybePromise instanceof Promise) {
  286. maybePromise._then(function(thisArg) {
  287. ret._setBoundTo(thisArg);
  288. ret._resolveCallback(value);
  289. }, ret._reject, ret._progress, ret, null);
  290. } else {
  291. ret._setBoundTo(thisArg);
  292. ret._resolveCallback(value);
  293. }
  294. return ret;
  295. };
  296. };
  297. },{}],4:[function(_dereq_,module,exports){
  298. "use strict";
  299. var old;
  300. if (typeof Promise !== "undefined") old = Promise;
  301. function noConflict() {
  302. try { if (Promise === bluebird) Promise = old; }
  303. catch (e) {}
  304. return bluebird;
  305. }
  306. var bluebird = _dereq_("./promise.js")();
  307. bluebird.noConflict = noConflict;
  308. module.exports = bluebird;
  309. },{"./promise.js":23}],5:[function(_dereq_,module,exports){
  310. "use strict";
  311. var cr = Object.create;
  312. if (cr) {
  313. var callerCache = cr(null);
  314. var getterCache = cr(null);
  315. callerCache[" size"] = getterCache[" size"] = 0;
  316. }
  317. module.exports = function(Promise) {
  318. var util = _dereq_("./util.js");
  319. var canEvaluate = util.canEvaluate;
  320. var isIdentifier = util.isIdentifier;
  321. var getMethodCaller;
  322. var getGetter;
  323. if (!true) {
  324. var makeMethodCaller = function (methodName) {
  325. return new Function("ensureMethod", " \n\
  326. return function(obj) { \n\
  327. 'use strict' \n\
  328. var len = this.length; \n\
  329. ensureMethod(obj, 'methodName'); \n\
  330. switch(len) { \n\
  331. case 1: return obj.methodName(this[0]); \n\
  332. case 2: return obj.methodName(this[0], this[1]); \n\
  333. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  334. case 0: return obj.methodName(); \n\
  335. default: \n\
  336. return obj.methodName.apply(obj, this); \n\
  337. } \n\
  338. }; \n\
  339. ".replace(/methodName/g, methodName))(ensureMethod);
  340. };
  341. var makeGetter = function (propertyName) {
  342. return new Function("obj", " \n\
  343. 'use strict'; \n\
  344. return obj.propertyName; \n\
  345. ".replace("propertyName", propertyName));
  346. };
  347. var getCompiled = function(name, compiler, cache) {
  348. var ret = cache[name];
  349. if (typeof ret !== "function") {
  350. if (!isIdentifier(name)) {
  351. return null;
  352. }
  353. ret = compiler(name);
  354. cache[name] = ret;
  355. cache[" size"]++;
  356. if (cache[" size"] > 512) {
  357. var keys = Object.keys(cache);
  358. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  359. cache[" size"] = keys.length - 256;
  360. }
  361. }
  362. return ret;
  363. };
  364. getMethodCaller = function(name) {
  365. return getCompiled(name, makeMethodCaller, callerCache);
  366. };
  367. getGetter = function(name) {
  368. return getCompiled(name, makeGetter, getterCache);
  369. };
  370. }
  371. function ensureMethod(obj, methodName) {
  372. var fn;
  373. if (obj != null) fn = obj[methodName];
  374. if (typeof fn !== "function") {
  375. var message = "Object " + util.classString(obj) + " has no method '" +
  376. util.toString(methodName) + "'";
  377. throw new Promise.TypeError(message);
  378. }
  379. return fn;
  380. }
  381. function caller(obj) {
  382. var methodName = this.pop();
  383. var fn = ensureMethod(obj, methodName);
  384. return fn.apply(obj, this);
  385. }
  386. Promise.prototype.call = function (methodName) {
  387. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  388. if (!true) {
  389. if (canEvaluate) {
  390. var maybeCaller = getMethodCaller(methodName);
  391. if (maybeCaller !== null) {
  392. return this._then(
  393. maybeCaller, undefined, undefined, args, undefined);
  394. }
  395. }
  396. }
  397. args.push(methodName);
  398. return this._then(caller, undefined, undefined, args, undefined);
  399. };
  400. function namedGetter(obj) {
  401. return obj[this];
  402. }
  403. function indexedGetter(obj) {
  404. var index = +this;
  405. if (index < 0) index = Math.max(0, index + obj.length);
  406. return obj[index];
  407. }
  408. Promise.prototype.get = function (propertyName) {
  409. var isIndex = (typeof propertyName === "number");
  410. var getter;
  411. if (!isIndex) {
  412. if (canEvaluate) {
  413. var maybeGetter = getGetter(propertyName);
  414. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  415. } else {
  416. getter = namedGetter;
  417. }
  418. } else {
  419. getter = indexedGetter;
  420. }
  421. return this._then(getter, undefined, undefined, propertyName, undefined);
  422. };
  423. };
  424. },{"./util.js":38}],6:[function(_dereq_,module,exports){
  425. "use strict";
  426. module.exports = function(Promise) {
  427. var errors = _dereq_("./errors.js");
  428. var async = _dereq_("./async.js");
  429. var CancellationError = errors.CancellationError;
  430. Promise.prototype._cancel = function (reason) {
  431. if (!this.isCancellable()) return this;
  432. var parent;
  433. var promiseToReject = this;
  434. while ((parent = promiseToReject._cancellationParent) !== undefined &&
  435. parent.isCancellable()) {
  436. promiseToReject = parent;
  437. }
  438. this._unsetCancellable();
  439. promiseToReject._target()._rejectCallback(reason, false, true);
  440. };
  441. Promise.prototype.cancel = function (reason) {
  442. if (!this.isCancellable()) return this;
  443. if (reason === undefined) reason = new CancellationError();
  444. async.invokeLater(this._cancel, this, reason);
  445. return this;
  446. };
  447. Promise.prototype.cancellable = function () {
  448. if (this._cancellable()) return this;
  449. async.enableTrampoline();
  450. this._setCancellable();
  451. this._cancellationParent = undefined;
  452. return this;
  453. };
  454. Promise.prototype.uncancellable = function () {
  455. var ret = this.then();
  456. ret._unsetCancellable();
  457. return ret;
  458. };
  459. Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
  460. var ret = this._then(didFulfill, didReject, didProgress,
  461. undefined, undefined);
  462. ret._setCancellable();
  463. ret._cancellationParent = undefined;
  464. return ret;
  465. };
  466. };
  467. },{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
  468. "use strict";
  469. module.exports = function() {
  470. var async = _dereq_("./async.js");
  471. var util = _dereq_("./util.js");
  472. var bluebirdFramePattern =
  473. /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
  474. var stackFramePattern = null;
  475. var formatStack = null;
  476. var indentStackFrames = false;
  477. var warn;
  478. function CapturedTrace(parent) {
  479. this._parent = parent;
  480. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  481. captureStackTrace(this, CapturedTrace);
  482. if (length > 32) this.uncycle();
  483. }
  484. util.inherits(CapturedTrace, Error);
  485. CapturedTrace.prototype.uncycle = function() {
  486. var length = this._length;
  487. if (length < 2) return;
  488. var nodes = [];
  489. var stackToIndex = {};
  490. for (var i = 0, node = this; node !== undefined; ++i) {
  491. nodes.push(node);
  492. node = node._parent;
  493. }
  494. length = this._length = i;
  495. for (var i = length - 1; i >= 0; --i) {
  496. var stack = nodes[i].stack;
  497. if (stackToIndex[stack] === undefined) {
  498. stackToIndex[stack] = i;
  499. }
  500. }
  501. for (var i = 0; i < length; ++i) {
  502. var currentStack = nodes[i].stack;
  503. var index = stackToIndex[currentStack];
  504. if (index !== undefined && index !== i) {
  505. if (index > 0) {
  506. nodes[index - 1]._parent = undefined;
  507. nodes[index - 1]._length = 1;
  508. }
  509. nodes[i]._parent = undefined;
  510. nodes[i]._length = 1;
  511. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  512. if (index < length - 1) {
  513. cycleEdgeNode._parent = nodes[index + 1];
  514. cycleEdgeNode._parent.uncycle();
  515. cycleEdgeNode._length =
  516. cycleEdgeNode._parent._length + 1;
  517. } else {
  518. cycleEdgeNode._parent = undefined;
  519. cycleEdgeNode._length = 1;
  520. }
  521. var currentChildLength = cycleEdgeNode._length + 1;
  522. for (var j = i - 2; j >= 0; --j) {
  523. nodes[j]._length = currentChildLength;
  524. currentChildLength++;
  525. }
  526. return;
  527. }
  528. }
  529. };
  530. CapturedTrace.prototype.parent = function() {
  531. return this._parent;
  532. };
  533. CapturedTrace.prototype.hasParent = function() {
  534. return this._parent !== undefined;
  535. };
  536. CapturedTrace.prototype.attachExtraTrace = function(error) {
  537. if (error.__stackCleaned__) return;
  538. this.uncycle();
  539. var parsed = CapturedTrace.parseStackAndMessage(error);
  540. var message = parsed.message;
  541. var stacks = [parsed.stack];
  542. var trace = this;
  543. while (trace !== undefined) {
  544. stacks.push(cleanStack(trace.stack.split("\n")));
  545. trace = trace._parent;
  546. }
  547. removeCommonRoots(stacks);
  548. removeDuplicateOrEmptyJumps(stacks);
  549. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  550. util.notEnumerableProp(error, "__stackCleaned__", true);
  551. };
  552. function reconstructStack(message, stacks) {
  553. for (var i = 0; i < stacks.length - 1; ++i) {
  554. stacks[i].push("From previous event:");
  555. stacks[i] = stacks[i].join("\n");
  556. }
  557. if (i < stacks.length) {
  558. stacks[i] = stacks[i].join("\n");
  559. }
  560. return message + "\n" + stacks.join("\n");
  561. }
  562. function removeDuplicateOrEmptyJumps(stacks) {
  563. for (var i = 0; i < stacks.length; ++i) {
  564. if (stacks[i].length === 0 ||
  565. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  566. stacks.splice(i, 1);
  567. i--;
  568. }
  569. }
  570. }
  571. function removeCommonRoots(stacks) {
  572. var current = stacks[0];
  573. for (var i = 1; i < stacks.length; ++i) {
  574. var prev = stacks[i];
  575. var currentLastIndex = current.length - 1;
  576. var currentLastLine = current[currentLastIndex];
  577. var commonRootMeetPoint = -1;
  578. for (var j = prev.length - 1; j >= 0; --j) {
  579. if (prev[j] === currentLastLine) {
  580. commonRootMeetPoint = j;
  581. break;
  582. }
  583. }
  584. for (var j = commonRootMeetPoint; j >= 0; --j) {
  585. var line = prev[j];
  586. if (current[currentLastIndex] === line) {
  587. current.pop();
  588. currentLastIndex--;
  589. } else {
  590. break;
  591. }
  592. }
  593. current = prev;
  594. }
  595. }
  596. function cleanStack(stack) {
  597. var ret = [];
  598. for (var i = 0; i < stack.length; ++i) {
  599. var line = stack[i];
  600. var isTraceLine = stackFramePattern.test(line) ||
  601. " (No stack trace)" === line;
  602. var isInternalFrame = isTraceLine && shouldIgnore(line);
  603. if (isTraceLine && !isInternalFrame) {
  604. if (indentStackFrames && line.charAt(0) !== " ") {
  605. line = " " + line;
  606. }
  607. ret.push(line);
  608. }
  609. }
  610. return ret;
  611. }
  612. function stackFramesAsArray(error) {
  613. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  614. for (var i = 0; i < stack.length; ++i) {
  615. var line = stack[i];
  616. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  617. break;
  618. }
  619. }
  620. if (i > 0) {
  621. stack = stack.slice(i);
  622. }
  623. return stack;
  624. }
  625. CapturedTrace.parseStackAndMessage = function(error) {
  626. var stack = error.stack;
  627. var message = error.toString();
  628. stack = typeof stack === "string" && stack.length > 0
  629. ? stackFramesAsArray(error) : [" (No stack trace)"];
  630. return {
  631. message: message,
  632. stack: cleanStack(stack)
  633. };
  634. };
  635. CapturedTrace.formatAndLogError = function(error, title) {
  636. if (typeof console !== "undefined") {
  637. var message;
  638. if (typeof error === "object" || typeof error === "function") {
  639. var stack = error.stack;
  640. message = title + formatStack(stack, error);
  641. } else {
  642. message = title + String(error);
  643. }
  644. if (typeof warn === "function") {
  645. warn(message);
  646. } else if (typeof console.log === "function" ||
  647. typeof console.log === "object") {
  648. console.log(message);
  649. }
  650. }
  651. };
  652. CapturedTrace.unhandledRejection = function (reason) {
  653. CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
  654. };
  655. CapturedTrace.isSupported = function () {
  656. return typeof captureStackTrace === "function";
  657. };
  658. CapturedTrace.fireRejectionEvent =
  659. function(name, localHandler, reason, promise) {
  660. var localEventFired = false;
  661. try {
  662. if (typeof localHandler === "function") {
  663. localEventFired = true;
  664. if (name === "rejectionHandled") {
  665. localHandler(promise);
  666. } else {
  667. localHandler(reason, promise);
  668. }
  669. }
  670. } catch (e) {
  671. async.throwLater(e);
  672. }
  673. var globalEventFired = false;
  674. try {
  675. globalEventFired = fireGlobalEvent(name, reason, promise);
  676. } catch (e) {
  677. globalEventFired = true;
  678. async.throwLater(e);
  679. }
  680. var domEventFired = false;
  681. if (fireDomEvent) {
  682. try {
  683. domEventFired = fireDomEvent(name.toLowerCase(), {
  684. reason: reason,
  685. promise: promise
  686. });
  687. } catch (e) {
  688. domEventFired = true;
  689. async.throwLater(e);
  690. }
  691. }
  692. if (!globalEventFired && !localEventFired && !domEventFired &&
  693. name === "unhandledRejection") {
  694. CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
  695. }
  696. };
  697. function formatNonError(obj) {
  698. var str;
  699. if (typeof obj === "function") {
  700. str = "[function " +
  701. (obj.name || "anonymous") +
  702. "]";
  703. } else {
  704. str = obj.toString();
  705. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  706. if (ruselessToString.test(str)) {
  707. try {
  708. var newStr = JSON.stringify(obj);
  709. str = newStr;
  710. }
  711. catch(e) {
  712. }
  713. }
  714. if (str.length === 0) {
  715. str = "(empty array)";
  716. }
  717. }
  718. return ("(<" + snip(str) + ">, no stack trace)");
  719. }
  720. function snip(str) {
  721. var maxChars = 41;
  722. if (str.length < maxChars) {
  723. return str;
  724. }
  725. return str.substr(0, maxChars - 3) + "...";
  726. }
  727. var shouldIgnore = function() { return false; };
  728. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  729. function parseLineInfo(line) {
  730. var matches = line.match(parseLineInfoRegex);
  731. if (matches) {
  732. return {
  733. fileName: matches[1],
  734. line: parseInt(matches[2], 10)
  735. };
  736. }
  737. }
  738. CapturedTrace.setBounds = function(firstLineError, lastLineError) {
  739. if (!CapturedTrace.isSupported()) return;
  740. var firstStackLines = firstLineError.stack.split("\n");
  741. var lastStackLines = lastLineError.stack.split("\n");
  742. var firstIndex = -1;
  743. var lastIndex = -1;
  744. var firstFileName;
  745. var lastFileName;
  746. for (var i = 0; i < firstStackLines.length; ++i) {
  747. var result = parseLineInfo(firstStackLines[i]);
  748. if (result) {
  749. firstFileName = result.fileName;
  750. firstIndex = result.line;
  751. break;
  752. }
  753. }
  754. for (var i = 0; i < lastStackLines.length; ++i) {
  755. var result = parseLineInfo(lastStackLines[i]);
  756. if (result) {
  757. lastFileName = result.fileName;
  758. lastIndex = result.line;
  759. break;
  760. }
  761. }
  762. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  763. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  764. return;
  765. }
  766. shouldIgnore = function(line) {
  767. if (bluebirdFramePattern.test(line)) return true;
  768. var info = parseLineInfo(line);
  769. if (info) {
  770. if (info.fileName === firstFileName &&
  771. (firstIndex <= info.line && info.line <= lastIndex)) {
  772. return true;
  773. }
  774. }
  775. return false;
  776. };
  777. };
  778. var captureStackTrace = (function stackDetection() {
  779. var v8stackFramePattern = /^\s*at\s*/;
  780. var v8stackFormatter = function(stack, error) {
  781. if (typeof stack === "string") return stack;
  782. if (error.name !== undefined &&
  783. error.message !== undefined) {
  784. return error.toString();
  785. }
  786. return formatNonError(error);
  787. };
  788. if (typeof Error.stackTraceLimit === "number" &&
  789. typeof Error.captureStackTrace === "function") {
  790. Error.stackTraceLimit = Error.stackTraceLimit + 6;
  791. stackFramePattern = v8stackFramePattern;
  792. formatStack = v8stackFormatter;
  793. var captureStackTrace = Error.captureStackTrace;
  794. shouldIgnore = function(line) {
  795. return bluebirdFramePattern.test(line);
  796. };
  797. return function(receiver, ignoreUntil) {
  798. Error.stackTraceLimit = Error.stackTraceLimit + 6;
  799. captureStackTrace(receiver, ignoreUntil);
  800. Error.stackTraceLimit = Error.stackTraceLimit - 6;
  801. };
  802. }
  803. var err = new Error();
  804. if (typeof err.stack === "string" &&
  805. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  806. stackFramePattern = /@/;
  807. formatStack = v8stackFormatter;
  808. indentStackFrames = true;
  809. return function captureStackTrace(o) {
  810. o.stack = new Error().stack;
  811. };
  812. }
  813. var hasStackAfterThrow;
  814. try { throw new Error(); }
  815. catch(e) {
  816. hasStackAfterThrow = ("stack" in e);
  817. }
  818. if (!("stack" in err) && hasStackAfterThrow) {
  819. stackFramePattern = v8stackFramePattern;
  820. formatStack = v8stackFormatter;
  821. return function captureStackTrace(o) {
  822. Error.stackTraceLimit = Error.stackTraceLimit + 6;
  823. try { throw new Error(); }
  824. catch(e) { o.stack = e.stack; }
  825. Error.stackTraceLimit = Error.stackTraceLimit - 6;
  826. };
  827. }
  828. formatStack = function(stack, error) {
  829. if (typeof stack === "string") return stack;
  830. if ((typeof error === "object" ||
  831. typeof error === "function") &&
  832. error.name !== undefined &&
  833. error.message !== undefined) {
  834. return error.toString();
  835. }
  836. return formatNonError(error);
  837. };
  838. return null;
  839. })([]);
  840. var fireDomEvent;
  841. var fireGlobalEvent = (function() {
  842. if (util.isNode) {
  843. return function(name, reason, promise) {
  844. if (name === "rejectionHandled") {
  845. return process.emit(name, promise);
  846. } else {
  847. return process.emit(name, reason, promise);
  848. }
  849. };
  850. } else {
  851. var customEventWorks = false;
  852. var anyEventWorks = true;
  853. try {
  854. var ev = new self.CustomEvent("test");
  855. customEventWorks = ev instanceof CustomEvent;
  856. } catch (e) {}
  857. if (!customEventWorks) {
  858. try {
  859. var event = document.createEvent("CustomEvent");
  860. event.initCustomEvent("testingtheevent", false, true, {});
  861. self.dispatchEvent(event);
  862. } catch (e) {
  863. anyEventWorks = false;
  864. }
  865. }
  866. if (anyEventWorks) {
  867. fireDomEvent = function(type, detail) {
  868. var event;
  869. if (customEventWorks) {
  870. event = new self.CustomEvent(type, {
  871. detail: detail,
  872. bubbles: false,
  873. cancelable: true
  874. });
  875. } else if (self.dispatchEvent) {
  876. event = document.createEvent("CustomEvent");
  877. event.initCustomEvent(type, false, true, detail);
  878. }
  879. return event ? !self.dispatchEvent(event) : false;
  880. };
  881. }
  882. var toWindowMethodNameMap = {};
  883. toWindowMethodNameMap["unhandledRejection"] = ("on" +
  884. "unhandledRejection").toLowerCase();
  885. toWindowMethodNameMap["rejectionHandled"] = ("on" +
  886. "rejectionHandled").toLowerCase();
  887. return function(name, reason, promise) {
  888. var methodName = toWindowMethodNameMap[name];
  889. var method = self[methodName];
  890. if (!method) return false;
  891. if (name === "rejectionHandled") {
  892. method.call(self, promise);
  893. } else {
  894. method.call(self, reason, promise);
  895. }
  896. return true;
  897. };
  898. }
  899. })();
  900. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  901. warn = function (message) {
  902. console.warn(message);
  903. };
  904. if (util.isNode && process.stderr.isTTY) {
  905. warn = function(message) {
  906. process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
  907. };
  908. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  909. warn = function(message) {
  910. console.warn("%c" + message, "color: red");
  911. };
  912. }
  913. }
  914. return CapturedTrace;
  915. };
  916. },{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
  917. "use strict";
  918. module.exports = function(NEXT_FILTER) {
  919. var util = _dereq_("./util.js");
  920. var errors = _dereq_("./errors.js");
  921. var tryCatch = util.tryCatch;
  922. var errorObj = util.errorObj;
  923. var keys = _dereq_("./es5.js").keys;
  924. var TypeError = errors.TypeError;
  925. function CatchFilter(instances, callback, promise) {
  926. this._instances = instances;
  927. this._callback = callback;
  928. this._promise = promise;
  929. }
  930. function safePredicate(predicate, e) {
  931. var safeObject = {};
  932. var retfilter = tryCatch(predicate).call(safeObject, e);
  933. if (retfilter === errorObj) return retfilter;
  934. var safeKeys = keys(safeObject);
  935. if (safeKeys.length) {
  936. errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a");
  937. return errorObj;
  938. }
  939. return retfilter;
  940. }
  941. CatchFilter.prototype.doFilter = function (e) {
  942. var cb = this._callback;
  943. var promise = this._promise;
  944. var boundTo = promise._boundTo;
  945. for (var i = 0, len = this._instances.length; i < len; ++i) {
  946. var item = this._instances[i];
  947. var itemIsErrorType = item === Error ||
  948. (item != null && item.prototype instanceof Error);
  949. if (itemIsErrorType && e instanceof item) {
  950. var ret = tryCatch(cb).call(boundTo, e);
  951. if (ret === errorObj) {
  952. NEXT_FILTER.e = ret.e;
  953. return NEXT_FILTER;
  954. }
  955. return ret;
  956. } else if (typeof item === "function" && !itemIsErrorType) {
  957. var shouldHandle = safePredicate(item, e);
  958. if (shouldHandle === errorObj) {
  959. e = errorObj.e;
  960. break;
  961. } else if (shouldHandle) {
  962. var ret = tryCatch(cb).call(boundTo, e);
  963. if (ret === errorObj) {
  964. NEXT_FILTER.e = ret.e;
  965. return NEXT_FILTER;
  966. }
  967. return ret;
  968. }
  969. }
  970. }
  971. NEXT_FILTER.e = e;
  972. return NEXT_FILTER;
  973. };
  974. return CatchFilter;
  975. };
  976. },{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
  977. "use strict";
  978. module.exports = function(Promise, CapturedTrace, isDebugging) {
  979. var contextStack = [];
  980. function Context() {
  981. this._trace = new CapturedTrace(peekContext());
  982. }
  983. Context.prototype._pushContext = function () {
  984. if (!isDebugging()) return;
  985. if (this._trace !== undefined) {
  986. contextStack.push(this._trace);
  987. }
  988. };
  989. Context.prototype._popContext = function () {
  990. if (!isDebugging()) return;
  991. if (this._trace !== undefined) {
  992. contextStack.pop();
  993. }
  994. };
  995. function createContext() {
  996. if (isDebugging()) return new Context();
  997. }
  998. function peekContext() {
  999. var lastIndex = contextStack.length - 1;
  1000. if (lastIndex >= 0) {
  1001. return contextStack[lastIndex];
  1002. }
  1003. return undefined;
  1004. }
  1005. Promise.prototype._peekContext = peekContext;
  1006. Promise.prototype._pushContext = Context.prototype._pushContext;
  1007. Promise.prototype._popContext = Context.prototype._popContext;
  1008. return createContext;
  1009. };
  1010. },{}],10:[function(_dereq_,module,exports){
  1011. "use strict";
  1012. module.exports = function(Promise, CapturedTrace) {
  1013. var async = _dereq_("./async.js");
  1014. var Warning = _dereq_("./errors.js").Warning;
  1015. var util = _dereq_("./util.js");
  1016. var canAttachTrace = util.canAttachTrace;
  1017. var unhandledRejectionHandled;
  1018. var possiblyUnhandledRejection;
  1019. var debugging = false || (util.isNode &&
  1020. (!!process.env["BLUEBIRD_DEBUG"] ||
  1021. process.env["NODE_ENV"] === "development"));
  1022. if (debugging) {
  1023. async.disableTrampolineIfNecessary();
  1024. }
  1025. Promise.prototype._ensurePossibleRejectionHandled = function () {
  1026. this._setRejectionIsUnhandled();
  1027. async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  1028. };
  1029. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  1030. CapturedTrace.fireRejectionEvent("rejectionHandled",
  1031. unhandledRejectionHandled, undefined, this);
  1032. };
  1033. Promise.prototype._notifyUnhandledRejection = function () {
  1034. if (this._isRejectionUnhandled()) {
  1035. var reason = this._getCarriedStackTrace() || this._settledValue;
  1036. this._setUnhandledRejectionIsNotified();
  1037. CapturedTrace.fireRejectionEvent("unhandledRejection",
  1038. possiblyUnhandledRejection, reason, this);
  1039. }
  1040. };
  1041. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  1042. this._bitField = this._bitField | 524288;
  1043. };
  1044. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  1045. this._bitField = this._bitField & (~524288);
  1046. };
  1047. Promise.prototype._isUnhandledRejectionNotified = function () {
  1048. return (this._bitField & 524288) > 0;
  1049. };
  1050. Promise.prototype._setRejectionIsUnhandled = function () {
  1051. this._bitField = this._bitField | 2097152;
  1052. };
  1053. Promise.prototype._unsetRejectionIsUnhandled = function () {
  1054. this._bitField = this._bitField & (~2097152);
  1055. if (this._isUnhandledRejectionNotified()) {
  1056. this._unsetUnhandledRejectionIsNotified();
  1057. this._notifyUnhandledRejectionIsHandled();
  1058. }
  1059. };
  1060. Promise.prototype._isRejectionUnhandled = function () {
  1061. return (this._bitField & 2097152) > 0;
  1062. };
  1063. Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
  1064. this._bitField = this._bitField | 1048576;
  1065. this._fulfillmentHandler0 = capturedTrace;
  1066. };
  1067. Promise.prototype._isCarryingStackTrace = function () {
  1068. return (this._bitField & 1048576) > 0;
  1069. };
  1070. Promise.prototype._getCarriedStackTrace = function () {
  1071. return this._isCarryingStackTrace()
  1072. ? this._fulfillmentHandler0
  1073. : undefined;
  1074. };
  1075. Promise.prototype._captureStackTrace = function () {
  1076. if (debugging) {
  1077. this._trace = new CapturedTrace(this._peekContext());
  1078. }
  1079. return this;
  1080. };
  1081. Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
  1082. if (debugging && canAttachTrace(error)) {
  1083. var trace = this._trace;
  1084. if (trace !== undefined) {
  1085. if (ignoreSelf) trace = trace._parent;
  1086. }
  1087. if (trace !== undefined) {
  1088. trace.attachExtraTrace(error);
  1089. } else if (!error.__stackCleaned__) {
  1090. var parsed = CapturedTrace.parseStackAndMessage(error);
  1091. util.notEnumerableProp(error, "stack",
  1092. parsed.message + "\n" + parsed.stack.join("\n"));
  1093. util.notEnumerableProp(error, "__stackCleaned__", true);
  1094. }
  1095. }
  1096. };
  1097. Promise.prototype._warn = function(message) {
  1098. var warning = new Warning(message);
  1099. var ctx = this._peekContext();
  1100. if (ctx) {
  1101. ctx.attachExtraTrace(warning);
  1102. } else {
  1103. var parsed = CapturedTrace.parseStackAndMessage(warning);
  1104. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  1105. }
  1106. CapturedTrace.formatAndLogError(warning, "");
  1107. };
  1108. Promise.onPossiblyUnhandledRejection = function (fn) {
  1109. possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined;
  1110. };
  1111. Promise.onUnhandledRejectionHandled = function (fn) {
  1112. unhandledRejectionHandled = typeof fn === "function" ? fn : undefined;
  1113. };
  1114. Promise.longStackTraces = function () {
  1115. if (async.haveItemsQueued() &&
  1116. debugging === false
  1117. ) {
  1118. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a");
  1119. }
  1120. debugging = CapturedTrace.isSupported();
  1121. if (debugging) {
  1122. async.disableTrampolineIfNecessary();
  1123. }
  1124. };
  1125. Promise.hasLongStackTraces = function () {
  1126. return debugging && CapturedTrace.isSupported();
  1127. };
  1128. if (!CapturedTrace.isSupported()) {
  1129. Promise.longStackTraces = function(){};
  1130. debugging = false;
  1131. }
  1132. return function() {
  1133. return debugging;
  1134. };
  1135. };
  1136. },{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
  1137. "use strict";
  1138. var util = _dereq_("./util.js");
  1139. var isPrimitive = util.isPrimitive;
  1140. var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
  1141. module.exports = function(Promise) {
  1142. var returner = function () {
  1143. return this;
  1144. };
  1145. var thrower = function () {
  1146. throw this;
  1147. };
  1148. var returnUndefined = function() {};
  1149. var throwUndefined = function() {
  1150. throw undefined;
  1151. };
  1152. var wrapper = function (value, action) {
  1153. if (action === 1) {
  1154. return function () {
  1155. throw value;
  1156. };
  1157. } else if (action === 2) {
  1158. return function () {
  1159. return value;
  1160. };
  1161. }
  1162. };
  1163. Promise.prototype["return"] =
  1164. Promise.prototype.thenReturn = function (value) {
  1165. if (value === undefined) return this.then(returnUndefined);
  1166. if (wrapsPrimitiveReceiver && isPrimitive(value)) {
  1167. return this._then(
  1168. wrapper(value, 2),
  1169. undefined,
  1170. undefined,
  1171. undefined,
  1172. undefined
  1173. );
  1174. }
  1175. return this._then(returner, undefined, undefined, value, undefined);
  1176. };
  1177. Promise.prototype["throw"] =
  1178. Promise.prototype.thenThrow = function (reason) {
  1179. if (reason === undefined) return this.then(throwUndefined);
  1180. if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
  1181. return this._then(
  1182. wrapper(reason, 1),
  1183. undefined,
  1184. undefined,
  1185. undefined,
  1186. undefined
  1187. );
  1188. }
  1189. return this._then(thrower, undefined, undefined, reason, undefined);
  1190. };
  1191. };
  1192. },{"./util.js":38}],12:[function(_dereq_,module,exports){
  1193. "use strict";
  1194. module.exports = function(Promise, INTERNAL) {
  1195. var PromiseReduce = Promise.reduce;
  1196. Promise.prototype.each = function (fn) {
  1197. return PromiseReduce(this, fn, null, INTERNAL);
  1198. };
  1199. Promise.each = function (promises, fn) {
  1200. return PromiseReduce(promises, fn, null, INTERNAL);
  1201. };
  1202. };
  1203. },{}],13:[function(_dereq_,module,exports){
  1204. "use strict";
  1205. var es5 = _dereq_("./es5.js");
  1206. var Objectfreeze = es5.freeze;
  1207. var util = _dereq_("./util.js");
  1208. var inherits = util.inherits;
  1209. var notEnumerableProp = util.notEnumerableProp;
  1210. function subError(nameProperty, defaultMessage) {
  1211. function SubError(message) {
  1212. if (!(this instanceof SubError)) return new SubError(message);
  1213. notEnumerableProp(this, "message",
  1214. typeof message === "string" ? message : defaultMessage);
  1215. notEnumerableProp(this, "name", nameProperty);
  1216. if (Error.captureStackTrace) {
  1217. Error.captureStackTrace(this, this.constructor);
  1218. } else {
  1219. Error.call(this);
  1220. }
  1221. }
  1222. inherits(SubError, Error);
  1223. return SubError;
  1224. }
  1225. var _TypeError, _RangeError;
  1226. var Warning = subError("Warning", "warning");
  1227. var CancellationError = subError("CancellationError", "cancellation error");
  1228. var TimeoutError = subError("TimeoutError", "timeout error");
  1229. var AggregateError = subError("AggregateError", "aggregate error");
  1230. try {
  1231. _TypeError = TypeError;
  1232. _RangeError = RangeError;
  1233. } catch(e) {
  1234. _TypeError = subError("TypeError", "type error");
  1235. _RangeError = subError("RangeError", "range error");
  1236. }
  1237. var methods = ("join pop push shift unshift slice filter forEach some " +
  1238. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  1239. for (var i = 0; i < methods.length; ++i) {
  1240. if (typeof Array.prototype[methods[i]] === "function") {
  1241. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  1242. }
  1243. }
  1244. es5.defineProperty(AggregateError.prototype, "length", {
  1245. value: 0,
  1246. configurable: false,
  1247. writable: true,
  1248. enumerable: true
  1249. });
  1250. AggregateError.prototype["isOperational"] = true;
  1251. var level = 0;
  1252. AggregateError.prototype.toString = function() {
  1253. var indent = Array(level * 4 + 1).join(" ");
  1254. var ret = "\n" + indent + "AggregateError of:" + "\n";
  1255. level++;
  1256. indent = Array(level * 4 + 1).join(" ");
  1257. for (var i = 0; i < this.length; ++i) {
  1258. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  1259. var lines = str.split("\n");
  1260. for (var j = 0; j < lines.length; ++j) {
  1261. lines[j] = indent + lines[j];
  1262. }
  1263. str = lines.join("\n");
  1264. ret += str + "\n";
  1265. }
  1266. level--;
  1267. return ret;
  1268. };
  1269. function OperationalError(message) {
  1270. if (!(this instanceof OperationalError))
  1271. return new OperationalError(message);
  1272. notEnumerableProp(this, "name", "OperationalError");
  1273. notEnumerableProp(this, "message", message);
  1274. this.cause = message;
  1275. this["isOperational"] = true;
  1276. if (message instanceof Error) {
  1277. notEnumerableProp(this, "message", message.message);
  1278. notEnumerableProp(this, "stack", message.stack);
  1279. } else if (Error.captureStackTrace) {
  1280. Error.captureStackTrace(this, this.constructor);
  1281. }
  1282. }
  1283. inherits(OperationalError, Error);
  1284. var errorTypes = Error["__BluebirdErrorTypes__"];
  1285. if (!errorTypes) {
  1286. errorTypes = Objectfreeze({
  1287. CancellationError: CancellationError,
  1288. TimeoutError: TimeoutError,
  1289. OperationalError: OperationalError,
  1290. RejectionError: OperationalError,
  1291. AggregateError: AggregateError
  1292. });
  1293. notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
  1294. }
  1295. module.exports = {
  1296. Error: Error,
  1297. TypeError: _TypeError,
  1298. RangeError: _RangeError,
  1299. CancellationError: errorTypes.CancellationError,
  1300. OperationalError: errorTypes.OperationalError,
  1301. TimeoutError: errorTypes.TimeoutError,
  1302. AggregateError: errorTypes.AggregateError,
  1303. Warning: Warning
  1304. };
  1305. },{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
  1306. var isES5 = (function(){
  1307. "use strict";
  1308. return this === undefined;
  1309. })();
  1310. if (isES5) {
  1311. module.exports = {
  1312. freeze: Object.freeze,
  1313. defineProperty: Object.defineProperty,
  1314. getDescriptor: Object.getOwnPropertyDescriptor,
  1315. keys: Object.keys,
  1316. names: Object.getOwnPropertyNames,
  1317. getPrototypeOf: Object.getPrototypeOf,
  1318. isArray: Array.isArray,
  1319. isES5: isES5,
  1320. propertyIsWritable: function(obj, prop) {
  1321. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  1322. return !!(!descriptor || descriptor.writable || descriptor.set);
  1323. }
  1324. };
  1325. } else {
  1326. var has = {}.hasOwnProperty;
  1327. var str = {}.toString;
  1328. var proto = {}.constructor.prototype;
  1329. var ObjectKeys = function (o) {
  1330. var ret = [];
  1331. for (var key in o) {
  1332. if (has.call(o, key)) {
  1333. ret.push(key);
  1334. }
  1335. }
  1336. return ret;
  1337. };
  1338. var ObjectGetDescriptor = function(o, key) {
  1339. return {value: o[key]};
  1340. };
  1341. var ObjectDefineProperty = function (o, key, desc) {
  1342. o[key] = desc.value;
  1343. return o;
  1344. };
  1345. var ObjectFreeze = function (obj) {
  1346. return obj;
  1347. };
  1348. var ObjectGetPrototypeOf = function (obj) {
  1349. try {
  1350. return Object(obj).constructor.prototype;
  1351. }
  1352. catch (e) {
  1353. return proto;
  1354. }
  1355. };
  1356. var ArrayIsArray = function (obj) {
  1357. try {
  1358. return str.call(obj) === "[object Array]";
  1359. }
  1360. catch(e) {
  1361. return false;
  1362. }
  1363. };
  1364. module.exports = {
  1365. isArray: ArrayIsArray,
  1366. keys: ObjectKeys,
  1367. names: ObjectKeys,
  1368. defineProperty: ObjectDefineProperty,
  1369. getDescriptor: ObjectGetDescriptor,
  1370. freeze: ObjectFreeze,
  1371. getPrototypeOf: ObjectGetPrototypeOf,
  1372. isES5: isES5,
  1373. propertyIsWritable: function() {
  1374. return true;
  1375. }
  1376. };
  1377. }
  1378. },{}],15:[function(_dereq_,module,exports){
  1379. "use strict";
  1380. module.exports = function(Promise, INTERNAL) {
  1381. var PromiseMap = Promise.map;
  1382. Promise.prototype.filter = function (fn, options) {
  1383. return PromiseMap(this, fn, options, INTERNAL);
  1384. };
  1385. Promise.filter = function (promises, fn, options) {
  1386. return PromiseMap(promises, fn, options, INTERNAL);
  1387. };
  1388. };
  1389. },{}],16:[function(_dereq_,module,exports){
  1390. "use strict";
  1391. module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
  1392. var util = _dereq_("./util.js");
  1393. var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
  1394. var isPrimitive = util.isPrimitive;
  1395. var thrower = util.thrower;
  1396. function returnThis() {
  1397. return this;
  1398. }
  1399. function throwThis() {
  1400. throw this;
  1401. }
  1402. function return$(r) {
  1403. return function() {
  1404. return r;
  1405. };
  1406. }
  1407. function throw$(r) {
  1408. return function() {
  1409. throw r;
  1410. };
  1411. }
  1412. function promisedFinally(ret, reasonOrValue, isFulfilled) {
  1413. var then;
  1414. if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
  1415. then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
  1416. } else {
  1417. then = isFulfilled ? returnThis : throwThis;
  1418. }
  1419. return ret._then(then, thrower, undefined, reasonOrValue, undefined);
  1420. }
  1421. function finallyHandler(reasonOrValue) {
  1422. var promise = this.promise;
  1423. var handler = this.handler;
  1424. var ret = promise._isBound()
  1425. ? handler.call(promise._boundTo)
  1426. : handler();
  1427. if (ret !== undefined) {
  1428. var maybePromise = tryConvertToPromise(ret, promise);
  1429. if (maybePromise instanceof Promise) {
  1430. maybePromise = maybePromise._target();
  1431. return promisedFinally(maybePromise, reasonOrValue,
  1432. promise.isFulfilled());
  1433. }
  1434. }
  1435. if (promise.isRejected()) {
  1436. NEXT_FILTER.e = reasonOrValue;
  1437. return NEXT_FILTER;
  1438. } else {
  1439. return reasonOrValue;
  1440. }
  1441. }
  1442. function tapHandler(value) {
  1443. var promise = this.promise;
  1444. var handler = this.handler;
  1445. var ret = promise._isBound()
  1446. ? handler.call(promise._boundTo, value)
  1447. : handler(value);
  1448. if (ret !== undefined) {
  1449. var maybePromise = tryConvertToPromise(ret, promise);
  1450. if (maybePromise instanceof Promise) {
  1451. maybePromise = maybePromise._target();
  1452. return promisedFinally(maybePromise, value, true);
  1453. }
  1454. }
  1455. return value;
  1456. }
  1457. Promise.prototype._passThroughHandler = function (handler, isFinally) {
  1458. if (typeof handler !== "function") return this.then();
  1459. var promiseAndHandler = {
  1460. promise: this,
  1461. handler: handler
  1462. };
  1463. return this._then(
  1464. isFinally ? finallyHandler : tapHandler,
  1465. isFinally ? finallyHandler : undefined, undefined,
  1466. promiseAndHandler, undefined);
  1467. };
  1468. Promise.prototype.lastly =
  1469. Promise.prototype["finally"] = function (handler) {
  1470. return this._passThroughHandler(handler, true);
  1471. };
  1472. Promise.prototype.tap = function (handler) {
  1473. return this._passThroughHandler(handler, false);
  1474. };
  1475. };
  1476. },{"./util.js":38}],17:[function(_dereq_,module,exports){
  1477. "use strict";
  1478. module.exports = function(Promise,
  1479. apiRejection,
  1480. INTERNAL,
  1481. tryConvertToPromise) {
  1482. var errors = _dereq_("./errors.js");
  1483. var TypeError = errors.TypeError;
  1484. var util = _dereq_("./util.js");
  1485. var errorObj = util.errorObj;
  1486. var tryCatch = util.tryCatch;
  1487. var yieldHandlers = [];
  1488. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  1489. for (var i = 0; i < yieldHandlers.length; ++i) {
  1490. traceParent._pushContext();
  1491. var result = tryCatch(yieldHandlers[i])(value);
  1492. traceParent._popContext();
  1493. if (result === errorObj) {
  1494. traceParent._pushContext();
  1495. var ret = Promise.reject(errorObj.e);
  1496. traceParent._popContext();
  1497. return ret;
  1498. }
  1499. var maybePromise = tryConvertToPromise(result, traceParent);
  1500. if (maybePromise instanceof Promise) return maybePromise;
  1501. }
  1502. return null;
  1503. }
  1504. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  1505. var promise = this._promise = new Promise(INTERNAL);
  1506. promise._captureStackTrace();
  1507. this._stack = stack;
  1508. this._generatorFunction = generatorFunction;
  1509. this._receiver = receiver;
  1510. this._generator = undefined;
  1511. this._yieldHandlers = typeof yieldHandler === "function"
  1512. ? [yieldHandler].concat(yieldHandlers)
  1513. : yieldHandlers;
  1514. }
  1515. PromiseSpawn.prototype.promise = function () {
  1516. return this._promise;
  1517. };
  1518. PromiseSpawn.prototype._run = function () {
  1519. this._generator = this._generatorFunction.call(this._receiver);
  1520. this._receiver =
  1521. this._generatorFunction = undefined;
  1522. this._next(undefined);
  1523. };
  1524. PromiseSpawn.prototype._continue = function (result) {
  1525. if (result === errorObj) {
  1526. return this._promise._rejectCallback(result.e, false, true);
  1527. }
  1528. var value = result.value;
  1529. if (result.done === true) {
  1530. this._promise._resolveCallback(value);
  1531. } else {
  1532. var maybePromise = tryConvertToPromise(value, this._promise);
  1533. if (!(maybePromise instanceof Promise)) {
  1534. maybePromise =
  1535. promiseFromYieldHandler(maybePromise,
  1536. this._yieldHandlers,
  1537. this._promise);
  1538. if (maybePromise === null) {
  1539. this._throw(
  1540. new TypeError(
  1541. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) +
  1542. "From coroutine:\u000a" +
  1543. this._stack.split("\n").slice(1, -7).join("\n")
  1544. )
  1545. );
  1546. return;
  1547. }
  1548. }
  1549. maybePromise._then(
  1550. this._next,
  1551. this._throw,
  1552. undefined,
  1553. this,
  1554. null
  1555. );
  1556. }
  1557. };
  1558. PromiseSpawn.prototype._throw = function (reason) {
  1559. this._promise._attachExtraTrace(reason);
  1560. this._promise._pushContext();
  1561. var result = tryCatch(this._generator["throw"])
  1562. .call(this._generator, reason);
  1563. this._promise._popContext();
  1564. this._continue(result);
  1565. };
  1566. PromiseSpawn.prototype._next = function (value) {
  1567. this._promise._pushContext();
  1568. var result = tryCatch(this._generator.next).call(this._generator, value);
  1569. this._promise._popContext();
  1570. this._continue(result);
  1571. };
  1572. Promise.coroutine = function (generatorFunction, options) {
  1573. if (typeof generatorFunction !== "function") {
  1574. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
  1575. }
  1576. var yieldHandler = Object(options).yieldHandler;
  1577. var PromiseSpawn$ = PromiseSpawn;
  1578. var stack = new Error().stack;
  1579. return function () {
  1580. var generator = generatorFunction.apply(this, arguments);
  1581. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  1582. stack);
  1583. spawn._generator = generator;
  1584. spawn._next(undefined);
  1585. return spawn.promise();
  1586. };
  1587. };
  1588. Promise.coroutine.addYieldHandler = function(fn) {
  1589. if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1590. yieldHandlers.push(fn);
  1591. };
  1592. Promise.spawn = function (generatorFunction) {
  1593. if (typeof generatorFunction !== "function") {
  1594. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
  1595. }
  1596. var spawn = new PromiseSpawn(generatorFunction, this);
  1597. var ret = spawn.promise();
  1598. spawn._run(Promise.spawn);
  1599. return ret;
  1600. };
  1601. };
  1602. },{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
  1603. "use strict";
  1604. module.exports =
  1605. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
  1606. var util = _dereq_("./util.js");
  1607. var canEvaluate = util.canEvaluate;
  1608. var tryCatch = util.tryCatch;
  1609. var errorObj = util.errorObj;
  1610. var reject;
  1611. if (!true) {
  1612. if (canEvaluate) {
  1613. var thenCallback = function(i) {
  1614. return new Function("value", "holder", " \n\
  1615. 'use strict'; \n\
  1616. holder.pIndex = value; \n\
  1617. holder.checkFulfillment(this); \n\
  1618. ".replace(/Index/g, i));
  1619. };
  1620. var caller = function(count) {
  1621. var values = [];
  1622. for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
  1623. return new Function("holder", " \n\
  1624. 'use strict'; \n\
  1625. var callback = holder.fn; \n\
  1626. return callback(values); \n\
  1627. ".replace(/values/g, values.join(", ")));
  1628. };
  1629. var thenCallbacks = [];
  1630. var callers = [undefined];
  1631. for (var i = 1; i <= 5; ++i) {
  1632. thenCallbacks.push(thenCallback(i));
  1633. callers.push(caller(i));
  1634. }
  1635. var Holder = function(total, fn) {
  1636. this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
  1637. this.fn = fn;
  1638. this.total = total;
  1639. this.now = 0;
  1640. };
  1641. Holder.prototype.callers = callers;
  1642. Holder.prototype.checkFulfillment = function(promise) {
  1643. var now = this.now;
  1644. now++;
  1645. var total = this.total;
  1646. if (now >= total) {
  1647. var handler = this.callers[total];
  1648. promise._pushContext();
  1649. var ret = tryCatch(handler)(this);
  1650. promise._popContext();
  1651. if (ret === errorObj) {
  1652. promise._rejectCallback(ret.e, false, true);
  1653. } else {
  1654. promise._resolveCallback(ret);
  1655. }
  1656. } else {
  1657. this.now = now;
  1658. }
  1659. };
  1660. var reject = function (reason) {
  1661. this._reject(reason);
  1662. };
  1663. }
  1664. }
  1665. Promise.join = function () {
  1666. var last = arguments.length - 1;
  1667. var fn;
  1668. if (last > 0 && typeof arguments[last] === "function") {
  1669. fn = arguments[last];
  1670. if (!true) {
  1671. if (last < 6 && canEvaluate) {
  1672. var ret = new Promise(INTERNAL);
  1673. ret._captureStackTrace();
  1674. var holder = new Holder(last, fn);
  1675. var callbacks = thenCallbacks;
  1676. for (var i = 0; i < last; ++i) {
  1677. var maybePromise = tryConvertToPromise(arguments[i], ret);
  1678. if (maybePromise instanceof Promise) {
  1679. maybePromise = maybePromise._target();
  1680. if (maybePromise._isPending()) {
  1681. maybePromise._then(callbacks[i], reject,
  1682. undefined, ret, holder);
  1683. } else if (maybePromise._isFulfilled()) {
  1684. callbacks[i].call(ret,
  1685. maybePromise._value(), holder);
  1686. } else {
  1687. ret._reject(maybePromise._reason());
  1688. }
  1689. } else {
  1690. callbacks[i].call(ret, maybePromise, holder);
  1691. }
  1692. }
  1693. return ret;
  1694. }
  1695. }
  1696. }
  1697. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
  1698. if (fn) args.pop();
  1699. var ret = new PromiseArray(args).promise();
  1700. return fn !== undefined ? ret.spread(fn) : ret;
  1701. };
  1702. };
  1703. },{"./util.js":38}],19:[function(_dereq_,module,exports){
  1704. "use strict";
  1705. module.exports = function(Promise,
  1706. PromiseArray,
  1707. apiRejection,
  1708. tryConvertToPromise,
  1709. INTERNAL) {
  1710. var async = _dereq_("./async.js");
  1711. var util = _dereq_("./util.js");
  1712. var tryCatch = util.tryCatch;
  1713. var errorObj = util.errorObj;
  1714. var PENDING = {};
  1715. var EMPTY_ARRAY = [];
  1716. function MappingPromiseArray(promises, fn, limit, _filter) {
  1717. this.constructor$(promises);
  1718. this._promise._captureStackTrace();
  1719. this._callback = fn;
  1720. this._preservedValues = _filter === INTERNAL
  1721. ? new Array(this.length())
  1722. : null;
  1723. this._limit = limit;
  1724. this._inFlight = 0;
  1725. this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
  1726. async.invoke(init, this, undefined);
  1727. }
  1728. util.inherits(MappingPromiseArray, PromiseArray);
  1729. function init() {this._init$(undefined, -2);}
  1730. MappingPromiseArray.prototype._init = function () {};
  1731. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  1732. var values = this._values;
  1733. var length = this.length();
  1734. var preservedValues = this._preservedValues;
  1735. var limit = this._limit;
  1736. if (values[index] === PENDING) {
  1737. values[index] = value;
  1738. if (limit >= 1) {
  1739. this._inFlight--;
  1740. this._drainQueue();
  1741. if (this._isResolved()) return;
  1742. }
  1743. } else {
  1744. if (limit >= 1 && this._inFlight >= limit) {
  1745. values[index] = value;
  1746. this._queue.push(index);
  1747. return;
  1748. }
  1749. if (preservedValues !== null) preservedValues[index] = value;
  1750. var callback = this._callback;
  1751. var receiver = this._promise._boundTo;
  1752. this._promise._pushContext();
  1753. var ret = tryCatch(callback).call(receiver, value, index, length);
  1754. this._promise._popContext();
  1755. if (ret === errorObj) return this._reject(ret.e);
  1756. var maybePromise = tryConvertToPromise(ret, this._promise);
  1757. if (maybePromise instanceof Promise) {
  1758. maybePromise = maybePromise._target();
  1759. if (maybePromise._isPending()) {
  1760. if (limit >= 1) this._inFlight++;
  1761. values[index] = PENDING;
  1762. return maybePromise._proxyPromiseArray(this, index);
  1763. } else if (maybePromise._isFulfilled()) {
  1764. ret = maybePromise._value();
  1765. } else {
  1766. return this._reject(maybePromise._reason());
  1767. }
  1768. }
  1769. values[index] = ret;
  1770. }
  1771. var totalResolved = ++this._totalResolved;
  1772. if (totalResolved >= length) {
  1773. if (preservedValues !== null) {
  1774. this._filter(values, preservedValues);
  1775. } else {
  1776. this._resolve(values);
  1777. }
  1778. }
  1779. };
  1780. MappingPromiseArray.prototype._drainQueue = function () {
  1781. var queue = this._queue;
  1782. var limit = this._limit;
  1783. var values = this._values;
  1784. while (queue.length > 0 && this._inFlight < limit) {
  1785. if (this._isResolved()) return;
  1786. var index = queue.pop();
  1787. this._promiseFulfilled(values[index], index);
  1788. }
  1789. };
  1790. MappingPromiseArray.prototype._filter = function (booleans, values) {
  1791. var len = values.length;
  1792. var ret = new Array(len);
  1793. var j = 0;
  1794. for (var i = 0; i < len; ++i) {
  1795. if (booleans[i]) ret[j++] = values[i];
  1796. }
  1797. ret.length = j;
  1798. this._resolve(ret);
  1799. };
  1800. MappingPromiseArray.prototype.preservedValues = function () {
  1801. return this._preservedValues;
  1802. };
  1803. function map(promises, fn, options, _filter) {
  1804. var limit = typeof options === "object" && options !== null
  1805. ? options.concurrency
  1806. : 0;
  1807. limit = typeof limit === "number" &&
  1808. isFinite(limit) && limit >= 1 ? limit : 0;
  1809. return new MappingPromiseArray(promises, fn, limit, _filter);
  1810. }
  1811. Promise.prototype.map = function (fn, options) {
  1812. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1813. return map(this, fn, options, null).promise();
  1814. };
  1815. Promise.map = function (promises, fn, options, _filter) {
  1816. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1817. return map(promises, fn, options, _filter).promise();
  1818. };
  1819. };
  1820. },{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
  1821. "use strict";
  1822. module.exports =
  1823. function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  1824. var util = _dereq_("./util.js");
  1825. var tryCatch = util.tryCatch;
  1826. Promise.method = function (fn) {
  1827. if (typeof fn !== "function") {
  1828. throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1829. }
  1830. return function () {
  1831. var ret = new Promise(INTERNAL);
  1832. ret._captureStackTrace();
  1833. ret._pushContext();
  1834. var value = tryCatch(fn).apply(this, arguments);
  1835. ret._popContext();
  1836. ret._resolveFromSyncValue(value);
  1837. return ret;
  1838. };
  1839. };
  1840. Promise.attempt = Promise["try"] = function (fn, args, ctx) {
  1841. if (typeof fn !== "function") {
  1842. return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1843. }
  1844. var ret = new Promise(INTERNAL);
  1845. ret._captureStackTrace();
  1846. ret._pushContext();
  1847. var value = util.isArray(args)
  1848. ? tryCatch(fn).apply(ctx, args)
  1849. : tryCatch(fn).call(ctx, args);
  1850. ret._popContext();
  1851. ret._resolveFromSyncValue(value);
  1852. return ret;
  1853. };
  1854. Promise.prototype._resolveFromSyncValue = function (value) {
  1855. if (value === util.errorObj) {
  1856. this._rejectCallback(value.e, false, true);
  1857. } else {
  1858. this._resolveCallback(value, true);
  1859. }
  1860. };
  1861. };
  1862. },{"./util.js":38}],21:[function(_dereq_,module,exports){
  1863. "use strict";
  1864. module.exports = function(Promise) {
  1865. var util = _dereq_("./util.js");
  1866. var async = _dereq_("./async.js");
  1867. var tryCatch = util.tryCatch;
  1868. var errorObj = util.errorObj;
  1869. function spreadAdapter(val, nodeback) {
  1870. var promise = this;
  1871. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  1872. var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val));
  1873. if (ret === errorObj) {
  1874. async.throwLater(ret.e);
  1875. }
  1876. }
  1877. function successAdapter(val, nodeback) {
  1878. var promise = this;
  1879. var receiver = promise._boundTo;
  1880. var ret = val === undefined
  1881. ? tryCatch(nodeback).call(receiver, null)
  1882. : tryCatch(nodeback).call(receiver, null, val);
  1883. if (ret === errorObj) {
  1884. async.throwLater(ret.e);
  1885. }
  1886. }
  1887. function errorAdapter(reason, nodeback) {
  1888. var promise = this;
  1889. if (!reason) {
  1890. var target = promise._target();
  1891. var newReason = target._getCarriedStackTrace();
  1892. newReason.cause = reason;
  1893. reason = newReason;
  1894. }
  1895. var ret = tryCatch(nodeback).call(promise._boundTo, reason);
  1896. if (ret === errorObj) {
  1897. async.throwLater(ret.e);
  1898. }
  1899. }
  1900. Promise.prototype.asCallback =
  1901. Promise.prototype.nodeify = function (nodeback, options) {
  1902. if (typeof nodeback == "function") {
  1903. var adapter = successAdapter;
  1904. if (options !== undefined && Object(options).spread) {
  1905. adapter = spreadAdapter;
  1906. }
  1907. this._then(
  1908. adapter,
  1909. errorAdapter,
  1910. undefined,
  1911. this,
  1912. nodeback
  1913. );
  1914. }
  1915. return this;
  1916. };
  1917. };
  1918. },{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
  1919. "use strict";
  1920. module.exports = function(Promise, PromiseArray) {
  1921. var util = _dereq_("./util.js");
  1922. var async = _dereq_("./async.js");
  1923. var tryCatch = util.tryCatch;
  1924. var errorObj = util.errorObj;
  1925. Promise.prototype.progressed = function (handler) {
  1926. return this._then(undefined, undefined, handler, undefined, undefined);
  1927. };
  1928. Promise.prototype._progress = function (progressValue) {
  1929. if (this._isFollowingOrFulfilledOrRejected()) return;
  1930. this._target()._progressUnchecked(progressValue);
  1931. };
  1932. Promise.prototype._progressHandlerAt = function (index) {
  1933. return index === 0
  1934. ? this._progressHandler0
  1935. : this[(index << 2) + index - 5 + 2];
  1936. };
  1937. Promise.prototype._doProgressWith = function (progression) {
  1938. var progressValue = progression.value;
  1939. var handler = progression.handler;
  1940. var promise = progression.promise;
  1941. var receiver = progression.receiver;
  1942. var ret = tryCatch(handler).call(receiver, progressValue);
  1943. if (ret === errorObj) {
  1944. if (ret.e != null &&
  1945. ret.e.name !== "StopProgressPropagation") {
  1946. var trace = util.canAttachTrace(ret.e)
  1947. ? ret.e : new Error(util.toString(ret.e));
  1948. promise._attachExtraTrace(trace);
  1949. promise._progress(ret.e);
  1950. }
  1951. } else if (ret instanceof Promise) {
  1952. ret._then(promise._progress, null, null, promise, undefined);
  1953. } else {
  1954. promise._progress(ret);
  1955. }
  1956. };
  1957. Promise.prototype._progressUnchecked = function (progressValue) {
  1958. var len = this._length();
  1959. var progress = this._progress;
  1960. for (var i = 0; i < len; i++) {
  1961. var handler = this._progressHandlerAt(i);
  1962. var promise = this._promiseAt(i);
  1963. if (!(promise instanceof Promise)) {
  1964. var receiver = this._receiverAt(i);
  1965. if (typeof handler === "function") {
  1966. handler.call(receiver, progressValue, promise);
  1967. } else if (receiver instanceof PromiseArray &&
  1968. !receiver._isResolved()) {
  1969. receiver._promiseProgressed(progressValue, promise);
  1970. }
  1971. continue;
  1972. }
  1973. if (typeof handler === "function") {
  1974. async.invoke(this._doProgressWith, this, {
  1975. handler: handler,
  1976. promise: promise,
  1977. receiver: this._receiverAt(i),
  1978. value: progressValue
  1979. });
  1980. } else {
  1981. async.invoke(progress, promise, progressValue);
  1982. }
  1983. }
  1984. };
  1985. };
  1986. },{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
  1987. "use strict";
  1988. module.exports = function() {
  1989. var makeSelfResolutionError = function () {
  1990. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a");
  1991. };
  1992. var reflect = function() {
  1993. return new Promise.PromiseInspection(this._target());
  1994. };
  1995. var apiRejection = function(msg) {
  1996. return Promise.reject(new TypeError(msg));
  1997. };
  1998. var util = _dereq_("./util.js");
  1999. var async = _dereq_("./async.js");
  2000. var errors = _dereq_("./errors.js");
  2001. var TypeError = Promise.TypeError = errors.TypeError;
  2002. Promise.RangeError = errors.RangeError;
  2003. Promise.CancellationError = errors.CancellationError;
  2004. Promise.TimeoutError = errors.TimeoutError;
  2005. Promise.OperationalError = errors.OperationalError;
  2006. Promise.RejectionError = errors.OperationalError;
  2007. Promise.AggregateError = errors.AggregateError;
  2008. var INTERNAL = function(){};
  2009. var APPLY = {};
  2010. var NEXT_FILTER = {e: null};
  2011. var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
  2012. var PromiseArray =
  2013. _dereq_("./promise_array.js")(Promise, INTERNAL,
  2014. tryConvertToPromise, apiRejection);
  2015. var CapturedTrace = _dereq_("./captured_trace.js")();
  2016. var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
  2017. /*jshint unused:false*/
  2018. var createContext =
  2019. _dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
  2020. var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
  2021. var PromiseResolver = _dereq_("./promise_resolver.js");
  2022. var nodebackForPromise = PromiseResolver._nodebackForPromise;
  2023. var errorObj = util.errorObj;
  2024. var tryCatch = util.tryCatch;
  2025. function Promise(resolver) {
  2026. if (typeof resolver !== "function") {
  2027. throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a");
  2028. }
  2029. if (this.constructor !== Promise) {
  2030. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a");
  2031. }
  2032. this._bitField = 0;
  2033. this._fulfillmentHandler0 = undefined;
  2034. this._rejectionHandler0 = undefined;
  2035. this._progressHandler0 = undefined;
  2036. this._promise0 = undefined;
  2037. this._receiver0 = undefined;
  2038. this._settledValue = undefined;
  2039. if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
  2040. }
  2041. Promise.prototype.toString = function () {
  2042. return "[object Promise]";
  2043. };
  2044. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  2045. var len = arguments.length;
  2046. if (len > 1) {
  2047. var catchInstances = new Array(len - 1),
  2048. j = 0, i;
  2049. for (i = 0; i < len - 1; ++i) {
  2050. var item = arguments[i];
  2051. if (typeof item === "function") {
  2052. catchInstances[j++] = item;
  2053. } else {
  2054. return Promise.reject(
  2055. new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"));
  2056. }
  2057. }
  2058. catchInstances.length = j;
  2059. fn = arguments[i];
  2060. var catchFilter = new CatchFilter(catchInstances, fn, this);
  2061. return this._then(undefined, catchFilter.doFilter, undefined,
  2062. catchFilter, undefined);
  2063. }
  2064. return this._then(undefined, fn, undefined, undefined, undefined);
  2065. };
  2066. Promise.prototype.reflect = function () {
  2067. return this._then(reflect, reflect, undefined, this, undefined);
  2068. };
  2069. Promise.prototype.then = function (didFulfill, didReject, didProgress) {
  2070. if (isDebugging() && arguments.length > 0 &&
  2071. typeof didFulfill !== "function" &&
  2072. typeof didReject !== "function") {
  2073. var msg = ".then() only accepts functions but was passed: " +
  2074. util.classString(didFulfill);
  2075. if (arguments.length > 1) {
  2076. msg += ", " + util.classString(didReject);
  2077. }
  2078. this._warn(msg);
  2079. }
  2080. return this._then(didFulfill, didReject, didProgress,
  2081. undefined, undefined);
  2082. };
  2083. Promise.prototype.done = function (didFulfill, didReject, didProgress) {
  2084. var promise = this._then(didFulfill, didReject, didProgress,
  2085. undefined, undefined);
  2086. promise._setIsFinal();
  2087. };
  2088. Promise.prototype.spread = function (didFulfill, didReject) {
  2089. return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
  2090. };
  2091. Promise.prototype.isCancellable = function () {
  2092. return !this.isResolved() &&
  2093. this._cancellable();
  2094. };
  2095. Promise.prototype.toJSON = function () {
  2096. var ret = {
  2097. isFulfilled: false,
  2098. isRejected: false,
  2099. fulfillmentValue: undefined,
  2100. rejectionReason: undefined
  2101. };
  2102. if (this.isFulfilled()) {
  2103. ret.fulfillmentValue = this.value();
  2104. ret.isFulfilled = true;
  2105. } else if (this.isRejected()) {
  2106. ret.rejectionReason = this.reason();
  2107. ret.isRejected = true;
  2108. }
  2109. return ret;
  2110. };
  2111. Promise.prototype.all = function () {
  2112. return new PromiseArray(this).promise();
  2113. };
  2114. Promise.prototype.error = function (fn) {
  2115. return this.caught(util.originatesFromRejection, fn);
  2116. };
  2117. Promise.is = function (val) {
  2118. return val instanceof Promise;
  2119. };
  2120. Promise.fromNode = function(fn) {
  2121. var ret = new Promise(INTERNAL);
  2122. var result = tryCatch(fn)(nodebackForPromise(ret));
  2123. if (result === errorObj) {
  2124. ret._rejectCallback(result.e, true, true);
  2125. }
  2126. return ret;
  2127. };
  2128. Promise.all = function (promises) {
  2129. return new PromiseArray(promises).promise();
  2130. };
  2131. Promise.defer = Promise.pending = function () {
  2132. var promise = new Promise(INTERNAL);
  2133. return new PromiseResolver(promise);
  2134. };
  2135. Promise.cast = function (obj) {
  2136. var ret = tryConvertToPromise(obj);
  2137. if (!(ret instanceof Promise)) {
  2138. var val = ret;
  2139. ret = new Promise(INTERNAL);
  2140. ret._fulfillUnchecked(val);
  2141. }
  2142. return ret;
  2143. };
  2144. Promise.resolve = Promise.fulfilled = Promise.cast;
  2145. Promise.reject = Promise.rejected = function (reason) {
  2146. var ret = new Promise(INTERNAL);
  2147. ret._captureStackTrace();
  2148. ret._rejectCallback(reason, true);
  2149. return ret;
  2150. };
  2151. Promise.setScheduler = function(fn) {
  2152. if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  2153. var prev = async._schedule;
  2154. async._schedule = fn;
  2155. return prev;
  2156. };
  2157. Promise.prototype._then = function (
  2158. didFulfill,
  2159. didReject,
  2160. didProgress,
  2161. receiver,
  2162. internalData
  2163. ) {
  2164. var haveInternalData = internalData !== undefined;
  2165. var ret = haveInternalData ? internalData : new Promise(INTERNAL);
  2166. if (!haveInternalData) {
  2167. ret._propagateFrom(this, 4 | 1);
  2168. ret._captureStackTrace();
  2169. }
  2170. var target = this._target();
  2171. if (target !== this) {
  2172. if (receiver === undefined) receiver = this._boundTo;
  2173. if (!haveInternalData) ret._setIsMigrated();
  2174. }
  2175. var callbackIndex =
  2176. target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver);
  2177. if (target._isResolved() && !target._isSettlePromisesQueued()) {
  2178. async.invoke(
  2179. target._settlePromiseAtPostResolution, target, callbackIndex);
  2180. }
  2181. return ret;
  2182. };
  2183. Promise.prototype._settlePromiseAtPostResolution = function (index) {
  2184. if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
  2185. this._settlePromiseAt(index);
  2186. };
  2187. Promise.prototype._length = function () {
  2188. return this._bitField & 131071;
  2189. };
  2190. Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
  2191. return (this._bitField & 939524096) > 0;
  2192. };
  2193. Promise.prototype._isFollowing = function () {
  2194. return (this._bitField & 536870912) === 536870912;
  2195. };
  2196. Promise.prototype._setLength = function (len) {
  2197. this._bitField = (this._bitField & -131072) |
  2198. (len & 131071);
  2199. };
  2200. Promise.prototype._setFulfilled = function () {
  2201. this._bitField = this._bitField | 268435456;
  2202. };
  2203. Promise.prototype._setRejected = function () {
  2204. this._bitField = this._bitField | 134217728;
  2205. };
  2206. Promise.prototype._setFollowing = function () {
  2207. this._bitField = this._bitField | 536870912;
  2208. };
  2209. Promise.prototype._setIsFinal = function () {
  2210. this._bitField = this._bitField | 33554432;
  2211. };
  2212. Promise.prototype._isFinal = function () {
  2213. return (this._bitField & 33554432) > 0;
  2214. };
  2215. Promise.prototype._cancellable = function () {
  2216. return (this._bitField & 67108864) > 0;
  2217. };
  2218. Promise.prototype._setCancellable = function () {
  2219. this._bitField = this._bitField | 67108864;
  2220. };
  2221. Promise.prototype._unsetCancellable = function () {
  2222. this._bitField = this._bitField & (~67108864);
  2223. };
  2224. Promise.prototype._setIsMigrated = function () {
  2225. this._bitField = this._bitField | 4194304;
  2226. };
  2227. Promise.prototype._unsetIsMigrated = function () {
  2228. this._bitField = this._bitField & (~4194304);
  2229. };
  2230. Promise.prototype._isMigrated = function () {
  2231. return (this._bitField & 4194304) > 0;
  2232. };
  2233. Promise.prototype._receiverAt = function (index) {
  2234. var ret = index === 0
  2235. ? this._receiver0
  2236. : this[
  2237. index * 5 - 5 + 4];
  2238. if (ret === undefined && this._isBound()) {
  2239. return this._boundTo;
  2240. }
  2241. return ret;
  2242. };
  2243. Promise.prototype._promiseAt = function (index) {
  2244. return index === 0
  2245. ? this._promise0
  2246. : this[index * 5 - 5 + 3];
  2247. };
  2248. Promise.prototype._fulfillmentHandlerAt = function (index) {
  2249. return index === 0
  2250. ? this._fulfillmentHandler0
  2251. : this[index * 5 - 5 + 0];
  2252. };
  2253. Promise.prototype._rejectionHandlerAt = function (index) {
  2254. return index === 0
  2255. ? this._rejectionHandler0
  2256. : this[index * 5 - 5 + 1];
  2257. };
  2258. Promise.prototype._migrateCallbacks = function (follower, index) {
  2259. var fulfill = follower._fulfillmentHandlerAt(index);
  2260. var reject = follower._rejectionHandlerAt(index);
  2261. var progress = follower._progressHandlerAt(index);
  2262. var promise = follower._promiseAt(index);
  2263. var receiver = follower._receiverAt(index);
  2264. if (promise instanceof Promise) promise._setIsMigrated();
  2265. this._addCallbacks(fulfill, reject, progress, promise, receiver);
  2266. };
  2267. Promise.prototype._addCallbacks = function (
  2268. fulfill,
  2269. reject,
  2270. progress,
  2271. promise,
  2272. receiver
  2273. ) {
  2274. var index = this._length();
  2275. if (index >= 131071 - 5) {
  2276. index = 0;
  2277. this._setLength(0);
  2278. }
  2279. if (index === 0) {
  2280. this._promise0 = promise;
  2281. if (receiver !== undefined) this._receiver0 = receiver;
  2282. if (typeof fulfill === "function" && !this._isCarryingStackTrace())
  2283. this._fulfillmentHandler0 = fulfill;
  2284. if (typeof reject === "function") this._rejectionHandler0 = reject;
  2285. if (typeof progress === "function") this._progressHandler0 = progress;
  2286. } else {
  2287. var base = index * 5 - 5;
  2288. this[base + 3] = promise;
  2289. this[base + 4] = receiver;
  2290. if (typeof fulfill === "function")
  2291. this[base + 0] = fulfill;
  2292. if (typeof reject === "function")
  2293. this[base + 1] = reject;
  2294. if (typeof progress === "function")
  2295. this[base + 2] = progress;
  2296. }
  2297. this._setLength(index + 1);
  2298. return index;
  2299. };
  2300. Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
  2301. var index = this._length();
  2302. if (index >= 131071 - 5) {
  2303. index = 0;
  2304. this._setLength(0);
  2305. }
  2306. if (index === 0) {
  2307. this._promise0 = promiseSlotValue;
  2308. this._receiver0 = receiver;
  2309. } else {
  2310. var base = index * 5 - 5;
  2311. this[base + 3] = promiseSlotValue;
  2312. this[base + 4] = receiver;
  2313. }
  2314. this._setLength(index + 1);
  2315. };
  2316. Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
  2317. this._setProxyHandlers(promiseArray, index);
  2318. };
  2319. Promise.prototype._resolveCallback = function(value, shouldBind) {
  2320. if (this._isFollowingOrFulfilledOrRejected()) return;
  2321. if (value === this)
  2322. return this._rejectCallback(makeSelfResolutionError(), false, true);
  2323. var maybePromise = tryConvertToPromise(value, this);
  2324. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  2325. var propagationFlags = 1 | (shouldBind ? 4 : 0);
  2326. this._propagateFrom(maybePromise, propagationFlags);
  2327. var promise = maybePromise._target();
  2328. if (promise._isPending()) {
  2329. var len = this._length();
  2330. for (var i = 0; i < len; ++i) {
  2331. promise._migrateCallbacks(this, i);
  2332. }
  2333. this._setFollowing();
  2334. this._setLength(0);
  2335. this._setFollowee(promise);
  2336. } else if (promise._isFulfilled()) {
  2337. this._fulfillUnchecked(promise._value());
  2338. } else {
  2339. this._rejectUnchecked(promise._reason(),
  2340. promise._getCarriedStackTrace());
  2341. }
  2342. };
  2343. Promise.prototype._rejectCallback =
  2344. function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
  2345. if (!shouldNotMarkOriginatingFromRejection) {
  2346. util.markAsOriginatingFromRejection(reason);
  2347. }
  2348. var trace = util.ensureErrorObject(reason);
  2349. var hasStack = trace === reason;
  2350. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  2351. this._reject(reason, hasStack ? undefined : trace);
  2352. };
  2353. Promise.prototype._resolveFromResolver = function (resolver) {
  2354. var promise = this;
  2355. this._captureStackTrace();
  2356. this._pushContext();
  2357. var synchronous = true;
  2358. var r = tryCatch(resolver)(function(value) {
  2359. if (promise === null) return;
  2360. promise._resolveCallback(value);
  2361. promise = null;
  2362. }, function (reason) {
  2363. if (promise === null) return;
  2364. promise._rejectCallback(reason, synchronous);
  2365. promise = null;
  2366. });
  2367. synchronous = false;
  2368. this._popContext();
  2369. if (r !== undefined && r === errorObj && promise !== null) {
  2370. promise._rejectCallback(r.e, true, true);
  2371. promise = null;
  2372. }
  2373. };
  2374. Promise.prototype._settlePromiseFromHandler = function (
  2375. handler, receiver, value, promise
  2376. ) {
  2377. if (promise._isRejected()) return;
  2378. promise._pushContext();
  2379. var x;
  2380. if (receiver === APPLY && !this._isRejected()) {
  2381. x = tryCatch(handler).apply(this._boundTo, value);
  2382. } else {
  2383. x = tryCatch(handler).call(receiver, value);
  2384. }
  2385. promise._popContext();
  2386. if (x === errorObj || x === promise || x === NEXT_FILTER) {
  2387. var err = x === promise ? makeSelfResolutionError() : x.e;
  2388. promise._rejectCallback(err, false, true);
  2389. } else {
  2390. promise._resolveCallback(x);
  2391. }
  2392. };
  2393. Promise.prototype._target = function() {
  2394. var ret = this;
  2395. while (ret._isFollowing()) ret = ret._followee();
  2396. return ret;
  2397. };
  2398. Promise.prototype._followee = function() {
  2399. return this._rejectionHandler0;
  2400. };
  2401. Promise.prototype._setFollowee = function(promise) {
  2402. this._rejectionHandler0 = promise;
  2403. };
  2404. Promise.prototype._cleanValues = function () {
  2405. if (this._cancellable()) {
  2406. this._cancellationParent = undefined;
  2407. }
  2408. };
  2409. Promise.prototype._propagateFrom = function (parent, flags) {
  2410. if ((flags & 1) > 0 && parent._cancellable()) {
  2411. this._setCancellable();
  2412. this._cancellationParent = parent;
  2413. }
  2414. if ((flags & 4) > 0 && parent._isBound()) {
  2415. this._setBoundTo(parent._boundTo);
  2416. }
  2417. };
  2418. Promise.prototype._fulfill = function (value) {
  2419. if (this._isFollowingOrFulfilledOrRejected()) return;
  2420. this._fulfillUnchecked(value);
  2421. };
  2422. Promise.prototype._reject = function (reason, carriedStackTrace) {
  2423. if (this._isFollowingOrFulfilledOrRejected()) return;
  2424. this._rejectUnchecked(reason, carriedStackTrace);
  2425. };
  2426. Promise.prototype._settlePromiseAt = function (index) {
  2427. var promise = this._promiseAt(index);
  2428. var isPromise = promise instanceof Promise;
  2429. if (isPromise && promise._isMigrated()) {
  2430. promise._unsetIsMigrated();
  2431. return async.invoke(this._settlePromiseAt, this, index);
  2432. }
  2433. var handler = this._isFulfilled()
  2434. ? this._fulfillmentHandlerAt(index)
  2435. : this._rejectionHandlerAt(index);
  2436. var carriedStackTrace =
  2437. this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
  2438. var value = this._settledValue;
  2439. var receiver = this._receiverAt(index);
  2440. this._clearCallbackDataAtIndex(index);
  2441. if (typeof handler === "function") {
  2442. if (!isPromise) {
  2443. handler.call(receiver, value, promise);
  2444. } else {
  2445. this._settlePromiseFromHandler(handler, receiver, value, promise);
  2446. }
  2447. } else if (receiver instanceof PromiseArray) {
  2448. if (!receiver._isResolved()) {
  2449. if (this._isFulfilled()) {
  2450. receiver._promiseFulfilled(value, promise);
  2451. }
  2452. else {
  2453. receiver._promiseRejected(value, promise);
  2454. }
  2455. }
  2456. } else if (isPromise) {
  2457. if (this._isFulfilled()) {
  2458. promise._fulfill(value);
  2459. } else {
  2460. promise._reject(value, carriedStackTrace);
  2461. }
  2462. }
  2463. if (index >= 4 && (index & 31) === 4)
  2464. async.invokeLater(this._setLength, this, 0);
  2465. };
  2466. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  2467. if (index === 0) {
  2468. if (!this._isCarryingStackTrace()) {
  2469. this._fulfillmentHandler0 = undefined;
  2470. }
  2471. this._rejectionHandler0 =
  2472. this._progressHandler0 =
  2473. this._receiver0 =
  2474. this._promise0 = undefined;
  2475. } else {
  2476. var base = index * 5 - 5;
  2477. this[base + 3] =
  2478. this[base + 4] =
  2479. this[base + 0] =
  2480. this[base + 1] =
  2481. this[base + 2] = undefined;
  2482. }
  2483. };
  2484. Promise.prototype._isSettlePromisesQueued = function () {
  2485. return (this._bitField &
  2486. -1073741824) === -1073741824;
  2487. };
  2488. Promise.prototype._setSettlePromisesQueued = function () {
  2489. this._bitField = this._bitField | -1073741824;
  2490. };
  2491. Promise.prototype._unsetSettlePromisesQueued = function () {
  2492. this._bitField = this._bitField & (~-1073741824);
  2493. };
  2494. Promise.prototype._queueSettlePromises = function() {
  2495. async.settlePromises(this);
  2496. this._setSettlePromisesQueued();
  2497. };
  2498. Promise.prototype._fulfillUnchecked = function (value) {
  2499. if (value === this) {
  2500. var err = makeSelfResolutionError();
  2501. this._attachExtraTrace(err);
  2502. return this._rejectUnchecked(err, undefined);
  2503. }
  2504. this._setFulfilled();
  2505. this._settledValue = value;
  2506. this._cleanValues();
  2507. if (this._length() > 0) {
  2508. this._queueSettlePromises();
  2509. }
  2510. };
  2511. Promise.prototype._rejectUncheckedCheckError = function (reason) {
  2512. var trace = util.ensureErrorObject(reason);
  2513. this._rejectUnchecked(reason, trace === reason ? undefined : trace);
  2514. };
  2515. Promise.prototype._rejectUnchecked = function (reason, trace) {
  2516. if (reason === this) {
  2517. var err = makeSelfResolutionError();
  2518. this._attachExtraTrace(err);
  2519. return this._rejectUnchecked(err);
  2520. }
  2521. this._setRejected();
  2522. this._settledValue = reason;
  2523. this._cleanValues();
  2524. if (this._isFinal()) {
  2525. async.throwLater(function(e) {
  2526. if ("stack" in e) {
  2527. async.invokeFirst(
  2528. CapturedTrace.unhandledRejection, undefined, e);
  2529. }
  2530. throw e;
  2531. }, trace === undefined ? reason : trace);
  2532. return;
  2533. }
  2534. if (trace !== undefined && trace !== reason) {
  2535. this._setCarriedStackTrace(trace);
  2536. }
  2537. if (this._length() > 0) {
  2538. this._queueSettlePromises();
  2539. } else {
  2540. this._ensurePossibleRejectionHandled();
  2541. }
  2542. };
  2543. Promise.prototype._settlePromises = function () {
  2544. this._unsetSettlePromisesQueued();
  2545. var len = this._length();
  2546. for (var i = 0; i < len; i++) {
  2547. this._settlePromiseAt(i);
  2548. }
  2549. };
  2550. Promise._makeSelfResolutionError = makeSelfResolutionError;
  2551. _dereq_("./progress.js")(Promise, PromiseArray);
  2552. _dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  2553. _dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
  2554. _dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
  2555. _dereq_("./direct_resolve.js")(Promise);
  2556. _dereq_("./synchronous_inspection.js")(Promise);
  2557. _dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
  2558. Promise.Promise = Promise;
  2559. _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
  2560. _dereq_('./cancel.js')(Promise);
  2561. _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
  2562. _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
  2563. _dereq_('./nodeify.js')(Promise);
  2564. _dereq_('./call_get.js')(Promise);
  2565. _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  2566. _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  2567. _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
  2568. _dereq_('./settle.js')(Promise, PromiseArray);
  2569. _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
  2570. _dereq_('./promisify.js')(Promise, INTERNAL);
  2571. _dereq_('./any.js')(Promise);
  2572. _dereq_('./each.js')(Promise, INTERNAL);
  2573. _dereq_('./timers.js')(Promise, INTERNAL);
  2574. _dereq_('./filter.js')(Promise, INTERNAL);
  2575. util.toFastProperties(Promise);
  2576. util.toFastProperties(Promise.prototype);
  2577. function fillTypes(value) {
  2578. var p = new Promise(INTERNAL);
  2579. p._fulfillmentHandler0 = value;
  2580. p._rejectionHandler0 = value;
  2581. p._progressHandler0 = value;
  2582. p._promise0 = value;
  2583. p._receiver0 = value;
  2584. p._settledValue = value;
  2585. }
  2586. // Complete slack tracking, opt out of field-type tracking and
  2587. // stabilize map
  2588. fillTypes({a: 1});
  2589. fillTypes({b: 2});
  2590. fillTypes({c: 3});
  2591. fillTypes(1);
  2592. fillTypes(function(){});
  2593. fillTypes(undefined);
  2594. fillTypes(false);
  2595. fillTypes(new Promise(INTERNAL));
  2596. CapturedTrace.setBounds(async.firstLineError, util.lastLineError);
  2597. return Promise;
  2598. };
  2599. },{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){
  2600. "use strict";
  2601. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  2602. apiRejection) {
  2603. var util = _dereq_("./util.js");
  2604. var isArray = util.isArray;
  2605. function toResolutionValue(val) {
  2606. switch(val) {
  2607. case -2: return [];
  2608. case -3: return {};
  2609. }
  2610. }
  2611. function PromiseArray(values) {
  2612. var promise = this._promise = new Promise(INTERNAL);
  2613. var parent;
  2614. if (values instanceof Promise) {
  2615. parent = values;
  2616. promise._propagateFrom(parent, 1 | 4);
  2617. }
  2618. this._values = values;
  2619. this._length = 0;
  2620. this._totalResolved = 0;
  2621. this._init(undefined, -2);
  2622. }
  2623. PromiseArray.prototype.length = function () {
  2624. return this._length;
  2625. };
  2626. PromiseArray.prototype.promise = function () {
  2627. return this._promise;
  2628. };
  2629. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  2630. var values = tryConvertToPromise(this._values, this._promise);
  2631. if (values instanceof Promise) {
  2632. values = values._target();
  2633. this._values = values;
  2634. if (values._isFulfilled()) {
  2635. values = values._value();
  2636. if (!isArray(values)) {
  2637. var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
  2638. this.__hardReject__(err);
  2639. return;
  2640. }
  2641. } else if (values._isPending()) {
  2642. values._then(
  2643. init,
  2644. this._reject,
  2645. undefined,
  2646. this,
  2647. resolveValueIfEmpty
  2648. );
  2649. return;
  2650. } else {
  2651. this._reject(values._reason());
  2652. return;
  2653. }
  2654. } else if (!isArray(values)) {
  2655. this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason());
  2656. return;
  2657. }
  2658. if (values.length === 0) {
  2659. if (resolveValueIfEmpty === -5) {
  2660. this._resolveEmptyArray();
  2661. }
  2662. else {
  2663. this._resolve(toResolutionValue(resolveValueIfEmpty));
  2664. }
  2665. return;
  2666. }
  2667. var len = this.getActualLength(values.length);
  2668. this._length = len;
  2669. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  2670. var promise = this._promise;
  2671. for (var i = 0; i < len; ++i) {
  2672. var isResolved = this._isResolved();
  2673. var maybePromise = tryConvertToPromise(values[i], promise);
  2674. if (maybePromise instanceof Promise) {
  2675. maybePromise = maybePromise._target();
  2676. if (isResolved) {
  2677. maybePromise._unsetRejectionIsUnhandled();
  2678. } else if (maybePromise._isPending()) {
  2679. maybePromise._proxyPromiseArray(this, i);
  2680. } else if (maybePromise._isFulfilled()) {
  2681. this._promiseFulfilled(maybePromise._value(), i);
  2682. } else {
  2683. this._promiseRejected(maybePromise._reason(), i);
  2684. }
  2685. } else if (!isResolved) {
  2686. this._promiseFulfilled(maybePromise, i);
  2687. }
  2688. }
  2689. };
  2690. PromiseArray.prototype._isResolved = function () {
  2691. return this._values === null;
  2692. };
  2693. PromiseArray.prototype._resolve = function (value) {
  2694. this._values = null;
  2695. this._promise._fulfill(value);
  2696. };
  2697. PromiseArray.prototype.__hardReject__ =
  2698. PromiseArray.prototype._reject = function (reason) {
  2699. this._values = null;
  2700. this._promise._rejectCallback(reason, false, true);
  2701. };
  2702. PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
  2703. this._promise._progress({
  2704. index: index,
  2705. value: progressValue
  2706. });
  2707. };
  2708. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  2709. this._values[index] = value;
  2710. var totalResolved = ++this._totalResolved;
  2711. if (totalResolved >= this._length) {
  2712. this._resolve(this._values);
  2713. }
  2714. };
  2715. PromiseArray.prototype._promiseRejected = function (reason, index) {
  2716. this._totalResolved++;
  2717. this._reject(reason);
  2718. };
  2719. PromiseArray.prototype.shouldCopyValues = function () {
  2720. return true;
  2721. };
  2722. PromiseArray.prototype.getActualLength = function (len) {
  2723. return len;
  2724. };
  2725. return PromiseArray;
  2726. };
  2727. },{"./util.js":38}],25:[function(_dereq_,module,exports){
  2728. "use strict";
  2729. var util = _dereq_("./util.js");
  2730. var maybeWrapAsError = util.maybeWrapAsError;
  2731. var errors = _dereq_("./errors.js");
  2732. var TimeoutError = errors.TimeoutError;
  2733. var OperationalError = errors.OperationalError;
  2734. var haveGetters = util.haveGetters;
  2735. var es5 = _dereq_("./es5.js");
  2736. function isUntypedError(obj) {
  2737. return obj instanceof Error &&
  2738. es5.getPrototypeOf(obj) === Error.prototype;
  2739. }
  2740. var rErrorKey = /^(?:name|message|stack|cause)$/;
  2741. function wrapAsOperationalError(obj) {
  2742. var ret;
  2743. if (isUntypedError(obj)) {
  2744. ret = new OperationalError(obj);
  2745. ret.name = obj.name;
  2746. ret.message = obj.message;
  2747. ret.stack = obj.stack;
  2748. var keys = es5.keys(obj);
  2749. for (var i = 0; i < keys.length; ++i) {
  2750. var key = keys[i];
  2751. if (!rErrorKey.test(key)) {
  2752. ret[key] = obj[key];
  2753. }
  2754. }
  2755. return ret;
  2756. }
  2757. util.markAsOriginatingFromRejection(obj);
  2758. return obj;
  2759. }
  2760. function nodebackForPromise(promise) {
  2761. return function(err, value) {
  2762. if (promise === null) return;
  2763. if (err) {
  2764. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  2765. promise._attachExtraTrace(wrapped);
  2766. promise._reject(wrapped);
  2767. } else if (arguments.length > 2) {
  2768. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  2769. promise._fulfill(args);
  2770. } else {
  2771. promise._fulfill(value);
  2772. }
  2773. promise = null;
  2774. };
  2775. }
  2776. var PromiseResolver;
  2777. if (!haveGetters) {
  2778. PromiseResolver = function (promise) {
  2779. this.promise = promise;
  2780. this.asCallback = nodebackForPromise(promise);
  2781. this.callback = this.asCallback;
  2782. };
  2783. }
  2784. else {
  2785. PromiseResolver = function (promise) {
  2786. this.promise = promise;
  2787. };
  2788. }
  2789. if (haveGetters) {
  2790. var prop = {
  2791. get: function() {
  2792. return nodebackForPromise(this.promise);
  2793. }
  2794. };
  2795. es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
  2796. es5.defineProperty(PromiseResolver.prototype, "callback", prop);
  2797. }
  2798. PromiseResolver._nodebackForPromise = nodebackForPromise;
  2799. PromiseResolver.prototype.toString = function () {
  2800. return "[object PromiseResolver]";
  2801. };
  2802. PromiseResolver.prototype.resolve =
  2803. PromiseResolver.prototype.fulfill = function (value) {
  2804. if (!(this instanceof PromiseResolver)) {
  2805. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
  2806. }
  2807. this.promise._resolveCallback(value);
  2808. };
  2809. PromiseResolver.prototype.reject = function (reason) {
  2810. if (!(this instanceof PromiseResolver)) {
  2811. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
  2812. }
  2813. this.promise._rejectCallback(reason);
  2814. };
  2815. PromiseResolver.prototype.progress = function (value) {
  2816. if (!(this instanceof PromiseResolver)) {
  2817. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
  2818. }
  2819. this.promise._progress(value);
  2820. };
  2821. PromiseResolver.prototype.cancel = function (err) {
  2822. this.promise.cancel(err);
  2823. };
  2824. PromiseResolver.prototype.timeout = function () {
  2825. this.reject(new TimeoutError("timeout"));
  2826. };
  2827. PromiseResolver.prototype.isResolved = function () {
  2828. return this.promise.isResolved();
  2829. };
  2830. PromiseResolver.prototype.toJSON = function () {
  2831. return this.promise.toJSON();
  2832. };
  2833. module.exports = PromiseResolver;
  2834. },{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
  2835. "use strict";
  2836. module.exports = function(Promise, INTERNAL) {
  2837. var THIS = {};
  2838. var util = _dereq_("./util.js");
  2839. var nodebackForPromise = _dereq_("./promise_resolver.js")
  2840. ._nodebackForPromise;
  2841. var withAppended = util.withAppended;
  2842. var maybeWrapAsError = util.maybeWrapAsError;
  2843. var canEvaluate = util.canEvaluate;
  2844. var TypeError = _dereq_("./errors").TypeError;
  2845. var defaultSuffix = "Async";
  2846. var defaultPromisified = {__isPromisified__: true};
  2847. var noCopyPropsPattern =
  2848. /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/;
  2849. var defaultFilter = function(name, func) {
  2850. return util.isIdentifier(name) &&
  2851. name.charAt(0) !== "_" &&
  2852. !util.isClass(func);
  2853. };
  2854. function propsFilter(key) {
  2855. return !noCopyPropsPattern.test(key);
  2856. }
  2857. function isPromisified(fn) {
  2858. try {
  2859. return fn.__isPromisified__ === true;
  2860. }
  2861. catch (e) {
  2862. return false;
  2863. }
  2864. }
  2865. function hasPromisified(obj, key, suffix) {
  2866. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  2867. defaultPromisified);
  2868. return val ? isPromisified(val) : false;
  2869. }
  2870. function checkValid(ret, suffix, suffixRegexp) {
  2871. for (var i = 0; i < ret.length; i += 2) {
  2872. var key = ret[i];
  2873. if (suffixRegexp.test(key)) {
  2874. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  2875. for (var j = 0; j < ret.length; j += 2) {
  2876. if (ret[j] === keyWithoutAsyncSuffix) {
  2877. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a"
  2878. .replace("%s", suffix));
  2879. }
  2880. }
  2881. }
  2882. }
  2883. }
  2884. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  2885. var keys = util.inheritedDataKeys(obj);
  2886. var ret = [];
  2887. for (var i = 0; i < keys.length; ++i) {
  2888. var key = keys[i];
  2889. var value = obj[key];
  2890. var passesDefaultFilter = filter === defaultFilter
  2891. ? true : defaultFilter(key, value, obj);
  2892. if (typeof value === "function" &&
  2893. !isPromisified(value) &&
  2894. !hasPromisified(obj, key, suffix) &&
  2895. filter(key, value, obj, passesDefaultFilter)) {
  2896. ret.push(key, value);
  2897. }
  2898. }
  2899. checkValid(ret, suffix, suffixRegexp);
  2900. return ret;
  2901. }
  2902. var escapeIdentRegex = function(str) {
  2903. return str.replace(/([$])/, "\\$");
  2904. };
  2905. var makeNodePromisifiedEval;
  2906. if (!true) {
  2907. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  2908. var ret = [likelyArgumentCount];
  2909. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  2910. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  2911. ret.push(i);
  2912. }
  2913. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  2914. ret.push(i);
  2915. }
  2916. return ret;
  2917. };
  2918. var argumentSequence = function(argumentCount) {
  2919. return util.filledRange(argumentCount, "_arg", "");
  2920. };
  2921. var parameterDeclaration = function(parameterCount) {
  2922. return util.filledRange(
  2923. Math.max(parameterCount, 3), "_arg", "");
  2924. };
  2925. var parameterCount = function(fn) {
  2926. if (typeof fn.length === "number") {
  2927. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  2928. }
  2929. return 0;
  2930. };
  2931. makeNodePromisifiedEval =
  2932. function(callback, receiver, originalName, fn) {
  2933. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  2934. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  2935. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  2936. function generateCallForArgumentCount(count) {
  2937. var args = argumentSequence(count).join(", ");
  2938. var comma = count > 0 ? ", " : "";
  2939. var ret;
  2940. if (shouldProxyThis) {
  2941. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  2942. } else {
  2943. ret = receiver === undefined
  2944. ? "ret = callback({{args}}, nodeback); break;\n"
  2945. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  2946. }
  2947. return ret.replace("{{args}}", args).replace(", ", comma);
  2948. }
  2949. function generateArgumentSwitchCase() {
  2950. var ret = "";
  2951. for (var i = 0; i < argumentOrder.length; ++i) {
  2952. ret += "case " + argumentOrder[i] +":" +
  2953. generateCallForArgumentCount(argumentOrder[i]);
  2954. }
  2955. ret += " \n\
  2956. default: \n\
  2957. var args = new Array(len + 1); \n\
  2958. var i = 0; \n\
  2959. for (var i = 0; i < len; ++i) { \n\
  2960. args[i] = arguments[i]; \n\
  2961. } \n\
  2962. args[i] = nodeback; \n\
  2963. [CodeForCall] \n\
  2964. break; \n\
  2965. ".replace("[CodeForCall]", (shouldProxyThis
  2966. ? "ret = callback.apply(this, args);\n"
  2967. : "ret = callback.apply(receiver, args);\n"));
  2968. return ret;
  2969. }
  2970. var getFunctionCode = typeof callback === "string"
  2971. ? ("this != null ? this['"+callback+"'] : fn")
  2972. : "fn";
  2973. return new Function("Promise",
  2974. "fn",
  2975. "receiver",
  2976. "withAppended",
  2977. "maybeWrapAsError",
  2978. "nodebackForPromise",
  2979. "tryCatch",
  2980. "errorObj",
  2981. "INTERNAL","'use strict'; \n\
  2982. var ret = function (Parameters) { \n\
  2983. 'use strict'; \n\
  2984. var len = arguments.length; \n\
  2985. var promise = new Promise(INTERNAL); \n\
  2986. promise._captureStackTrace(); \n\
  2987. var nodeback = nodebackForPromise(promise); \n\
  2988. var ret; \n\
  2989. var callback = tryCatch([GetFunctionCode]); \n\
  2990. switch(len) { \n\
  2991. [CodeForSwitchCase] \n\
  2992. } \n\
  2993. if (ret === errorObj) { \n\
  2994. promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
  2995. } \n\
  2996. return promise; \n\
  2997. }; \n\
  2998. ret.__isPromisified__ = true; \n\
  2999. return ret; \n\
  3000. "
  3001. .replace("Parameters", parameterDeclaration(newParameterCount))
  3002. .replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  3003. .replace("[GetFunctionCode]", getFunctionCode))(
  3004. Promise,
  3005. fn,
  3006. receiver,
  3007. withAppended,
  3008. maybeWrapAsError,
  3009. nodebackForPromise,
  3010. util.tryCatch,
  3011. util.errorObj,
  3012. INTERNAL
  3013. );
  3014. };
  3015. }
  3016. function makeNodePromisifiedClosure(callback, receiver, _, fn) {
  3017. var defaultThis = (function() {return this;})();
  3018. var method = callback;
  3019. if (typeof method === "string") {
  3020. callback = fn;
  3021. }
  3022. function promisified() {
  3023. var _receiver = receiver;
  3024. if (receiver === THIS) _receiver = this;
  3025. var promise = new Promise(INTERNAL);
  3026. promise._captureStackTrace();
  3027. var cb = typeof method === "string" && this !== defaultThis
  3028. ? this[method] : callback;
  3029. var fn = nodebackForPromise(promise);
  3030. try {
  3031. cb.apply(_receiver, withAppended(arguments, fn));
  3032. } catch(e) {
  3033. promise._rejectCallback(maybeWrapAsError(e), true, true);
  3034. }
  3035. return promise;
  3036. }
  3037. promisified.__isPromisified__ = true;
  3038. return promisified;
  3039. }
  3040. var makeNodePromisified = canEvaluate
  3041. ? makeNodePromisifiedEval
  3042. : makeNodePromisifiedClosure;
  3043. function promisifyAll(obj, suffix, filter, promisifier) {
  3044. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  3045. var methods =
  3046. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  3047. for (var i = 0, len = methods.length; i < len; i+= 2) {
  3048. var key = methods[i];
  3049. var fn = methods[i+1];
  3050. var promisifiedKey = key + suffix;
  3051. obj[promisifiedKey] = promisifier === makeNodePromisified
  3052. ? makeNodePromisified(key, THIS, key, fn, suffix)
  3053. : promisifier(fn, function() {
  3054. return makeNodePromisified(key, THIS, key, fn, suffix);
  3055. });
  3056. }
  3057. util.toFastProperties(obj);
  3058. return obj;
  3059. }
  3060. function promisify(callback, receiver) {
  3061. return makeNodePromisified(callback, receiver, undefined, callback);
  3062. }
  3063. Promise.promisify = function (fn, receiver) {
  3064. if (typeof fn !== "function") {
  3065. throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  3066. }
  3067. if (isPromisified(fn)) {
  3068. return fn;
  3069. }
  3070. var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
  3071. util.copyDescriptors(fn, ret, propsFilter);
  3072. return ret;
  3073. };
  3074. Promise.promisifyAll = function (target, options) {
  3075. if (typeof target !== "function" && typeof target !== "object") {
  3076. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a");
  3077. }
  3078. options = Object(options);
  3079. var suffix = options.suffix;
  3080. if (typeof suffix !== "string") suffix = defaultSuffix;
  3081. var filter = options.filter;
  3082. if (typeof filter !== "function") filter = defaultFilter;
  3083. var promisifier = options.promisifier;
  3084. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  3085. if (!util.isIdentifier(suffix)) {
  3086. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a");
  3087. }
  3088. var keys = util.inheritedDataKeys(target);
  3089. for (var i = 0; i < keys.length; ++i) {
  3090. var value = target[keys[i]];
  3091. if (keys[i] !== "constructor" &&
  3092. util.isClass(value)) {
  3093. promisifyAll(value.prototype, suffix, filter, promisifier);
  3094. promisifyAll(value, suffix, filter, promisifier);
  3095. }
  3096. }
  3097. return promisifyAll(target, suffix, filter, promisifier);
  3098. };
  3099. };
  3100. },{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
  3101. "use strict";
  3102. module.exports = function(
  3103. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  3104. var util = _dereq_("./util.js");
  3105. var isObject = util.isObject;
  3106. var es5 = _dereq_("./es5.js");
  3107. function PropertiesPromiseArray(obj) {
  3108. var keys = es5.keys(obj);
  3109. var len = keys.length;
  3110. var values = new Array(len * 2);
  3111. for (var i = 0; i < len; ++i) {
  3112. var key = keys[i];
  3113. values[i] = obj[key];
  3114. values[i + len] = key;
  3115. }
  3116. this.constructor$(values);
  3117. }
  3118. util.inherits(PropertiesPromiseArray, PromiseArray);
  3119. PropertiesPromiseArray.prototype._init = function () {
  3120. this._init$(undefined, -3) ;
  3121. };
  3122. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3123. this._values[index] = value;
  3124. var totalResolved = ++this._totalResolved;
  3125. if (totalResolved >= this._length) {
  3126. var val = {};
  3127. var keyOffset = this.length();
  3128. for (var i = 0, len = this.length(); i < len; ++i) {
  3129. val[this._values[i + keyOffset]] = this._values[i];
  3130. }
  3131. this._resolve(val);
  3132. }
  3133. };
  3134. PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
  3135. this._promise._progress({
  3136. key: this._values[index + this.length()],
  3137. value: value
  3138. });
  3139. };
  3140. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  3141. return false;
  3142. };
  3143. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  3144. return len >> 1;
  3145. };
  3146. function props(promises) {
  3147. var ret;
  3148. var castValue = tryConvertToPromise(promises);
  3149. if (!isObject(castValue)) {
  3150. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
  3151. } else if (castValue instanceof Promise) {
  3152. ret = castValue._then(
  3153. Promise.props, undefined, undefined, undefined, undefined);
  3154. } else {
  3155. ret = new PropertiesPromiseArray(castValue).promise();
  3156. }
  3157. if (castValue instanceof Promise) {
  3158. ret._propagateFrom(castValue, 4);
  3159. }
  3160. return ret;
  3161. }
  3162. Promise.prototype.props = function () {
  3163. return props(this);
  3164. };
  3165. Promise.props = function (promises) {
  3166. return props(promises);
  3167. };
  3168. };
  3169. },{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
  3170. "use strict";
  3171. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  3172. for (var j = 0; j < len; ++j) {
  3173. dst[j + dstIndex] = src[j + srcIndex];
  3174. src[j + srcIndex] = void 0;
  3175. }
  3176. }
  3177. function Queue(capacity) {
  3178. this._capacity = capacity;
  3179. this._length = 0;
  3180. this._front = 0;
  3181. }
  3182. Queue.prototype._willBeOverCapacity = function (size) {
  3183. return this._capacity < size;
  3184. };
  3185. Queue.prototype._pushOne = function (arg) {
  3186. var length = this.length();
  3187. this._checkCapacity(length + 1);
  3188. var i = (this._front + length) & (this._capacity - 1);
  3189. this[i] = arg;
  3190. this._length = length + 1;
  3191. };
  3192. Queue.prototype._unshiftOne = function(value) {
  3193. var capacity = this._capacity;
  3194. this._checkCapacity(this.length() + 1);
  3195. var front = this._front;
  3196. var i = (((( front - 1 ) &
  3197. ( capacity - 1) ) ^ capacity ) - capacity );
  3198. this[i] = value;
  3199. this._front = i;
  3200. this._length = this.length() + 1;
  3201. };
  3202. Queue.prototype.unshift = function(fn, receiver, arg) {
  3203. this._unshiftOne(arg);
  3204. this._unshiftOne(receiver);
  3205. this._unshiftOne(fn);
  3206. };
  3207. Queue.prototype.push = function (fn, receiver, arg) {
  3208. var length = this.length() + 3;
  3209. if (this._willBeOverCapacity(length)) {
  3210. this._pushOne(fn);
  3211. this._pushOne(receiver);
  3212. this._pushOne(arg);
  3213. return;
  3214. }
  3215. var j = this._front + length - 3;
  3216. this._checkCapacity(length);
  3217. var wrapMask = this._capacity - 1;
  3218. this[(j + 0) & wrapMask] = fn;
  3219. this[(j + 1) & wrapMask] = receiver;
  3220. this[(j + 2) & wrapMask] = arg;
  3221. this._length = length;
  3222. };
  3223. Queue.prototype.shift = function () {
  3224. var front = this._front,
  3225. ret = this[front];
  3226. this[front] = undefined;
  3227. this._front = (front + 1) & (this._capacity - 1);
  3228. this._length--;
  3229. return ret;
  3230. };
  3231. Queue.prototype.length = function () {
  3232. return this._length;
  3233. };
  3234. Queue.prototype._checkCapacity = function (size) {
  3235. if (this._capacity < size) {
  3236. this._resizeTo(this._capacity << 1);
  3237. }
  3238. };
  3239. Queue.prototype._resizeTo = function (capacity) {
  3240. var oldCapacity = this._capacity;
  3241. this._capacity = capacity;
  3242. var front = this._front;
  3243. var length = this._length;
  3244. var moveItemsCount = (front + length) & (oldCapacity - 1);
  3245. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  3246. };
  3247. module.exports = Queue;
  3248. },{}],29:[function(_dereq_,module,exports){
  3249. "use strict";
  3250. module.exports = function(
  3251. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  3252. var isArray = _dereq_("./util.js").isArray;
  3253. var raceLater = function (promise) {
  3254. return promise.then(function(array) {
  3255. return race(array, promise);
  3256. });
  3257. };
  3258. function race(promises, parent) {
  3259. var maybePromise = tryConvertToPromise(promises);
  3260. if (maybePromise instanceof Promise) {
  3261. return raceLater(maybePromise);
  3262. } else if (!isArray(promises)) {
  3263. return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
  3264. }
  3265. var ret = new Promise(INTERNAL);
  3266. if (parent !== undefined) {
  3267. ret._propagateFrom(parent, 4 | 1);
  3268. }
  3269. var fulfill = ret._fulfill;
  3270. var reject = ret._reject;
  3271. for (var i = 0, len = promises.length; i < len; ++i) {
  3272. var val = promises[i];
  3273. if (val === undefined && !(i in promises)) {
  3274. continue;
  3275. }
  3276. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  3277. }
  3278. return ret;
  3279. }
  3280. Promise.race = function (promises) {
  3281. return race(promises, undefined);
  3282. };
  3283. Promise.prototype.race = function () {
  3284. return race(this, undefined);
  3285. };
  3286. };
  3287. },{"./util.js":38}],30:[function(_dereq_,module,exports){
  3288. "use strict";
  3289. module.exports = function(Promise,
  3290. PromiseArray,
  3291. apiRejection,
  3292. tryConvertToPromise,
  3293. INTERNAL) {
  3294. var async = _dereq_("./async.js");
  3295. var util = _dereq_("./util.js");
  3296. var tryCatch = util.tryCatch;
  3297. var errorObj = util.errorObj;
  3298. function ReductionPromiseArray(promises, fn, accum, _each) {
  3299. this.constructor$(promises);
  3300. this._promise._captureStackTrace();
  3301. this._preservedValues = _each === INTERNAL ? [] : null;
  3302. this._zerothIsAccum = (accum === undefined);
  3303. this._gotAccum = false;
  3304. this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
  3305. this._valuesPhase = undefined;
  3306. var maybePromise = tryConvertToPromise(accum, this._promise);
  3307. var rejected = false;
  3308. var isPromise = maybePromise instanceof Promise;
  3309. if (isPromise) {
  3310. maybePromise = maybePromise._target();
  3311. if (maybePromise._isPending()) {
  3312. maybePromise._proxyPromiseArray(this, -1);
  3313. } else if (maybePromise._isFulfilled()) {
  3314. accum = maybePromise._value();
  3315. this._gotAccum = true;
  3316. } else {
  3317. this._reject(maybePromise._reason());
  3318. rejected = true;
  3319. }
  3320. }
  3321. if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
  3322. this._callback = fn;
  3323. this._accum = accum;
  3324. if (!rejected) async.invoke(init, this, undefined);
  3325. }
  3326. function init() {
  3327. this._init$(undefined, -5);
  3328. }
  3329. util.inherits(ReductionPromiseArray, PromiseArray);
  3330. ReductionPromiseArray.prototype._init = function () {};
  3331. ReductionPromiseArray.prototype._resolveEmptyArray = function () {
  3332. if (this._gotAccum || this._zerothIsAccum) {
  3333. this._resolve(this._preservedValues !== null
  3334. ? [] : this._accum);
  3335. }
  3336. };
  3337. ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3338. var values = this._values;
  3339. values[index] = value;
  3340. var length = this.length();
  3341. var preservedValues = this._preservedValues;
  3342. var isEach = preservedValues !== null;
  3343. var gotAccum = this._gotAccum;
  3344. var valuesPhase = this._valuesPhase;
  3345. var valuesPhaseIndex;
  3346. if (!valuesPhase) {
  3347. valuesPhase = this._valuesPhase = new Array(length);
  3348. for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
  3349. valuesPhase[valuesPhaseIndex] = 0;
  3350. }
  3351. }
  3352. valuesPhaseIndex = valuesPhase[index];
  3353. if (index === 0 && this._zerothIsAccum) {
  3354. this._accum = value;
  3355. this._gotAccum = gotAccum = true;
  3356. valuesPhase[index] = ((valuesPhaseIndex === 0)
  3357. ? 1 : 2);
  3358. } else if (index === -1) {
  3359. this._accum = value;
  3360. this._gotAccum = gotAccum = true;
  3361. } else {
  3362. if (valuesPhaseIndex === 0) {
  3363. valuesPhase[index] = 1;
  3364. } else {
  3365. valuesPhase[index] = 2;
  3366. this._accum = value;
  3367. }
  3368. }
  3369. if (!gotAccum) return;
  3370. var callback = this._callback;
  3371. var receiver = this._promise._boundTo;
  3372. var ret;
  3373. for (var i = this._reducingIndex; i < length; ++i) {
  3374. valuesPhaseIndex = valuesPhase[i];
  3375. if (valuesPhaseIndex === 2) {
  3376. this._reducingIndex = i + 1;
  3377. continue;
  3378. }
  3379. if (valuesPhaseIndex !== 1) return;
  3380. value = values[i];
  3381. this._promise._pushContext();
  3382. if (isEach) {
  3383. preservedValues.push(value);
  3384. ret = tryCatch(callback).call(receiver, value, i, length);
  3385. }
  3386. else {
  3387. ret = tryCatch(callback)
  3388. .call(receiver, this._accum, value, i, length);
  3389. }
  3390. this._promise._popContext();
  3391. if (ret === errorObj) return this._reject(ret.e);
  3392. var maybePromise = tryConvertToPromise(ret, this._promise);
  3393. if (maybePromise instanceof Promise) {
  3394. maybePromise = maybePromise._target();
  3395. if (maybePromise._isPending()) {
  3396. valuesPhase[i] = 4;
  3397. return maybePromise._proxyPromiseArray(this, i);
  3398. } else if (maybePromise._isFulfilled()) {
  3399. ret = maybePromise._value();
  3400. } else {
  3401. return this._reject(maybePromise._reason());
  3402. }
  3403. }
  3404. this._reducingIndex = i + 1;
  3405. this._accum = ret;
  3406. }
  3407. this._resolve(isEach ? preservedValues : this._accum);
  3408. };
  3409. function reduce(promises, fn, initialValue, _each) {
  3410. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  3411. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  3412. return array.promise();
  3413. }
  3414. Promise.prototype.reduce = function (fn, initialValue) {
  3415. return reduce(this, fn, initialValue, null);
  3416. };
  3417. Promise.reduce = function (promises, fn, initialValue, _each) {
  3418. return reduce(promises, fn, initialValue, _each);
  3419. };
  3420. };
  3421. },{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
  3422. "use strict";
  3423. var schedule;
  3424. var noAsyncScheduler = function() {
  3425. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
  3426. };
  3427. if (_dereq_("./util.js").isNode) {
  3428. var version = process.versions.node.split(".").map(Number);
  3429. schedule = (version[0] === 0 && version[1] > 10) || (version[0] > 0)
  3430. ? function(fn) { global.setImmediate(fn); } : process.nextTick;
  3431. if (!schedule) {
  3432. if (typeof setImmediate !== "undefined") {
  3433. schedule = setImmediate;
  3434. } else if (typeof setTimeout !== "undefined") {
  3435. schedule = setTimeout;
  3436. } else {
  3437. schedule = noAsyncScheduler;
  3438. }
  3439. }
  3440. } else if (typeof MutationObserver !== "undefined") {
  3441. schedule = function(fn) {
  3442. var div = document.createElement("div");
  3443. var observer = new MutationObserver(fn);
  3444. observer.observe(div, {attributes: true});
  3445. return function() { div.classList.toggle("foo"); };
  3446. };
  3447. schedule.isStatic = true;
  3448. } else if (typeof setImmediate !== "undefined") {
  3449. schedule = function (fn) {
  3450. setImmediate(fn);
  3451. };
  3452. } else if (typeof setTimeout !== "undefined") {
  3453. schedule = function (fn) {
  3454. setTimeout(fn, 0);
  3455. };
  3456. } else {
  3457. schedule = noAsyncScheduler;
  3458. }
  3459. module.exports = schedule;
  3460. },{"./util.js":38}],32:[function(_dereq_,module,exports){
  3461. "use strict";
  3462. module.exports =
  3463. function(Promise, PromiseArray) {
  3464. var PromiseInspection = Promise.PromiseInspection;
  3465. var util = _dereq_("./util.js");
  3466. function SettledPromiseArray(values) {
  3467. this.constructor$(values);
  3468. }
  3469. util.inherits(SettledPromiseArray, PromiseArray);
  3470. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  3471. this._values[index] = inspection;
  3472. var totalResolved = ++this._totalResolved;
  3473. if (totalResolved >= this._length) {
  3474. this._resolve(this._values);
  3475. }
  3476. };
  3477. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3478. var ret = new PromiseInspection();
  3479. ret._bitField = 268435456;
  3480. ret._settledValue = value;
  3481. this._promiseResolved(index, ret);
  3482. };
  3483. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  3484. var ret = new PromiseInspection();
  3485. ret._bitField = 134217728;
  3486. ret._settledValue = reason;
  3487. this._promiseResolved(index, ret);
  3488. };
  3489. Promise.settle = function (promises) {
  3490. return new SettledPromiseArray(promises).promise();
  3491. };
  3492. Promise.prototype.settle = function () {
  3493. return new SettledPromiseArray(this).promise();
  3494. };
  3495. };
  3496. },{"./util.js":38}],33:[function(_dereq_,module,exports){
  3497. "use strict";
  3498. module.exports =
  3499. function(Promise, PromiseArray, apiRejection) {
  3500. var util = _dereq_("./util.js");
  3501. var RangeError = _dereq_("./errors.js").RangeError;
  3502. var AggregateError = _dereq_("./errors.js").AggregateError;
  3503. var isArray = util.isArray;
  3504. function SomePromiseArray(values) {
  3505. this.constructor$(values);
  3506. this._howMany = 0;
  3507. this._unwrap = false;
  3508. this._initialized = false;
  3509. }
  3510. util.inherits(SomePromiseArray, PromiseArray);
  3511. SomePromiseArray.prototype._init = function () {
  3512. if (!this._initialized) {
  3513. return;
  3514. }
  3515. if (this._howMany === 0) {
  3516. this._resolve([]);
  3517. return;
  3518. }
  3519. this._init$(undefined, -5);
  3520. var isArrayResolved = isArray(this._values);
  3521. if (!this._isResolved() &&
  3522. isArrayResolved &&
  3523. this._howMany > this._canPossiblyFulfill()) {
  3524. this._reject(this._getRangeError(this.length()));
  3525. }
  3526. };
  3527. SomePromiseArray.prototype.init = function () {
  3528. this._initialized = true;
  3529. this._init();
  3530. };
  3531. SomePromiseArray.prototype.setUnwrap = function () {
  3532. this._unwrap = true;
  3533. };
  3534. SomePromiseArray.prototype.howMany = function () {
  3535. return this._howMany;
  3536. };
  3537. SomePromiseArray.prototype.setHowMany = function (count) {
  3538. this._howMany = count;
  3539. };
  3540. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  3541. this._addFulfilled(value);
  3542. if (this._fulfilled() === this.howMany()) {
  3543. this._values.length = this.howMany();
  3544. if (this.howMany() === 1 && this._unwrap) {
  3545. this._resolve(this._values[0]);
  3546. } else {
  3547. this._resolve(this._values);
  3548. }
  3549. }
  3550. };
  3551. SomePromiseArray.prototype._promiseRejected = function (reason) {
  3552. this._addRejected(reason);
  3553. if (this.howMany() > this._canPossiblyFulfill()) {
  3554. var e = new AggregateError();
  3555. for (var i = this.length(); i < this._values.length; ++i) {
  3556. e.push(this._values[i]);
  3557. }
  3558. this._reject(e);
  3559. }
  3560. };
  3561. SomePromiseArray.prototype._fulfilled = function () {
  3562. return this._totalResolved;
  3563. };
  3564. SomePromiseArray.prototype._rejected = function () {
  3565. return this._values.length - this.length();
  3566. };
  3567. SomePromiseArray.prototype._addRejected = function (reason) {
  3568. this._values.push(reason);
  3569. };
  3570. SomePromiseArray.prototype._addFulfilled = function (value) {
  3571. this._values[this._totalResolved++] = value;
  3572. };
  3573. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  3574. return this.length() - this._rejected();
  3575. };
  3576. SomePromiseArray.prototype._getRangeError = function (count) {
  3577. var message = "Input array must contain at least " +
  3578. this._howMany + " items but contains only " + count + " items";
  3579. return new RangeError(message);
  3580. };
  3581. SomePromiseArray.prototype._resolveEmptyArray = function () {
  3582. this._reject(this._getRangeError(0));
  3583. };
  3584. function some(promises, howMany) {
  3585. if ((howMany | 0) !== howMany || howMany < 0) {
  3586. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a");
  3587. }
  3588. var ret = new SomePromiseArray(promises);
  3589. var promise = ret.promise();
  3590. ret.setHowMany(howMany);
  3591. ret.init();
  3592. return promise;
  3593. }
  3594. Promise.some = function (promises, howMany) {
  3595. return some(promises, howMany);
  3596. };
  3597. Promise.prototype.some = function (howMany) {
  3598. return some(this, howMany);
  3599. };
  3600. Promise._SomePromiseArray = SomePromiseArray;
  3601. };
  3602. },{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
  3603. "use strict";
  3604. module.exports = function(Promise) {
  3605. function PromiseInspection(promise) {
  3606. if (promise !== undefined) {
  3607. promise = promise._target();
  3608. this._bitField = promise._bitField;
  3609. this._settledValue = promise._settledValue;
  3610. }
  3611. else {
  3612. this._bitField = 0;
  3613. this._settledValue = undefined;
  3614. }
  3615. }
  3616. PromiseInspection.prototype.value = function () {
  3617. if (!this.isFulfilled()) {
  3618. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
  3619. }
  3620. return this._settledValue;
  3621. };
  3622. PromiseInspection.prototype.error =
  3623. PromiseInspection.prototype.reason = function () {
  3624. if (!this.isRejected()) {
  3625. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
  3626. }
  3627. return this._settledValue;
  3628. };
  3629. PromiseInspection.prototype.isFulfilled =
  3630. Promise.prototype._isFulfilled = function () {
  3631. return (this._bitField & 268435456) > 0;
  3632. };
  3633. PromiseInspection.prototype.isRejected =
  3634. Promise.prototype._isRejected = function () {
  3635. return (this._bitField & 134217728) > 0;
  3636. };
  3637. PromiseInspection.prototype.isPending =
  3638. Promise.prototype._isPending = function () {
  3639. return (this._bitField & 402653184) === 0;
  3640. };
  3641. PromiseInspection.prototype.isResolved =
  3642. Promise.prototype._isResolved = function () {
  3643. return (this._bitField & 402653184) > 0;
  3644. };
  3645. Promise.prototype.isPending = function() {
  3646. return this._target()._isPending();
  3647. };
  3648. Promise.prototype.isRejected = function() {
  3649. return this._target()._isRejected();
  3650. };
  3651. Promise.prototype.isFulfilled = function() {
  3652. return this._target()._isFulfilled();
  3653. };
  3654. Promise.prototype.isResolved = function() {
  3655. return this._target()._isResolved();
  3656. };
  3657. Promise.prototype._value = function() {
  3658. return this._settledValue;
  3659. };
  3660. Promise.prototype._reason = function() {
  3661. this._unsetRejectionIsUnhandled();
  3662. return this._settledValue;
  3663. };
  3664. Promise.prototype.value = function() {
  3665. var target = this._target();
  3666. if (!target.isFulfilled()) {
  3667. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
  3668. }
  3669. return target._settledValue;
  3670. };
  3671. Promise.prototype.reason = function() {
  3672. var target = this._target();
  3673. if (!target.isRejected()) {
  3674. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
  3675. }
  3676. target._unsetRejectionIsUnhandled();
  3677. return target._settledValue;
  3678. };
  3679. Promise.PromiseInspection = PromiseInspection;
  3680. };
  3681. },{}],35:[function(_dereq_,module,exports){
  3682. "use strict";
  3683. module.exports = function(Promise, INTERNAL) {
  3684. var util = _dereq_("./util.js");
  3685. var errorObj = util.errorObj;
  3686. var isObject = util.isObject;
  3687. function tryConvertToPromise(obj, context) {
  3688. if (isObject(obj)) {
  3689. if (obj instanceof Promise) {
  3690. return obj;
  3691. }
  3692. else if (isAnyBluebirdPromise(obj)) {
  3693. var ret = new Promise(INTERNAL);
  3694. obj._then(
  3695. ret._fulfillUnchecked,
  3696. ret._rejectUncheckedCheckError,
  3697. ret._progressUnchecked,
  3698. ret,
  3699. null
  3700. );
  3701. return ret;
  3702. }
  3703. var then = util.tryCatch(getThen)(obj);
  3704. if (then === errorObj) {
  3705. if (context) context._pushContext();
  3706. var ret = Promise.reject(then.e);
  3707. if (context) context._popContext();
  3708. return ret;
  3709. } else if (typeof then === "function") {
  3710. return doThenable(obj, then, context);
  3711. }
  3712. }
  3713. return obj;
  3714. }
  3715. function getThen(obj) {
  3716. return obj.then;
  3717. }
  3718. var hasProp = {}.hasOwnProperty;
  3719. function isAnyBluebirdPromise(obj) {
  3720. return hasProp.call(obj, "_promise0");
  3721. }
  3722. function doThenable(x, then, context) {
  3723. var promise = new Promise(INTERNAL);
  3724. var ret = promise;
  3725. if (context) context._pushContext();
  3726. promise._captureStackTrace();
  3727. if (context) context._popContext();
  3728. var synchronous = true;
  3729. var result = util.tryCatch(then).call(x,
  3730. resolveFromThenable,
  3731. rejectFromThenable,
  3732. progressFromThenable);
  3733. synchronous = false;
  3734. if (promise && result === errorObj) {
  3735. promise._rejectCallback(result.e, true, true);
  3736. promise = null;
  3737. }
  3738. function resolveFromThenable(value) {
  3739. if (!promise) return;
  3740. if (x === value) {
  3741. promise._rejectCallback(
  3742. Promise._makeSelfResolutionError(), false, true);
  3743. } else {
  3744. promise._resolveCallback(value);
  3745. }
  3746. promise = null;
  3747. }
  3748. function rejectFromThenable(reason) {
  3749. if (!promise) return;
  3750. promise._rejectCallback(reason, synchronous, true);
  3751. promise = null;
  3752. }
  3753. function progressFromThenable(value) {
  3754. if (!promise) return;
  3755. if (typeof promise._progress === "function") {
  3756. promise._progress(value);
  3757. }
  3758. }
  3759. return ret;
  3760. }
  3761. return tryConvertToPromise;
  3762. };
  3763. },{"./util.js":38}],36:[function(_dereq_,module,exports){
  3764. "use strict";
  3765. module.exports = function(Promise, INTERNAL) {
  3766. var util = _dereq_("./util.js");
  3767. var TimeoutError = Promise.TimeoutError;
  3768. var afterTimeout = function (promise, message) {
  3769. if (!promise.isPending()) return;
  3770. if (typeof message !== "string") {
  3771. message = "operation timed out";
  3772. }
  3773. var err = new TimeoutError(message);
  3774. util.markAsOriginatingFromRejection(err);
  3775. promise._attachExtraTrace(err);
  3776. promise._cancel(err);
  3777. };
  3778. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  3779. var delay = Promise.delay = function (value, ms) {
  3780. if (ms === undefined) {
  3781. ms = value;
  3782. value = undefined;
  3783. var ret = new Promise(INTERNAL);
  3784. setTimeout(function() { ret._fulfill(); }, ms);
  3785. return ret;
  3786. }
  3787. ms = +ms;
  3788. return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
  3789. };
  3790. Promise.prototype.delay = function (ms) {
  3791. return delay(this, ms);
  3792. };
  3793. function successClear(value) {
  3794. var handle = this;
  3795. if (handle instanceof Number) handle = +handle;
  3796. clearTimeout(handle);
  3797. return value;
  3798. }
  3799. function failureClear(reason) {
  3800. var handle = this;
  3801. if (handle instanceof Number) handle = +handle;
  3802. clearTimeout(handle);
  3803. throw reason;
  3804. }
  3805. Promise.prototype.timeout = function (ms, message) {
  3806. ms = +ms;
  3807. var ret = this.then().cancellable();
  3808. ret._cancellationParent = this;
  3809. var handle = setTimeout(function timeoutTimeout() {
  3810. afterTimeout(ret, message);
  3811. }, ms);
  3812. return ret._then(successClear, failureClear, undefined, handle, undefined);
  3813. };
  3814. };
  3815. },{"./util.js":38}],37:[function(_dereq_,module,exports){
  3816. "use strict";
  3817. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  3818. createContext) {
  3819. var TypeError = _dereq_("./errors.js").TypeError;
  3820. var inherits = _dereq_("./util.js").inherits;
  3821. var PromiseInspection = Promise.PromiseInspection;
  3822. function inspectionMapper(inspections) {
  3823. var len = inspections.length;
  3824. for (var i = 0; i < len; ++i) {
  3825. var inspection = inspections[i];
  3826. if (inspection.isRejected()) {
  3827. return Promise.reject(inspection.error());
  3828. }
  3829. inspections[i] = inspection._settledValue;
  3830. }
  3831. return inspections;
  3832. }
  3833. function thrower(e) {
  3834. setTimeout(function(){throw e;}, 0);
  3835. }
  3836. function castPreservingDisposable(thenable) {
  3837. var maybePromise = tryConvertToPromise(thenable);
  3838. if (maybePromise !== thenable &&
  3839. typeof thenable._isDisposable === "function" &&
  3840. typeof thenable._getDisposer === "function" &&
  3841. thenable._isDisposable()) {
  3842. maybePromise._setDisposable(thenable._getDisposer());
  3843. }
  3844. return maybePromise;
  3845. }
  3846. function dispose(resources, inspection) {
  3847. var i = 0;
  3848. var len = resources.length;
  3849. var ret = Promise.defer();
  3850. function iterator() {
  3851. if (i >= len) return ret.resolve();
  3852. var maybePromise = castPreservingDisposable(resources[i++]);
  3853. if (maybePromise instanceof Promise &&
  3854. maybePromise._isDisposable()) {
  3855. try {
  3856. maybePromise = tryConvertToPromise(
  3857. maybePromise._getDisposer().tryDispose(inspection),
  3858. resources.promise);
  3859. } catch (e) {
  3860. return thrower(e);
  3861. }
  3862. if (maybePromise instanceof Promise) {
  3863. return maybePromise._then(iterator, thrower,
  3864. null, null, null);
  3865. }
  3866. }
  3867. iterator();
  3868. }
  3869. iterator();
  3870. return ret.promise;
  3871. }
  3872. function disposerSuccess(value) {
  3873. var inspection = new PromiseInspection();
  3874. inspection._settledValue = value;
  3875. inspection._bitField = 268435456;
  3876. return dispose(this, inspection).thenReturn(value);
  3877. }
  3878. function disposerFail(reason) {
  3879. var inspection = new PromiseInspection();
  3880. inspection._settledValue = reason;
  3881. inspection._bitField = 134217728;
  3882. return dispose(this, inspection).thenThrow(reason);
  3883. }
  3884. function Disposer(data, promise, context) {
  3885. this._data = data;
  3886. this._promise = promise;
  3887. this._context = context;
  3888. }
  3889. Disposer.prototype.data = function () {
  3890. return this._data;
  3891. };
  3892. Disposer.prototype.promise = function () {
  3893. return this._promise;
  3894. };
  3895. Disposer.prototype.resource = function () {
  3896. if (this.promise().isFulfilled()) {
  3897. return this.promise().value();
  3898. }
  3899. return null;
  3900. };
  3901. Disposer.prototype.tryDispose = function(inspection) {
  3902. var resource = this.resource();
  3903. var context = this._context;
  3904. if (context !== undefined) context._pushContext();
  3905. var ret = resource !== null
  3906. ? this.doDispose(resource, inspection) : null;
  3907. if (context !== undefined) context._popContext();
  3908. this._promise._unsetDisposable();
  3909. this._data = null;
  3910. return ret;
  3911. };
  3912. Disposer.isDisposer = function (d) {
  3913. return (d != null &&
  3914. typeof d.resource === "function" &&
  3915. typeof d.tryDispose === "function");
  3916. };
  3917. function FunctionDisposer(fn, promise, context) {
  3918. this.constructor$(fn, promise, context);
  3919. }
  3920. inherits(FunctionDisposer, Disposer);
  3921. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  3922. var fn = this.data();
  3923. return fn.call(resource, resource, inspection);
  3924. };
  3925. function maybeUnwrapDisposer(value) {
  3926. if (Disposer.isDisposer(value)) {
  3927. this.resources[this.index]._setDisposable(value);
  3928. return value.promise();
  3929. }
  3930. return value;
  3931. }
  3932. Promise.using = function () {
  3933. var len = arguments.length;
  3934. if (len < 2) return apiRejection(
  3935. "you must pass at least 2 arguments to Promise.using");
  3936. var fn = arguments[len - 1];
  3937. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  3938. len--;
  3939. var resources = new Array(len);
  3940. for (var i = 0; i < len; ++i) {
  3941. var resource = arguments[i];
  3942. if (Disposer.isDisposer(resource)) {
  3943. var disposer = resource;
  3944. resource = resource.promise();
  3945. resource._setDisposable(disposer);
  3946. } else {
  3947. var maybePromise = tryConvertToPromise(resource);
  3948. if (maybePromise instanceof Promise) {
  3949. resource =
  3950. maybePromise._then(maybeUnwrapDisposer, null, null, {
  3951. resources: resources,
  3952. index: i
  3953. }, undefined);
  3954. }
  3955. }
  3956. resources[i] = resource;
  3957. }
  3958. var promise = Promise.settle(resources)
  3959. .then(inspectionMapper)
  3960. .then(function(vals) {
  3961. promise._pushContext();
  3962. var ret;
  3963. try {
  3964. ret = fn.apply(undefined, vals);
  3965. } finally {
  3966. promise._popContext();
  3967. }
  3968. return ret;
  3969. })
  3970. ._then(
  3971. disposerSuccess, disposerFail, undefined, resources, undefined);
  3972. resources.promise = promise;
  3973. return promise;
  3974. };
  3975. Promise.prototype._setDisposable = function (disposer) {
  3976. this._bitField = this._bitField | 262144;
  3977. this._disposer = disposer;
  3978. };
  3979. Promise.prototype._isDisposable = function () {
  3980. return (this._bitField & 262144) > 0;
  3981. };
  3982. Promise.prototype._getDisposer = function () {
  3983. return this._disposer;
  3984. };
  3985. Promise.prototype._unsetDisposable = function () {
  3986. this._bitField = this._bitField & (~262144);
  3987. this._disposer = undefined;
  3988. };
  3989. Promise.prototype.disposer = function (fn) {
  3990. if (typeof fn === "function") {
  3991. return new FunctionDisposer(fn, this, createContext());
  3992. }
  3993. throw new TypeError();
  3994. };
  3995. };
  3996. },{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
  3997. "use strict";
  3998. var es5 = _dereq_("./es5.js");
  3999. var canEvaluate = typeof navigator == "undefined";
  4000. var haveGetters = (function(){
  4001. try {
  4002. var o = {};
  4003. es5.defineProperty(o, "f", {
  4004. get: function () {
  4005. return 3;
  4006. }
  4007. });
  4008. return o.f === 3;
  4009. }
  4010. catch (e) {
  4011. return false;
  4012. }
  4013. })();
  4014. var errorObj = {e: {}};
  4015. var tryCatchTarget;
  4016. function tryCatcher() {
  4017. try {
  4018. return tryCatchTarget.apply(this, arguments);
  4019. } catch (e) {
  4020. errorObj.e = e;
  4021. return errorObj;
  4022. }
  4023. }
  4024. function tryCatch(fn) {
  4025. tryCatchTarget = fn;
  4026. return tryCatcher;
  4027. }
  4028. var inherits = function(Child, Parent) {
  4029. var hasProp = {}.hasOwnProperty;
  4030. function T() {
  4031. this.constructor = Child;
  4032. this.constructor$ = Parent;
  4033. for (var propertyName in Parent.prototype) {
  4034. if (hasProp.call(Parent.prototype, propertyName) &&
  4035. propertyName.charAt(propertyName.length-1) !== "$"
  4036. ) {
  4037. this[propertyName + "$"] = Parent.prototype[propertyName];
  4038. }
  4039. }
  4040. }
  4041. T.prototype = Parent.prototype;
  4042. Child.prototype = new T();
  4043. return Child.prototype;
  4044. };
  4045. function isPrimitive(val) {
  4046. return val == null || val === true || val === false ||
  4047. typeof val === "string" || typeof val === "number";
  4048. }
  4049. function isObject(value) {
  4050. return !isPrimitive(value);
  4051. }
  4052. function maybeWrapAsError(maybeError) {
  4053. if (!isPrimitive(maybeError)) return maybeError;
  4054. return new Error(safeToString(maybeError));
  4055. }
  4056. function withAppended(target, appendee) {
  4057. var len = target.length;
  4058. var ret = new Array(len + 1);
  4059. var i;
  4060. for (i = 0; i < len; ++i) {
  4061. ret[i] = target[i];
  4062. }
  4063. ret[i] = appendee;
  4064. return ret;
  4065. }
  4066. function getDataPropertyOrDefault(obj, key, defaultValue) {
  4067. if (es5.isES5) {
  4068. var desc = Object.getOwnPropertyDescriptor(obj, key);
  4069. if (desc != null) {
  4070. return desc.get == null && desc.set == null
  4071. ? desc.value
  4072. : defaultValue;
  4073. }
  4074. } else {
  4075. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  4076. }
  4077. }
  4078. function notEnumerableProp(obj, name, value) {
  4079. if (isPrimitive(obj)) return obj;
  4080. var descriptor = {
  4081. value: value,
  4082. configurable: true,
  4083. enumerable: false,
  4084. writable: true
  4085. };
  4086. es5.defineProperty(obj, name, descriptor);
  4087. return obj;
  4088. }
  4089. var wrapsPrimitiveReceiver = (function() {
  4090. return this !== "string";
  4091. }).call("string");
  4092. function thrower(r) {
  4093. throw r;
  4094. }
  4095. var inheritedDataKeys = (function() {
  4096. if (es5.isES5) {
  4097. var oProto = Object.prototype;
  4098. var getKeys = Object.getOwnPropertyNames;
  4099. return function(obj) {
  4100. var ret = [];
  4101. var visitedKeys = Object.create(null);
  4102. while (obj != null && obj !== oProto) {
  4103. var keys;
  4104. try {
  4105. keys = getKeys(obj);
  4106. } catch (e) {
  4107. return ret;
  4108. }
  4109. for (var i = 0; i < keys.length; ++i) {
  4110. var key = keys[i];
  4111. if (visitedKeys[key]) continue;
  4112. visitedKeys[key] = true;
  4113. var desc = Object.getOwnPropertyDescriptor(obj, key);
  4114. if (desc != null && desc.get == null && desc.set == null) {
  4115. ret.push(key);
  4116. }
  4117. }
  4118. obj = es5.getPrototypeOf(obj);
  4119. }
  4120. return ret;
  4121. };
  4122. } else {
  4123. return function(obj) {
  4124. var ret = [];
  4125. /*jshint forin:false */
  4126. for (var key in obj) {
  4127. ret.push(key);
  4128. }
  4129. return ret;
  4130. };
  4131. }
  4132. })();
  4133. function isClass(fn) {
  4134. try {
  4135. if (typeof fn === "function") {
  4136. var keys = es5.names(fn.prototype);
  4137. if (es5.isES5) return keys.length > 1;
  4138. return keys.length > 0 &&
  4139. !(keys.length === 1 && keys[0] === "constructor");
  4140. }
  4141. return false;
  4142. } catch (e) {
  4143. return false;
  4144. }
  4145. }
  4146. function toFastProperties(obj) {
  4147. /*jshint -W027,-W055,-W031*/
  4148. function f() {}
  4149. f.prototype = obj;
  4150. var l = 8;
  4151. while (l--) new f();
  4152. return obj;
  4153. eval(obj);
  4154. }
  4155. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  4156. function isIdentifier(str) {
  4157. return rident.test(str);
  4158. }
  4159. function filledRange(count, prefix, suffix) {
  4160. var ret = new Array(count);
  4161. for(var i = 0; i < count; ++i) {
  4162. ret[i] = prefix + i + suffix;
  4163. }
  4164. return ret;
  4165. }
  4166. function safeToString(obj) {
  4167. try {
  4168. return obj + "";
  4169. } catch (e) {
  4170. return "[no string representation]";
  4171. }
  4172. }
  4173. function markAsOriginatingFromRejection(e) {
  4174. try {
  4175. notEnumerableProp(e, "isOperational", true);
  4176. }
  4177. catch(ignore) {}
  4178. }
  4179. function originatesFromRejection(e) {
  4180. if (e == null) return false;
  4181. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  4182. e["isOperational"] === true);
  4183. }
  4184. function canAttachTrace(obj) {
  4185. return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
  4186. }
  4187. var ensureErrorObject = (function() {
  4188. if (!("stack" in new Error())) {
  4189. return function(value) {
  4190. if (canAttachTrace(value)) return value;
  4191. try {throw new Error(safeToString(value));}
  4192. catch(err) {return err;}
  4193. };
  4194. } else {
  4195. return function(value) {
  4196. if (canAttachTrace(value)) return value;
  4197. return new Error(safeToString(value));
  4198. };
  4199. }
  4200. })();
  4201. function classString(obj) {
  4202. return {}.toString.call(obj);
  4203. }
  4204. function copyDescriptors(from, to, filter) {
  4205. var keys = es5.names(from);
  4206. for (var i = 0; i < keys.length; ++i) {
  4207. var key = keys[i];
  4208. if (filter(key)) {
  4209. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  4210. }
  4211. }
  4212. }
  4213. var ret = {
  4214. isClass: isClass,
  4215. isIdentifier: isIdentifier,
  4216. inheritedDataKeys: inheritedDataKeys,
  4217. getDataPropertyOrDefault: getDataPropertyOrDefault,
  4218. thrower: thrower,
  4219. isArray: es5.isArray,
  4220. haveGetters: haveGetters,
  4221. notEnumerableProp: notEnumerableProp,
  4222. isPrimitive: isPrimitive,
  4223. isObject: isObject,
  4224. canEvaluate: canEvaluate,
  4225. errorObj: errorObj,
  4226. tryCatch: tryCatch,
  4227. inherits: inherits,
  4228. withAppended: withAppended,
  4229. maybeWrapAsError: maybeWrapAsError,
  4230. wrapsPrimitiveReceiver: wrapsPrimitiveReceiver,
  4231. toFastProperties: toFastProperties,
  4232. filledRange: filledRange,
  4233. toString: safeToString,
  4234. canAttachTrace: canAttachTrace,
  4235. ensureErrorObject: ensureErrorObject,
  4236. originatesFromRejection: originatesFromRejection,
  4237. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  4238. classString: classString,
  4239. copyDescriptors: copyDescriptors,
  4240. hasDevTools: typeof chrome !== "undefined" && chrome &&
  4241. typeof chrome.loadTimes === "function",
  4242. isNode: typeof process !== "undefined" &&
  4243. classString(process).toLowerCase() === "[object process]"
  4244. };
  4245. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  4246. module.exports = ret;
  4247. },{"./es5.js":14}],39:[function(_dereq_,module,exports){
  4248. // Copyright Joyent, Inc. and other Node contributors.
  4249. //
  4250. // Permission is hereby granted, free of charge, to any person obtaining a
  4251. // copy of this software and associated documentation files (the
  4252. // "Software"), to deal in the Software without restriction, including
  4253. // without limitation the rights to use, copy, modify, merge, publish,
  4254. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4255. // persons to whom the Software is furnished to do so, subject to the
  4256. // following conditions:
  4257. //
  4258. // The above copyright notice and this permission notice shall be included
  4259. // in all copies or substantial portions of the Software.
  4260. //
  4261. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4262. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4263. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4264. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4265. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4266. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4267. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4268. function EventEmitter() {
  4269. this._events = this._events || {};
  4270. this._maxListeners = this._maxListeners || undefined;
  4271. }
  4272. module.exports = EventEmitter;
  4273. // Backwards-compat with node 0.10.x
  4274. EventEmitter.EventEmitter = EventEmitter;
  4275. EventEmitter.prototype._events = undefined;
  4276. EventEmitter.prototype._maxListeners = undefined;
  4277. // By default EventEmitters will print a warning if more than 10 listeners are
  4278. // added to it. This is a useful default which helps finding memory leaks.
  4279. EventEmitter.defaultMaxListeners = 10;
  4280. // Obviously not all Emitters should be limited to 10. This function allows
  4281. // that to be increased. Set to zero for unlimited.
  4282. EventEmitter.prototype.setMaxListeners = function(n) {
  4283. if (!isNumber(n) || n < 0 || isNaN(n))
  4284. throw TypeError('n must be a positive number');
  4285. this._maxListeners = n;
  4286. return this;
  4287. };
  4288. EventEmitter.prototype.emit = function(type) {
  4289. var er, handler, len, args, i, listeners;
  4290. if (!this._events)
  4291. this._events = {};
  4292. // If there is no 'error' event listener then throw.
  4293. if (type === 'error') {
  4294. if (!this._events.error ||
  4295. (isObject(this._events.error) && !this._events.error.length)) {
  4296. er = arguments[1];
  4297. if (er instanceof Error) {
  4298. throw er; // Unhandled 'error' event
  4299. }
  4300. throw TypeError('Uncaught, unspecified "error" event.');
  4301. }
  4302. }
  4303. handler = this._events[type];
  4304. if (isUndefined(handler))
  4305. return false;
  4306. if (isFunction(handler)) {
  4307. switch (arguments.length) {
  4308. // fast cases
  4309. case 1:
  4310. handler.call(this);
  4311. break;
  4312. case 2:
  4313. handler.call(this, arguments[1]);
  4314. break;
  4315. case 3:
  4316. handler.call(this, arguments[1], arguments[2]);
  4317. break;
  4318. // slower
  4319. default:
  4320. len = arguments.length;
  4321. args = new Array(len - 1);
  4322. for (i = 1; i < len; i++)
  4323. args[i - 1] = arguments[i];
  4324. handler.apply(this, args);
  4325. }
  4326. } else if (isObject(handler)) {
  4327. len = arguments.length;
  4328. args = new Array(len - 1);
  4329. for (i = 1; i < len; i++)
  4330. args[i - 1] = arguments[i];
  4331. listeners = handler.slice();
  4332. len = listeners.length;
  4333. for (i = 0; i < len; i++)
  4334. listeners[i].apply(this, args);
  4335. }
  4336. return true;
  4337. };
  4338. EventEmitter.prototype.addListener = function(type, listener) {
  4339. var m;
  4340. if (!isFunction(listener))
  4341. throw TypeError('listener must be a function');
  4342. if (!this._events)
  4343. this._events = {};
  4344. // To avoid recursion in the case that type === "newListener"! Before
  4345. // adding it to the listeners, first emit "newListener".
  4346. if (this._events.newListener)
  4347. this.emit('newListener', type,
  4348. isFunction(listener.listener) ?
  4349. listener.listener : listener);
  4350. if (!this._events[type])
  4351. // Optimize the case of one listener. Don't need the extra array object.
  4352. this._events[type] = listener;
  4353. else if (isObject(this._events[type]))
  4354. // If we've already got an array, just append.
  4355. this._events[type].push(listener);
  4356. else
  4357. // Adding the second element, need to change to array.
  4358. this._events[type] = [this._events[type], listener];
  4359. // Check for listener leak
  4360. if (isObject(this._events[type]) && !this._events[type].warned) {
  4361. var m;
  4362. if (!isUndefined(this._maxListeners)) {
  4363. m = this._maxListeners;
  4364. } else {
  4365. m = EventEmitter.defaultMaxListeners;
  4366. }
  4367. if (m && m > 0 && this._events[type].length > m) {
  4368. this._events[type].warned = true;
  4369. console.error('(node) warning: possible EventEmitter memory ' +
  4370. 'leak detected. %d listeners added. ' +
  4371. 'Use emitter.setMaxListeners() to increase limit.',
  4372. this._events[type].length);
  4373. if (typeof console.trace === 'function') {
  4374. // not supported in IE 10
  4375. console.trace();
  4376. }
  4377. }
  4378. }
  4379. return this;
  4380. };
  4381. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4382. EventEmitter.prototype.once = function(type, listener) {
  4383. if (!isFunction(listener))
  4384. throw TypeError('listener must be a function');
  4385. var fired = false;
  4386. function g() {
  4387. this.removeListener(type, g);
  4388. if (!fired) {
  4389. fired = true;
  4390. listener.apply(this, arguments);
  4391. }
  4392. }
  4393. g.listener = listener;
  4394. this.on(type, g);
  4395. return this;
  4396. };
  4397. // emits a 'removeListener' event iff the listener was removed
  4398. EventEmitter.prototype.removeListener = function(type, listener) {
  4399. var list, position, length, i;
  4400. if (!isFunction(listener))
  4401. throw TypeError('listener must be a function');
  4402. if (!this._events || !this._events[type])
  4403. return this;
  4404. list = this._events[type];
  4405. length = list.length;
  4406. position = -1;
  4407. if (list === listener ||
  4408. (isFunction(list.listener) && list.listener === listener)) {
  4409. delete this._events[type];
  4410. if (this._events.removeListener)
  4411. this.emit('removeListener', type, listener);
  4412. } else if (isObject(list)) {
  4413. for (i = length; i-- > 0;) {
  4414. if (list[i] === listener ||
  4415. (list[i].listener && list[i].listener === listener)) {
  4416. position = i;
  4417. break;
  4418. }
  4419. }
  4420. if (position < 0)
  4421. return this;
  4422. if (list.length === 1) {
  4423. list.length = 0;
  4424. delete this._events[type];
  4425. } else {
  4426. list.splice(position, 1);
  4427. }
  4428. if (this._events.removeListener)
  4429. this.emit('removeListener', type, listener);
  4430. }
  4431. return this;
  4432. };
  4433. EventEmitter.prototype.removeAllListeners = function(type) {
  4434. var key, listeners;
  4435. if (!this._events)
  4436. return this;
  4437. // not listening for removeListener, no need to emit
  4438. if (!this._events.removeListener) {
  4439. if (arguments.length === 0)
  4440. this._events = {};
  4441. else if (this._events[type])
  4442. delete this._events[type];
  4443. return this;
  4444. }
  4445. // emit removeListener for all listeners on all events
  4446. if (arguments.length === 0) {
  4447. for (key in this._events) {
  4448. if (key === 'removeListener') continue;
  4449. this.removeAllListeners(key);
  4450. }
  4451. this.removeAllListeners('removeListener');
  4452. this._events = {};
  4453. return this;
  4454. }
  4455. listeners = this._events[type];
  4456. if (isFunction(listeners)) {
  4457. this.removeListener(type, listeners);
  4458. } else {
  4459. // LIFO order
  4460. while (listeners.length)
  4461. this.removeListener(type, listeners[listeners.length - 1]);
  4462. }
  4463. delete this._events[type];
  4464. return this;
  4465. };
  4466. EventEmitter.prototype.listeners = function(type) {
  4467. var ret;
  4468. if (!this._events || !this._events[type])
  4469. ret = [];
  4470. else if (isFunction(this._events[type]))
  4471. ret = [this._events[type]];
  4472. else
  4473. ret = this._events[type].slice();
  4474. return ret;
  4475. };
  4476. EventEmitter.listenerCount = function(emitter, type) {
  4477. var ret;
  4478. if (!emitter._events || !emitter._events[type])
  4479. ret = 0;
  4480. else if (isFunction(emitter._events[type]))
  4481. ret = 1;
  4482. else
  4483. ret = emitter._events[type].length;
  4484. return ret;
  4485. };
  4486. function isFunction(arg) {
  4487. return typeof arg === 'function';
  4488. }
  4489. function isNumber(arg) {
  4490. return typeof arg === 'number';
  4491. }
  4492. function isObject(arg) {
  4493. return typeof arg === 'object' && arg !== null;
  4494. }
  4495. function isUndefined(arg) {
  4496. return arg === void 0;
  4497. }
  4498. },{}]},{},[4])(4)
  4499. }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }