bluebird.js 174 KB

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