omega_target.min.js 328 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.OmegaTarget = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  3. ;(function (exports) {
  4. 'use strict';
  5. var Arr = (typeof Uint8Array !== 'undefined')
  6. ? Uint8Array
  7. : Array
  8. var PLUS = '+'.charCodeAt(0)
  9. var SLASH = '/'.charCodeAt(0)
  10. var NUMBER = '0'.charCodeAt(0)
  11. var LOWER = 'a'.charCodeAt(0)
  12. var UPPER = 'A'.charCodeAt(0)
  13. var PLUS_URL_SAFE = '-'.charCodeAt(0)
  14. var SLASH_URL_SAFE = '_'.charCodeAt(0)
  15. function decode (elt) {
  16. var code = elt.charCodeAt(0)
  17. if (code === PLUS ||
  18. code === PLUS_URL_SAFE)
  19. return 62 // '+'
  20. if (code === SLASH ||
  21. code === SLASH_URL_SAFE)
  22. return 63 // '/'
  23. if (code < NUMBER)
  24. return -1 //no match
  25. if (code < NUMBER + 10)
  26. return code - NUMBER + 26 + 26
  27. if (code < UPPER + 26)
  28. return code - UPPER
  29. if (code < LOWER + 26)
  30. return code - LOWER + 26
  31. }
  32. function b64ToByteArray (b64) {
  33. var i, j, l, tmp, placeHolders, arr
  34. if (b64.length % 4 > 0) {
  35. throw new Error('Invalid string. Length must be a multiple of 4')
  36. }
  37. // the number of equal signs (place holders)
  38. // if there are two placeholders, than the two characters before it
  39. // represent one byte
  40. // if there is only one, then the three characters before it represent 2 bytes
  41. // this is just a cheap hack to not do indexOf twice
  42. var len = b64.length
  43. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  44. // base64 is 4/3 + up to two characters of the original data
  45. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  46. // if there are placeholders, only get up to the last complete 4 chars
  47. l = placeHolders > 0 ? b64.length - 4 : b64.length
  48. var L = 0
  49. function push (v) {
  50. arr[L++] = v
  51. }
  52. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  53. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  54. push((tmp & 0xFF0000) >> 16)
  55. push((tmp & 0xFF00) >> 8)
  56. push(tmp & 0xFF)
  57. }
  58. if (placeHolders === 2) {
  59. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  60. push(tmp & 0xFF)
  61. } else if (placeHolders === 1) {
  62. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  63. push((tmp >> 8) & 0xFF)
  64. push(tmp & 0xFF)
  65. }
  66. return arr
  67. }
  68. function uint8ToBase64 (uint8) {
  69. var i,
  70. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  71. output = "",
  72. temp, length
  73. function encode (num) {
  74. return lookup.charAt(num)
  75. }
  76. function tripletToBase64 (num) {
  77. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  78. }
  79. // go through the array every three bytes, we'll deal with trailing stuff later
  80. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  81. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  82. output += tripletToBase64(temp)
  83. }
  84. // pad the end with zeros, but make sure to not forget the extra bytes
  85. switch (extraBytes) {
  86. case 1:
  87. temp = uint8[uint8.length - 1]
  88. output += encode(temp >> 2)
  89. output += encode((temp << 4) & 0x3F)
  90. output += '=='
  91. break
  92. case 2:
  93. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  94. output += encode(temp >> 10)
  95. output += encode((temp >> 4) & 0x3F)
  96. output += encode((temp << 2) & 0x3F)
  97. output += '='
  98. break
  99. }
  100. return output
  101. }
  102. exports.toByteArray = b64ToByteArray
  103. exports.fromByteArray = uint8ToBase64
  104. }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
  105. },{}],2:[function(require,module,exports){
  106. (function (process,global){
  107. /* @preserve
  108. * The MIT License (MIT)
  109. *
  110. * Copyright (c) 2013-2015 Petka Antonov
  111. *
  112. * Permission is hereby granted, free of charge, to any person obtaining a copy
  113. * of this software and associated documentation files (the "Software"), to deal
  114. * in the Software without restriction, including without limitation the rights
  115. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  116. * copies of the Software, and to permit persons to whom the Software is
  117. * furnished to do so, subject to the following conditions:
  118. *
  119. * The above copyright notice and this permission notice shall be included in
  120. * all copies or substantial portions of the Software.
  121. *
  122. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  123. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  124. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  125. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  126. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  127. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  128. * THE SOFTWARE.
  129. *
  130. */
  131. /**
  132. * bluebird build version 2.11.0
  133. * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
  134. */
  135. !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){
  136. "use strict";
  137. module.exports = function(Promise) {
  138. var SomePromiseArray = Promise._SomePromiseArray;
  139. function any(promises) {
  140. var ret = new SomePromiseArray(promises);
  141. var promise = ret.promise();
  142. ret.setHowMany(1);
  143. ret.setUnwrap();
  144. ret.init();
  145. return promise;
  146. }
  147. Promise.any = function (promises) {
  148. return any(promises);
  149. };
  150. Promise.prototype.any = function () {
  151. return any(this);
  152. };
  153. };
  154. },{}],2:[function(_dereq_,module,exports){
  155. "use strict";
  156. var firstLineError;
  157. try {throw new Error(); } catch (e) {firstLineError = e;}
  158. var schedule = _dereq_("./schedule.js");
  159. var Queue = _dereq_("./queue.js");
  160. var util = _dereq_("./util.js");
  161. function Async() {
  162. this._isTickUsed = false;
  163. this._lateQueue = new Queue(16);
  164. this._normalQueue = new Queue(16);
  165. this._trampolineEnabled = true;
  166. var self = this;
  167. this.drainQueues = function () {
  168. self._drainQueues();
  169. };
  170. this._schedule =
  171. schedule.isStatic ? schedule(this.drainQueues) : schedule;
  172. }
  173. Async.prototype.disableTrampolineIfNecessary = function() {
  174. if (util.hasDevTools) {
  175. this._trampolineEnabled = false;
  176. }
  177. };
  178. Async.prototype.enableTrampoline = function() {
  179. if (!this._trampolineEnabled) {
  180. this._trampolineEnabled = true;
  181. this._schedule = function(fn) {
  182. setTimeout(fn, 0);
  183. };
  184. }
  185. };
  186. Async.prototype.haveItemsQueued = function () {
  187. return this._normalQueue.length() > 0;
  188. };
  189. Async.prototype.throwLater = function(fn, arg) {
  190. if (arguments.length === 1) {
  191. arg = fn;
  192. fn = function () { throw arg; };
  193. }
  194. if (typeof setTimeout !== "undefined") {
  195. setTimeout(function() {
  196. fn(arg);
  197. }, 0);
  198. } else try {
  199. this._schedule(function() {
  200. fn(arg);
  201. });
  202. } catch (e) {
  203. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
  204. }
  205. };
  206. function AsyncInvokeLater(fn, receiver, arg) {
  207. this._lateQueue.push(fn, receiver, arg);
  208. this._queueTick();
  209. }
  210. function AsyncInvoke(fn, receiver, arg) {
  211. this._normalQueue.push(fn, receiver, arg);
  212. this._queueTick();
  213. }
  214. function AsyncSettlePromises(promise) {
  215. this._normalQueue._pushOne(promise);
  216. this._queueTick();
  217. }
  218. if (!util.hasDevTools) {
  219. Async.prototype.invokeLater = AsyncInvokeLater;
  220. Async.prototype.invoke = AsyncInvoke;
  221. Async.prototype.settlePromises = AsyncSettlePromises;
  222. } else {
  223. if (schedule.isStatic) {
  224. schedule = function(fn) { setTimeout(fn, 0); };
  225. }
  226. Async.prototype.invokeLater = function (fn, receiver, arg) {
  227. if (this._trampolineEnabled) {
  228. AsyncInvokeLater.call(this, fn, receiver, arg);
  229. } else {
  230. this._schedule(function() {
  231. setTimeout(function() {
  232. fn.call(receiver, arg);
  233. }, 100);
  234. });
  235. }
  236. };
  237. Async.prototype.invoke = function (fn, receiver, arg) {
  238. if (this._trampolineEnabled) {
  239. AsyncInvoke.call(this, fn, receiver, arg);
  240. } else {
  241. this._schedule(function() {
  242. fn.call(receiver, arg);
  243. });
  244. }
  245. };
  246. Async.prototype.settlePromises = function(promise) {
  247. if (this._trampolineEnabled) {
  248. AsyncSettlePromises.call(this, promise);
  249. } else {
  250. this._schedule(function() {
  251. promise._settlePromises();
  252. });
  253. }
  254. };
  255. }
  256. Async.prototype.invokeFirst = function (fn, receiver, arg) {
  257. this._normalQueue.unshift(fn, receiver, arg);
  258. this._queueTick();
  259. };
  260. Async.prototype._drainQueue = function(queue) {
  261. while (queue.length() > 0) {
  262. var fn = queue.shift();
  263. if (typeof fn !== "function") {
  264. fn._settlePromises();
  265. continue;
  266. }
  267. var receiver = queue.shift();
  268. var arg = queue.shift();
  269. fn.call(receiver, arg);
  270. }
  271. };
  272. Async.prototype._drainQueues = function () {
  273. this._drainQueue(this._normalQueue);
  274. this._reset();
  275. this._drainQueue(this._lateQueue);
  276. };
  277. Async.prototype._queueTick = function () {
  278. if (!this._isTickUsed) {
  279. this._isTickUsed = true;
  280. this._schedule(this.drainQueues);
  281. }
  282. };
  283. Async.prototype._reset = function () {
  284. this._isTickUsed = false;
  285. };
  286. module.exports = new Async();
  287. module.exports.firstLineError = firstLineError;
  288. },{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){
  289. "use strict";
  290. module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
  291. var rejectThis = function(_, e) {
  292. this._reject(e);
  293. };
  294. var targetRejected = function(e, context) {
  295. context.promiseRejectionQueued = true;
  296. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  297. };
  298. var bindingResolved = function(thisArg, context) {
  299. if (this._isPending()) {
  300. this._resolveCallback(context.target);
  301. }
  302. };
  303. var bindingRejected = function(e, context) {
  304. if (!context.promiseRejectionQueued) this._reject(e);
  305. };
  306. Promise.prototype.bind = function (thisArg) {
  307. var maybePromise = tryConvertToPromise(thisArg);
  308. var ret = new Promise(INTERNAL);
  309. ret._propagateFrom(this, 1);
  310. var target = this._target();
  311. ret._setBoundTo(maybePromise);
  312. if (maybePromise instanceof Promise) {
  313. var context = {
  314. promiseRejectionQueued: false,
  315. promise: ret,
  316. target: target,
  317. bindingPromise: maybePromise
  318. };
  319. target._then(INTERNAL, targetRejected, ret._progress, ret, context);
  320. maybePromise._then(
  321. bindingResolved, bindingRejected, ret._progress, ret, context);
  322. } else {
  323. ret._resolveCallback(target);
  324. }
  325. return ret;
  326. };
  327. Promise.prototype._setBoundTo = function (obj) {
  328. if (obj !== undefined) {
  329. this._bitField = this._bitField | 131072;
  330. this._boundTo = obj;
  331. } else {
  332. this._bitField = this._bitField & (~131072);
  333. }
  334. };
  335. Promise.prototype._isBound = function () {
  336. return (this._bitField & 131072) === 131072;
  337. };
  338. Promise.bind = function (thisArg, value) {
  339. var maybePromise = tryConvertToPromise(thisArg);
  340. var ret = new Promise(INTERNAL);
  341. ret._setBoundTo(maybePromise);
  342. if (maybePromise instanceof Promise) {
  343. maybePromise._then(function() {
  344. ret._resolveCallback(value);
  345. }, ret._reject, ret._progress, ret, null);
  346. } else {
  347. ret._resolveCallback(value);
  348. }
  349. return ret;
  350. };
  351. };
  352. },{}],4:[function(_dereq_,module,exports){
  353. "use strict";
  354. var old;
  355. if (typeof Promise !== "undefined") old = Promise;
  356. function noConflict() {
  357. try { if (Promise === bluebird) Promise = old; }
  358. catch (e) {}
  359. return bluebird;
  360. }
  361. var bluebird = _dereq_("./promise.js")();
  362. bluebird.noConflict = noConflict;
  363. module.exports = bluebird;
  364. },{"./promise.js":23}],5:[function(_dereq_,module,exports){
  365. "use strict";
  366. var cr = Object.create;
  367. if (cr) {
  368. var callerCache = cr(null);
  369. var getterCache = cr(null);
  370. callerCache[" size"] = getterCache[" size"] = 0;
  371. }
  372. module.exports = function(Promise) {
  373. var util = _dereq_("./util.js");
  374. var canEvaluate = util.canEvaluate;
  375. var isIdentifier = util.isIdentifier;
  376. var getMethodCaller;
  377. var getGetter;
  378. if (!true) {
  379. var makeMethodCaller = function (methodName) {
  380. return new Function("ensureMethod", " \n\
  381. return function(obj) { \n\
  382. 'use strict' \n\
  383. var len = this.length; \n\
  384. ensureMethod(obj, 'methodName'); \n\
  385. switch(len) { \n\
  386. case 1: return obj.methodName(this[0]); \n\
  387. case 2: return obj.methodName(this[0], this[1]); \n\
  388. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  389. case 0: return obj.methodName(); \n\
  390. default: \n\
  391. return obj.methodName.apply(obj, this); \n\
  392. } \n\
  393. }; \n\
  394. ".replace(/methodName/g, methodName))(ensureMethod);
  395. };
  396. var makeGetter = function (propertyName) {
  397. return new Function("obj", " \n\
  398. 'use strict'; \n\
  399. return obj.propertyName; \n\
  400. ".replace("propertyName", propertyName));
  401. };
  402. var getCompiled = function(name, compiler, cache) {
  403. var ret = cache[name];
  404. if (typeof ret !== "function") {
  405. if (!isIdentifier(name)) {
  406. return null;
  407. }
  408. ret = compiler(name);
  409. cache[name] = ret;
  410. cache[" size"]++;
  411. if (cache[" size"] > 512) {
  412. var keys = Object.keys(cache);
  413. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  414. cache[" size"] = keys.length - 256;
  415. }
  416. }
  417. return ret;
  418. };
  419. getMethodCaller = function(name) {
  420. return getCompiled(name, makeMethodCaller, callerCache);
  421. };
  422. getGetter = function(name) {
  423. return getCompiled(name, makeGetter, getterCache);
  424. };
  425. }
  426. function ensureMethod(obj, methodName) {
  427. var fn;
  428. if (obj != null) fn = obj[methodName];
  429. if (typeof fn !== "function") {
  430. var message = "Object " + util.classString(obj) + " has no method '" +
  431. util.toString(methodName) + "'";
  432. throw new Promise.TypeError(message);
  433. }
  434. return fn;
  435. }
  436. function caller(obj) {
  437. var methodName = this.pop();
  438. var fn = ensureMethod(obj, methodName);
  439. return fn.apply(obj, this);
  440. }
  441. Promise.prototype.call = function (methodName) {
  442. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  443. if (!true) {
  444. if (canEvaluate) {
  445. var maybeCaller = getMethodCaller(methodName);
  446. if (maybeCaller !== null) {
  447. return this._then(
  448. maybeCaller, undefined, undefined, args, undefined);
  449. }
  450. }
  451. }
  452. args.push(methodName);
  453. return this._then(caller, undefined, undefined, args, undefined);
  454. };
  455. function namedGetter(obj) {
  456. return obj[this];
  457. }
  458. function indexedGetter(obj) {
  459. var index = +this;
  460. if (index < 0) index = Math.max(0, index + obj.length);
  461. return obj[index];
  462. }
  463. Promise.prototype.get = function (propertyName) {
  464. var isIndex = (typeof propertyName === "number");
  465. var getter;
  466. if (!isIndex) {
  467. if (canEvaluate) {
  468. var maybeGetter = getGetter(propertyName);
  469. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  470. } else {
  471. getter = namedGetter;
  472. }
  473. } else {
  474. getter = indexedGetter;
  475. }
  476. return this._then(getter, undefined, undefined, propertyName, undefined);
  477. };
  478. };
  479. },{"./util.js":38}],6:[function(_dereq_,module,exports){
  480. "use strict";
  481. module.exports = function(Promise) {
  482. var errors = _dereq_("./errors.js");
  483. var async = _dereq_("./async.js");
  484. var CancellationError = errors.CancellationError;
  485. Promise.prototype._cancel = function (reason) {
  486. if (!this.isCancellable()) return this;
  487. var parent;
  488. var promiseToReject = this;
  489. while ((parent = promiseToReject._cancellationParent) !== undefined &&
  490. parent.isCancellable()) {
  491. promiseToReject = parent;
  492. }
  493. this._unsetCancellable();
  494. promiseToReject._target()._rejectCallback(reason, false, true);
  495. };
  496. Promise.prototype.cancel = function (reason) {
  497. if (!this.isCancellable()) return this;
  498. if (reason === undefined) reason = new CancellationError();
  499. async.invokeLater(this._cancel, this, reason);
  500. return this;
  501. };
  502. Promise.prototype.cancellable = function () {
  503. if (this._cancellable()) return this;
  504. async.enableTrampoline();
  505. this._setCancellable();
  506. this._cancellationParent = undefined;
  507. return this;
  508. };
  509. Promise.prototype.uncancellable = function () {
  510. var ret = this.then();
  511. ret._unsetCancellable();
  512. return ret;
  513. };
  514. Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
  515. var ret = this._then(didFulfill, didReject, didProgress,
  516. undefined, undefined);
  517. ret._setCancellable();
  518. ret._cancellationParent = undefined;
  519. return ret;
  520. };
  521. };
  522. },{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
  523. "use strict";
  524. module.exports = function() {
  525. var async = _dereq_("./async.js");
  526. var util = _dereq_("./util.js");
  527. var bluebirdFramePattern =
  528. /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
  529. var stackFramePattern = null;
  530. var formatStack = null;
  531. var indentStackFrames = false;
  532. var warn;
  533. function CapturedTrace(parent) {
  534. this._parent = parent;
  535. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  536. captureStackTrace(this, CapturedTrace);
  537. if (length > 32) this.uncycle();
  538. }
  539. util.inherits(CapturedTrace, Error);
  540. CapturedTrace.prototype.uncycle = function() {
  541. var length = this._length;
  542. if (length < 2) return;
  543. var nodes = [];
  544. var stackToIndex = {};
  545. for (var i = 0, node = this; node !== undefined; ++i) {
  546. nodes.push(node);
  547. node = node._parent;
  548. }
  549. length = this._length = i;
  550. for (var i = length - 1; i >= 0; --i) {
  551. var stack = nodes[i].stack;
  552. if (stackToIndex[stack] === undefined) {
  553. stackToIndex[stack] = i;
  554. }
  555. }
  556. for (var i = 0; i < length; ++i) {
  557. var currentStack = nodes[i].stack;
  558. var index = stackToIndex[currentStack];
  559. if (index !== undefined && index !== i) {
  560. if (index > 0) {
  561. nodes[index - 1]._parent = undefined;
  562. nodes[index - 1]._length = 1;
  563. }
  564. nodes[i]._parent = undefined;
  565. nodes[i]._length = 1;
  566. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  567. if (index < length - 1) {
  568. cycleEdgeNode._parent = nodes[index + 1];
  569. cycleEdgeNode._parent.uncycle();
  570. cycleEdgeNode._length =
  571. cycleEdgeNode._parent._length + 1;
  572. } else {
  573. cycleEdgeNode._parent = undefined;
  574. cycleEdgeNode._length = 1;
  575. }
  576. var currentChildLength = cycleEdgeNode._length + 1;
  577. for (var j = i - 2; j >= 0; --j) {
  578. nodes[j]._length = currentChildLength;
  579. currentChildLength++;
  580. }
  581. return;
  582. }
  583. }
  584. };
  585. CapturedTrace.prototype.parent = function() {
  586. return this._parent;
  587. };
  588. CapturedTrace.prototype.hasParent = function() {
  589. return this._parent !== undefined;
  590. };
  591. CapturedTrace.prototype.attachExtraTrace = function(error) {
  592. if (error.__stackCleaned__) return;
  593. this.uncycle();
  594. var parsed = CapturedTrace.parseStackAndMessage(error);
  595. var message = parsed.message;
  596. var stacks = [parsed.stack];
  597. var trace = this;
  598. while (trace !== undefined) {
  599. stacks.push(cleanStack(trace.stack.split("\n")));
  600. trace = trace._parent;
  601. }
  602. removeCommonRoots(stacks);
  603. removeDuplicateOrEmptyJumps(stacks);
  604. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  605. util.notEnumerableProp(error, "__stackCleaned__", true);
  606. };
  607. function reconstructStack(message, stacks) {
  608. for (var i = 0; i < stacks.length - 1; ++i) {
  609. stacks[i].push("From previous event:");
  610. stacks[i] = stacks[i].join("\n");
  611. }
  612. if (i < stacks.length) {
  613. stacks[i] = stacks[i].join("\n");
  614. }
  615. return message + "\n" + stacks.join("\n");
  616. }
  617. function removeDuplicateOrEmptyJumps(stacks) {
  618. for (var i = 0; i < stacks.length; ++i) {
  619. if (stacks[i].length === 0 ||
  620. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  621. stacks.splice(i, 1);
  622. i--;
  623. }
  624. }
  625. }
  626. function removeCommonRoots(stacks) {
  627. var current = stacks[0];
  628. for (var i = 1; i < stacks.length; ++i) {
  629. var prev = stacks[i];
  630. var currentLastIndex = current.length - 1;
  631. var currentLastLine = current[currentLastIndex];
  632. var commonRootMeetPoint = -1;
  633. for (var j = prev.length - 1; j >= 0; --j) {
  634. if (prev[j] === currentLastLine) {
  635. commonRootMeetPoint = j;
  636. break;
  637. }
  638. }
  639. for (var j = commonRootMeetPoint; j >= 0; --j) {
  640. var line = prev[j];
  641. if (current[currentLastIndex] === line) {
  642. current.pop();
  643. currentLastIndex--;
  644. } else {
  645. break;
  646. }
  647. }
  648. current = prev;
  649. }
  650. }
  651. function cleanStack(stack) {
  652. var ret = [];
  653. for (var i = 0; i < stack.length; ++i) {
  654. var line = stack[i];
  655. var isTraceLine = stackFramePattern.test(line) ||
  656. " (No stack trace)" === line;
  657. var isInternalFrame = isTraceLine && shouldIgnore(line);
  658. if (isTraceLine && !isInternalFrame) {
  659. if (indentStackFrames && line.charAt(0) !== " ") {
  660. line = " " + line;
  661. }
  662. ret.push(line);
  663. }
  664. }
  665. return ret;
  666. }
  667. function stackFramesAsArray(error) {
  668. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  669. for (var i = 0; i < stack.length; ++i) {
  670. var line = stack[i];
  671. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  672. break;
  673. }
  674. }
  675. if (i > 0) {
  676. stack = stack.slice(i);
  677. }
  678. return stack;
  679. }
  680. CapturedTrace.parseStackAndMessage = function(error) {
  681. var stack = error.stack;
  682. var message = error.toString();
  683. stack = typeof stack === "string" && stack.length > 0
  684. ? stackFramesAsArray(error) : [" (No stack trace)"];
  685. return {
  686. message: message,
  687. stack: cleanStack(stack)
  688. };
  689. };
  690. CapturedTrace.formatAndLogError = function(error, title) {
  691. if (typeof console !== "undefined") {
  692. var message;
  693. if (typeof error === "object" || typeof error === "function") {
  694. var stack = error.stack;
  695. message = title + formatStack(stack, error);
  696. } else {
  697. message = title + String(error);
  698. }
  699. if (typeof warn === "function") {
  700. warn(message);
  701. } else if (typeof console.log === "function" ||
  702. typeof console.log === "object") {
  703. console.log(message);
  704. }
  705. }
  706. };
  707. CapturedTrace.unhandledRejection = function (reason) {
  708. CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
  709. };
  710. CapturedTrace.isSupported = function () {
  711. return typeof captureStackTrace === "function";
  712. };
  713. CapturedTrace.fireRejectionEvent =
  714. function(name, localHandler, reason, promise) {
  715. var localEventFired = false;
  716. try {
  717. if (typeof localHandler === "function") {
  718. localEventFired = true;
  719. if (name === "rejectionHandled") {
  720. localHandler(promise);
  721. } else {
  722. localHandler(reason, promise);
  723. }
  724. }
  725. } catch (e) {
  726. async.throwLater(e);
  727. }
  728. var globalEventFired = false;
  729. try {
  730. globalEventFired = fireGlobalEvent(name, reason, promise);
  731. } catch (e) {
  732. globalEventFired = true;
  733. async.throwLater(e);
  734. }
  735. var domEventFired = false;
  736. if (fireDomEvent) {
  737. try {
  738. domEventFired = fireDomEvent(name.toLowerCase(), {
  739. reason: reason,
  740. promise: promise
  741. });
  742. } catch (e) {
  743. domEventFired = true;
  744. async.throwLater(e);
  745. }
  746. }
  747. if (!globalEventFired && !localEventFired && !domEventFired &&
  748. name === "unhandledRejection") {
  749. CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
  750. }
  751. };
  752. function formatNonError(obj) {
  753. var str;
  754. if (typeof obj === "function") {
  755. str = "[function " +
  756. (obj.name || "anonymous") +
  757. "]";
  758. } else {
  759. str = obj.toString();
  760. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  761. if (ruselessToString.test(str)) {
  762. try {
  763. var newStr = JSON.stringify(obj);
  764. str = newStr;
  765. }
  766. catch(e) {
  767. }
  768. }
  769. if (str.length === 0) {
  770. str = "(empty array)";
  771. }
  772. }
  773. return ("(<" + snip(str) + ">, no stack trace)");
  774. }
  775. function snip(str) {
  776. var maxChars = 41;
  777. if (str.length < maxChars) {
  778. return str;
  779. }
  780. return str.substr(0, maxChars - 3) + "...";
  781. }
  782. var shouldIgnore = function() { return false; };
  783. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  784. function parseLineInfo(line) {
  785. var matches = line.match(parseLineInfoRegex);
  786. if (matches) {
  787. return {
  788. fileName: matches[1],
  789. line: parseInt(matches[2], 10)
  790. };
  791. }
  792. }
  793. CapturedTrace.setBounds = function(firstLineError, lastLineError) {
  794. if (!CapturedTrace.isSupported()) return;
  795. var firstStackLines = firstLineError.stack.split("\n");
  796. var lastStackLines = lastLineError.stack.split("\n");
  797. var firstIndex = -1;
  798. var lastIndex = -1;
  799. var firstFileName;
  800. var lastFileName;
  801. for (var i = 0; i < firstStackLines.length; ++i) {
  802. var result = parseLineInfo(firstStackLines[i]);
  803. if (result) {
  804. firstFileName = result.fileName;
  805. firstIndex = result.line;
  806. break;
  807. }
  808. }
  809. for (var i = 0; i < lastStackLines.length; ++i) {
  810. var result = parseLineInfo(lastStackLines[i]);
  811. if (result) {
  812. lastFileName = result.fileName;
  813. lastIndex = result.line;
  814. break;
  815. }
  816. }
  817. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  818. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  819. return;
  820. }
  821. shouldIgnore = function(line) {
  822. if (bluebirdFramePattern.test(line)) return true;
  823. var info = parseLineInfo(line);
  824. if (info) {
  825. if (info.fileName === firstFileName &&
  826. (firstIndex <= info.line && info.line <= lastIndex)) {
  827. return true;
  828. }
  829. }
  830. return false;
  831. };
  832. };
  833. var captureStackTrace = (function stackDetection() {
  834. var v8stackFramePattern = /^\s*at\s*/;
  835. var v8stackFormatter = function(stack, error) {
  836. if (typeof stack === "string") return stack;
  837. if (error.name !== undefined &&
  838. error.message !== undefined) {
  839. return error.toString();
  840. }
  841. return formatNonError(error);
  842. };
  843. if (typeof Error.stackTraceLimit === "number" &&
  844. typeof Error.captureStackTrace === "function") {
  845. Error.stackTraceLimit = Error.stackTraceLimit + 6;
  846. stackFramePattern = v8stackFramePattern;
  847. formatStack = v8stackFormatter;
  848. var captureStackTrace = Error.captureStackTrace;
  849. shouldIgnore = function(line) {
  850. return bluebirdFramePattern.test(line);
  851. };
  852. return function(receiver, ignoreUntil) {
  853. Error.stackTraceLimit = Error.stackTraceLimit + 6;
  854. captureStackTrace(receiver, ignoreUntil);
  855. Error.stackTraceLimit = Error.stackTraceLimit - 6;
  856. };
  857. }
  858. var err = new Error();
  859. if (typeof err.stack === "string" &&
  860. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  861. stackFramePattern = /@/;
  862. formatStack = v8stackFormatter;
  863. indentStackFrames = true;
  864. return function captureStackTrace(o) {
  865. o.stack = new Error().stack;
  866. };
  867. }
  868. var hasStackAfterThrow;
  869. try { throw new Error(); }
  870. catch(e) {
  871. hasStackAfterThrow = ("stack" in e);
  872. }
  873. if (!("stack" in err) && hasStackAfterThrow &&
  874. typeof Error.stackTraceLimit === "number") {
  875. stackFramePattern = v8stackFramePattern;
  876. formatStack = v8stackFormatter;
  877. return function captureStackTrace(o) {
  878. Error.stackTraceLimit = Error.stackTraceLimit + 6;
  879. try { throw new Error(); }
  880. catch(e) { o.stack = e.stack; }
  881. Error.stackTraceLimit = Error.stackTraceLimit - 6;
  882. };
  883. }
  884. formatStack = function(stack, error) {
  885. if (typeof stack === "string") return stack;
  886. if ((typeof error === "object" ||
  887. typeof error === "function") &&
  888. error.name !== undefined &&
  889. error.message !== undefined) {
  890. return error.toString();
  891. }
  892. return formatNonError(error);
  893. };
  894. return null;
  895. })([]);
  896. var fireDomEvent;
  897. var fireGlobalEvent = (function() {
  898. if (util.isNode) {
  899. return function(name, reason, promise) {
  900. if (name === "rejectionHandled") {
  901. return process.emit(name, promise);
  902. } else {
  903. return process.emit(name, reason, promise);
  904. }
  905. };
  906. } else {
  907. var customEventWorks = false;
  908. var anyEventWorks = true;
  909. try {
  910. var ev = new self.CustomEvent("test");
  911. customEventWorks = ev instanceof CustomEvent;
  912. } catch (e) {}
  913. if (!customEventWorks) {
  914. try {
  915. var event = document.createEvent("CustomEvent");
  916. event.initCustomEvent("testingtheevent", false, true, {});
  917. self.dispatchEvent(event);
  918. } catch (e) {
  919. anyEventWorks = false;
  920. }
  921. }
  922. if (anyEventWorks) {
  923. fireDomEvent = function(type, detail) {
  924. var event;
  925. if (customEventWorks) {
  926. event = new self.CustomEvent(type, {
  927. detail: detail,
  928. bubbles: false,
  929. cancelable: true
  930. });
  931. } else if (self.dispatchEvent) {
  932. event = document.createEvent("CustomEvent");
  933. event.initCustomEvent(type, false, true, detail);
  934. }
  935. return event ? !self.dispatchEvent(event) : false;
  936. };
  937. }
  938. var toWindowMethodNameMap = {};
  939. toWindowMethodNameMap["unhandledRejection"] = ("on" +
  940. "unhandledRejection").toLowerCase();
  941. toWindowMethodNameMap["rejectionHandled"] = ("on" +
  942. "rejectionHandled").toLowerCase();
  943. return function(name, reason, promise) {
  944. var methodName = toWindowMethodNameMap[name];
  945. var method = self[methodName];
  946. if (!method) return false;
  947. if (name === "rejectionHandled") {
  948. method.call(self, promise);
  949. } else {
  950. method.call(self, reason, promise);
  951. }
  952. return true;
  953. };
  954. }
  955. })();
  956. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  957. warn = function (message) {
  958. console.warn(message);
  959. };
  960. if (util.isNode && process.stderr.isTTY) {
  961. warn = function(message) {
  962. process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
  963. };
  964. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  965. warn = function(message) {
  966. console.warn("%c" + message, "color: red");
  967. };
  968. }
  969. }
  970. return CapturedTrace;
  971. };
  972. },{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
  973. "use strict";
  974. module.exports = function(NEXT_FILTER) {
  975. var util = _dereq_("./util.js");
  976. var errors = _dereq_("./errors.js");
  977. var tryCatch = util.tryCatch;
  978. var errorObj = util.errorObj;
  979. var keys = _dereq_("./es5.js").keys;
  980. var TypeError = errors.TypeError;
  981. function CatchFilter(instances, callback, promise) {
  982. this._instances = instances;
  983. this._callback = callback;
  984. this._promise = promise;
  985. }
  986. function safePredicate(predicate, e) {
  987. var safeObject = {};
  988. var retfilter = tryCatch(predicate).call(safeObject, e);
  989. if (retfilter === errorObj) return retfilter;
  990. var safeKeys = keys(safeObject);
  991. if (safeKeys.length) {
  992. errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a");
  993. return errorObj;
  994. }
  995. return retfilter;
  996. }
  997. CatchFilter.prototype.doFilter = function (e) {
  998. var cb = this._callback;
  999. var promise = this._promise;
  1000. var boundTo = promise._boundValue();
  1001. for (var i = 0, len = this._instances.length; i < len; ++i) {
  1002. var item = this._instances[i];
  1003. var itemIsErrorType = item === Error ||
  1004. (item != null && item.prototype instanceof Error);
  1005. if (itemIsErrorType && e instanceof item) {
  1006. var ret = tryCatch(cb).call(boundTo, e);
  1007. if (ret === errorObj) {
  1008. NEXT_FILTER.e = ret.e;
  1009. return NEXT_FILTER;
  1010. }
  1011. return ret;
  1012. } else if (typeof item === "function" && !itemIsErrorType) {
  1013. var shouldHandle = safePredicate(item, e);
  1014. if (shouldHandle === errorObj) {
  1015. e = errorObj.e;
  1016. break;
  1017. } else if (shouldHandle) {
  1018. var ret = tryCatch(cb).call(boundTo, e);
  1019. if (ret === errorObj) {
  1020. NEXT_FILTER.e = ret.e;
  1021. return NEXT_FILTER;
  1022. }
  1023. return ret;
  1024. }
  1025. }
  1026. }
  1027. NEXT_FILTER.e = e;
  1028. return NEXT_FILTER;
  1029. };
  1030. return CatchFilter;
  1031. };
  1032. },{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
  1033. "use strict";
  1034. module.exports = function(Promise, CapturedTrace, isDebugging) {
  1035. var contextStack = [];
  1036. function Context() {
  1037. this._trace = new CapturedTrace(peekContext());
  1038. }
  1039. Context.prototype._pushContext = function () {
  1040. if (!isDebugging()) return;
  1041. if (this._trace !== undefined) {
  1042. contextStack.push(this._trace);
  1043. }
  1044. };
  1045. Context.prototype._popContext = function () {
  1046. if (!isDebugging()) return;
  1047. if (this._trace !== undefined) {
  1048. contextStack.pop();
  1049. }
  1050. };
  1051. function createContext() {
  1052. if (isDebugging()) return new Context();
  1053. }
  1054. function peekContext() {
  1055. var lastIndex = contextStack.length - 1;
  1056. if (lastIndex >= 0) {
  1057. return contextStack[lastIndex];
  1058. }
  1059. return undefined;
  1060. }
  1061. Promise.prototype._peekContext = peekContext;
  1062. Promise.prototype._pushContext = Context.prototype._pushContext;
  1063. Promise.prototype._popContext = Context.prototype._popContext;
  1064. return createContext;
  1065. };
  1066. },{}],10:[function(_dereq_,module,exports){
  1067. "use strict";
  1068. module.exports = function(Promise, CapturedTrace) {
  1069. var getDomain = Promise._getDomain;
  1070. var async = _dereq_("./async.js");
  1071. var Warning = _dereq_("./errors.js").Warning;
  1072. var util = _dereq_("./util.js");
  1073. var canAttachTrace = util.canAttachTrace;
  1074. var unhandledRejectionHandled;
  1075. var possiblyUnhandledRejection;
  1076. var debugging = false || (util.isNode &&
  1077. (!!process.env["BLUEBIRD_DEBUG"] ||
  1078. process.env["NODE_ENV"] === "development"));
  1079. if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false;
  1080. if (debugging) {
  1081. async.disableTrampolineIfNecessary();
  1082. }
  1083. Promise.prototype._ignoreRejections = function() {
  1084. this._unsetRejectionIsUnhandled();
  1085. this._bitField = this._bitField | 16777216;
  1086. };
  1087. Promise.prototype._ensurePossibleRejectionHandled = function () {
  1088. if ((this._bitField & 16777216) !== 0) return;
  1089. this._setRejectionIsUnhandled();
  1090. async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  1091. };
  1092. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  1093. CapturedTrace.fireRejectionEvent("rejectionHandled",
  1094. unhandledRejectionHandled, undefined, this);
  1095. };
  1096. Promise.prototype._notifyUnhandledRejection = function () {
  1097. if (this._isRejectionUnhandled()) {
  1098. var reason = this._getCarriedStackTrace() || this._settledValue;
  1099. this._setUnhandledRejectionIsNotified();
  1100. CapturedTrace.fireRejectionEvent("unhandledRejection",
  1101. possiblyUnhandledRejection, reason, this);
  1102. }
  1103. };
  1104. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  1105. this._bitField = this._bitField | 524288;
  1106. };
  1107. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  1108. this._bitField = this._bitField & (~524288);
  1109. };
  1110. Promise.prototype._isUnhandledRejectionNotified = function () {
  1111. return (this._bitField & 524288) > 0;
  1112. };
  1113. Promise.prototype._setRejectionIsUnhandled = function () {
  1114. this._bitField = this._bitField | 2097152;
  1115. };
  1116. Promise.prototype._unsetRejectionIsUnhandled = function () {
  1117. this._bitField = this._bitField & (~2097152);
  1118. if (this._isUnhandledRejectionNotified()) {
  1119. this._unsetUnhandledRejectionIsNotified();
  1120. this._notifyUnhandledRejectionIsHandled();
  1121. }
  1122. };
  1123. Promise.prototype._isRejectionUnhandled = function () {
  1124. return (this._bitField & 2097152) > 0;
  1125. };
  1126. Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
  1127. this._bitField = this._bitField | 1048576;
  1128. this._fulfillmentHandler0 = capturedTrace;
  1129. };
  1130. Promise.prototype._isCarryingStackTrace = function () {
  1131. return (this._bitField & 1048576) > 0;
  1132. };
  1133. Promise.prototype._getCarriedStackTrace = function () {
  1134. return this._isCarryingStackTrace()
  1135. ? this._fulfillmentHandler0
  1136. : undefined;
  1137. };
  1138. Promise.prototype._captureStackTrace = function () {
  1139. if (debugging) {
  1140. this._trace = new CapturedTrace(this._peekContext());
  1141. }
  1142. return this;
  1143. };
  1144. Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
  1145. if (debugging && canAttachTrace(error)) {
  1146. var trace = this._trace;
  1147. if (trace !== undefined) {
  1148. if (ignoreSelf) trace = trace._parent;
  1149. }
  1150. if (trace !== undefined) {
  1151. trace.attachExtraTrace(error);
  1152. } else if (!error.__stackCleaned__) {
  1153. var parsed = CapturedTrace.parseStackAndMessage(error);
  1154. util.notEnumerableProp(error, "stack",
  1155. parsed.message + "\n" + parsed.stack.join("\n"));
  1156. util.notEnumerableProp(error, "__stackCleaned__", true);
  1157. }
  1158. }
  1159. };
  1160. Promise.prototype._warn = function(message) {
  1161. var warning = new Warning(message);
  1162. var ctx = this._peekContext();
  1163. if (ctx) {
  1164. ctx.attachExtraTrace(warning);
  1165. } else {
  1166. var parsed = CapturedTrace.parseStackAndMessage(warning);
  1167. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  1168. }
  1169. CapturedTrace.formatAndLogError(warning, "");
  1170. };
  1171. Promise.onPossiblyUnhandledRejection = function (fn) {
  1172. var domain = getDomain();
  1173. possiblyUnhandledRejection =
  1174. typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
  1175. : undefined;
  1176. };
  1177. Promise.onUnhandledRejectionHandled = function (fn) {
  1178. var domain = getDomain();
  1179. unhandledRejectionHandled =
  1180. typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
  1181. : undefined;
  1182. };
  1183. Promise.longStackTraces = function () {
  1184. if (async.haveItemsQueued() &&
  1185. debugging === false
  1186. ) {
  1187. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a");
  1188. }
  1189. debugging = CapturedTrace.isSupported();
  1190. if (debugging) {
  1191. async.disableTrampolineIfNecessary();
  1192. }
  1193. };
  1194. Promise.hasLongStackTraces = function () {
  1195. return debugging && CapturedTrace.isSupported();
  1196. };
  1197. if (!CapturedTrace.isSupported()) {
  1198. Promise.longStackTraces = function(){};
  1199. debugging = false;
  1200. }
  1201. return function() {
  1202. return debugging;
  1203. };
  1204. };
  1205. },{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
  1206. "use strict";
  1207. var util = _dereq_("./util.js");
  1208. var isPrimitive = util.isPrimitive;
  1209. module.exports = function(Promise) {
  1210. var returner = function () {
  1211. return this;
  1212. };
  1213. var thrower = function () {
  1214. throw this;
  1215. };
  1216. var returnUndefined = function() {};
  1217. var throwUndefined = function() {
  1218. throw undefined;
  1219. };
  1220. var wrapper = function (value, action) {
  1221. if (action === 1) {
  1222. return function () {
  1223. throw value;
  1224. };
  1225. } else if (action === 2) {
  1226. return function () {
  1227. return value;
  1228. };
  1229. }
  1230. };
  1231. Promise.prototype["return"] =
  1232. Promise.prototype.thenReturn = function (value) {
  1233. if (value === undefined) return this.then(returnUndefined);
  1234. if (isPrimitive(value)) {
  1235. return this._then(
  1236. wrapper(value, 2),
  1237. undefined,
  1238. undefined,
  1239. undefined,
  1240. undefined
  1241. );
  1242. } else if (value instanceof Promise) {
  1243. value._ignoreRejections();
  1244. }
  1245. return this._then(returner, undefined, undefined, value, undefined);
  1246. };
  1247. Promise.prototype["throw"] =
  1248. Promise.prototype.thenThrow = function (reason) {
  1249. if (reason === undefined) return this.then(throwUndefined);
  1250. if (isPrimitive(reason)) {
  1251. return this._then(
  1252. wrapper(reason, 1),
  1253. undefined,
  1254. undefined,
  1255. undefined,
  1256. undefined
  1257. );
  1258. }
  1259. return this._then(thrower, undefined, undefined, reason, undefined);
  1260. };
  1261. };
  1262. },{"./util.js":38}],12:[function(_dereq_,module,exports){
  1263. "use strict";
  1264. module.exports = function(Promise, INTERNAL) {
  1265. var PromiseReduce = Promise.reduce;
  1266. Promise.prototype.each = function (fn) {
  1267. return PromiseReduce(this, fn, null, INTERNAL);
  1268. };
  1269. Promise.each = function (promises, fn) {
  1270. return PromiseReduce(promises, fn, null, INTERNAL);
  1271. };
  1272. };
  1273. },{}],13:[function(_dereq_,module,exports){
  1274. "use strict";
  1275. var es5 = _dereq_("./es5.js");
  1276. var Objectfreeze = es5.freeze;
  1277. var util = _dereq_("./util.js");
  1278. var inherits = util.inherits;
  1279. var notEnumerableProp = util.notEnumerableProp;
  1280. function subError(nameProperty, defaultMessage) {
  1281. function SubError(message) {
  1282. if (!(this instanceof SubError)) return new SubError(message);
  1283. notEnumerableProp(this, "message",
  1284. typeof message === "string" ? message : defaultMessage);
  1285. notEnumerableProp(this, "name", nameProperty);
  1286. if (Error.captureStackTrace) {
  1287. Error.captureStackTrace(this, this.constructor);
  1288. } else {
  1289. Error.call(this);
  1290. }
  1291. }
  1292. inherits(SubError, Error);
  1293. return SubError;
  1294. }
  1295. var _TypeError, _RangeError;
  1296. var Warning = subError("Warning", "warning");
  1297. var CancellationError = subError("CancellationError", "cancellation error");
  1298. var TimeoutError = subError("TimeoutError", "timeout error");
  1299. var AggregateError = subError("AggregateError", "aggregate error");
  1300. try {
  1301. _TypeError = TypeError;
  1302. _RangeError = RangeError;
  1303. } catch(e) {
  1304. _TypeError = subError("TypeError", "type error");
  1305. _RangeError = subError("RangeError", "range error");
  1306. }
  1307. var methods = ("join pop push shift unshift slice filter forEach some " +
  1308. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  1309. for (var i = 0; i < methods.length; ++i) {
  1310. if (typeof Array.prototype[methods[i]] === "function") {
  1311. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  1312. }
  1313. }
  1314. es5.defineProperty(AggregateError.prototype, "length", {
  1315. value: 0,
  1316. configurable: false,
  1317. writable: true,
  1318. enumerable: true
  1319. });
  1320. AggregateError.prototype["isOperational"] = true;
  1321. var level = 0;
  1322. AggregateError.prototype.toString = function() {
  1323. var indent = Array(level * 4 + 1).join(" ");
  1324. var ret = "\n" + indent + "AggregateError of:" + "\n";
  1325. level++;
  1326. indent = Array(level * 4 + 1).join(" ");
  1327. for (var i = 0; i < this.length; ++i) {
  1328. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  1329. var lines = str.split("\n");
  1330. for (var j = 0; j < lines.length; ++j) {
  1331. lines[j] = indent + lines[j];
  1332. }
  1333. str = lines.join("\n");
  1334. ret += str + "\n";
  1335. }
  1336. level--;
  1337. return ret;
  1338. };
  1339. function OperationalError(message) {
  1340. if (!(this instanceof OperationalError))
  1341. return new OperationalError(message);
  1342. notEnumerableProp(this, "name", "OperationalError");
  1343. notEnumerableProp(this, "message", message);
  1344. this.cause = message;
  1345. this["isOperational"] = true;
  1346. if (message instanceof Error) {
  1347. notEnumerableProp(this, "message", message.message);
  1348. notEnumerableProp(this, "stack", message.stack);
  1349. } else if (Error.captureStackTrace) {
  1350. Error.captureStackTrace(this, this.constructor);
  1351. }
  1352. }
  1353. inherits(OperationalError, Error);
  1354. var errorTypes = Error["__BluebirdErrorTypes__"];
  1355. if (!errorTypes) {
  1356. errorTypes = Objectfreeze({
  1357. CancellationError: CancellationError,
  1358. TimeoutError: TimeoutError,
  1359. OperationalError: OperationalError,
  1360. RejectionError: OperationalError,
  1361. AggregateError: AggregateError
  1362. });
  1363. notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
  1364. }
  1365. module.exports = {
  1366. Error: Error,
  1367. TypeError: _TypeError,
  1368. RangeError: _RangeError,
  1369. CancellationError: errorTypes.CancellationError,
  1370. OperationalError: errorTypes.OperationalError,
  1371. TimeoutError: errorTypes.TimeoutError,
  1372. AggregateError: errorTypes.AggregateError,
  1373. Warning: Warning
  1374. };
  1375. },{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
  1376. var isES5 = (function(){
  1377. "use strict";
  1378. return this === undefined;
  1379. })();
  1380. if (isES5) {
  1381. module.exports = {
  1382. freeze: Object.freeze,
  1383. defineProperty: Object.defineProperty,
  1384. getDescriptor: Object.getOwnPropertyDescriptor,
  1385. keys: Object.keys,
  1386. names: Object.getOwnPropertyNames,
  1387. getPrototypeOf: Object.getPrototypeOf,
  1388. isArray: Array.isArray,
  1389. isES5: isES5,
  1390. propertyIsWritable: function(obj, prop) {
  1391. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  1392. return !!(!descriptor || descriptor.writable || descriptor.set);
  1393. }
  1394. };
  1395. } else {
  1396. var has = {}.hasOwnProperty;
  1397. var str = {}.toString;
  1398. var proto = {}.constructor.prototype;
  1399. var ObjectKeys = function (o) {
  1400. var ret = [];
  1401. for (var key in o) {
  1402. if (has.call(o, key)) {
  1403. ret.push(key);
  1404. }
  1405. }
  1406. return ret;
  1407. };
  1408. var ObjectGetDescriptor = function(o, key) {
  1409. return {value: o[key]};
  1410. };
  1411. var ObjectDefineProperty = function (o, key, desc) {
  1412. o[key] = desc.value;
  1413. return o;
  1414. };
  1415. var ObjectFreeze = function (obj) {
  1416. return obj;
  1417. };
  1418. var ObjectGetPrototypeOf = function (obj) {
  1419. try {
  1420. return Object(obj).constructor.prototype;
  1421. }
  1422. catch (e) {
  1423. return proto;
  1424. }
  1425. };
  1426. var ArrayIsArray = function (obj) {
  1427. try {
  1428. return str.call(obj) === "[object Array]";
  1429. }
  1430. catch(e) {
  1431. return false;
  1432. }
  1433. };
  1434. module.exports = {
  1435. isArray: ArrayIsArray,
  1436. keys: ObjectKeys,
  1437. names: ObjectKeys,
  1438. defineProperty: ObjectDefineProperty,
  1439. getDescriptor: ObjectGetDescriptor,
  1440. freeze: ObjectFreeze,
  1441. getPrototypeOf: ObjectGetPrototypeOf,
  1442. isES5: isES5,
  1443. propertyIsWritable: function() {
  1444. return true;
  1445. }
  1446. };
  1447. }
  1448. },{}],15:[function(_dereq_,module,exports){
  1449. "use strict";
  1450. module.exports = function(Promise, INTERNAL) {
  1451. var PromiseMap = Promise.map;
  1452. Promise.prototype.filter = function (fn, options) {
  1453. return PromiseMap(this, fn, options, INTERNAL);
  1454. };
  1455. Promise.filter = function (promises, fn, options) {
  1456. return PromiseMap(promises, fn, options, INTERNAL);
  1457. };
  1458. };
  1459. },{}],16:[function(_dereq_,module,exports){
  1460. "use strict";
  1461. module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
  1462. var util = _dereq_("./util.js");
  1463. var isPrimitive = util.isPrimitive;
  1464. var thrower = util.thrower;
  1465. function returnThis() {
  1466. return this;
  1467. }
  1468. function throwThis() {
  1469. throw this;
  1470. }
  1471. function return$(r) {
  1472. return function() {
  1473. return r;
  1474. };
  1475. }
  1476. function throw$(r) {
  1477. return function() {
  1478. throw r;
  1479. };
  1480. }
  1481. function promisedFinally(ret, reasonOrValue, isFulfilled) {
  1482. var then;
  1483. if (isPrimitive(reasonOrValue)) {
  1484. then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
  1485. } else {
  1486. then = isFulfilled ? returnThis : throwThis;
  1487. }
  1488. return ret._then(then, thrower, undefined, reasonOrValue, undefined);
  1489. }
  1490. function finallyHandler(reasonOrValue) {
  1491. var promise = this.promise;
  1492. var handler = this.handler;
  1493. var ret = promise._isBound()
  1494. ? handler.call(promise._boundValue())
  1495. : handler();
  1496. if (ret !== undefined) {
  1497. var maybePromise = tryConvertToPromise(ret, promise);
  1498. if (maybePromise instanceof Promise) {
  1499. maybePromise = maybePromise._target();
  1500. return promisedFinally(maybePromise, reasonOrValue,
  1501. promise.isFulfilled());
  1502. }
  1503. }
  1504. if (promise.isRejected()) {
  1505. NEXT_FILTER.e = reasonOrValue;
  1506. return NEXT_FILTER;
  1507. } else {
  1508. return reasonOrValue;
  1509. }
  1510. }
  1511. function tapHandler(value) {
  1512. var promise = this.promise;
  1513. var handler = this.handler;
  1514. var ret = promise._isBound()
  1515. ? handler.call(promise._boundValue(), value)
  1516. : handler(value);
  1517. if (ret !== undefined) {
  1518. var maybePromise = tryConvertToPromise(ret, promise);
  1519. if (maybePromise instanceof Promise) {
  1520. maybePromise = maybePromise._target();
  1521. return promisedFinally(maybePromise, value, true);
  1522. }
  1523. }
  1524. return value;
  1525. }
  1526. Promise.prototype._passThroughHandler = function (handler, isFinally) {
  1527. if (typeof handler !== "function") return this.then();
  1528. var promiseAndHandler = {
  1529. promise: this,
  1530. handler: handler
  1531. };
  1532. return this._then(
  1533. isFinally ? finallyHandler : tapHandler,
  1534. isFinally ? finallyHandler : undefined, undefined,
  1535. promiseAndHandler, undefined);
  1536. };
  1537. Promise.prototype.lastly =
  1538. Promise.prototype["finally"] = function (handler) {
  1539. return this._passThroughHandler(handler, true);
  1540. };
  1541. Promise.prototype.tap = function (handler) {
  1542. return this._passThroughHandler(handler, false);
  1543. };
  1544. };
  1545. },{"./util.js":38}],17:[function(_dereq_,module,exports){
  1546. "use strict";
  1547. module.exports = function(Promise,
  1548. apiRejection,
  1549. INTERNAL,
  1550. tryConvertToPromise) {
  1551. var errors = _dereq_("./errors.js");
  1552. var TypeError = errors.TypeError;
  1553. var util = _dereq_("./util.js");
  1554. var errorObj = util.errorObj;
  1555. var tryCatch = util.tryCatch;
  1556. var yieldHandlers = [];
  1557. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  1558. for (var i = 0; i < yieldHandlers.length; ++i) {
  1559. traceParent._pushContext();
  1560. var result = tryCatch(yieldHandlers[i])(value);
  1561. traceParent._popContext();
  1562. if (result === errorObj) {
  1563. traceParent._pushContext();
  1564. var ret = Promise.reject(errorObj.e);
  1565. traceParent._popContext();
  1566. return ret;
  1567. }
  1568. var maybePromise = tryConvertToPromise(result, traceParent);
  1569. if (maybePromise instanceof Promise) return maybePromise;
  1570. }
  1571. return null;
  1572. }
  1573. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  1574. var promise = this._promise = new Promise(INTERNAL);
  1575. promise._captureStackTrace();
  1576. this._stack = stack;
  1577. this._generatorFunction = generatorFunction;
  1578. this._receiver = receiver;
  1579. this._generator = undefined;
  1580. this._yieldHandlers = typeof yieldHandler === "function"
  1581. ? [yieldHandler].concat(yieldHandlers)
  1582. : yieldHandlers;
  1583. }
  1584. PromiseSpawn.prototype.promise = function () {
  1585. return this._promise;
  1586. };
  1587. PromiseSpawn.prototype._run = function () {
  1588. this._generator = this._generatorFunction.call(this._receiver);
  1589. this._receiver =
  1590. this._generatorFunction = undefined;
  1591. this._next(undefined);
  1592. };
  1593. PromiseSpawn.prototype._continue = function (result) {
  1594. if (result === errorObj) {
  1595. return this._promise._rejectCallback(result.e, false, true);
  1596. }
  1597. var value = result.value;
  1598. if (result.done === true) {
  1599. this._promise._resolveCallback(value);
  1600. } else {
  1601. var maybePromise = tryConvertToPromise(value, this._promise);
  1602. if (!(maybePromise instanceof Promise)) {
  1603. maybePromise =
  1604. promiseFromYieldHandler(maybePromise,
  1605. this._yieldHandlers,
  1606. this._promise);
  1607. if (maybePromise === null) {
  1608. this._throw(
  1609. new TypeError(
  1610. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) +
  1611. "From coroutine:\u000a" +
  1612. this._stack.split("\n").slice(1, -7).join("\n")
  1613. )
  1614. );
  1615. return;
  1616. }
  1617. }
  1618. maybePromise._then(
  1619. this._next,
  1620. this._throw,
  1621. undefined,
  1622. this,
  1623. null
  1624. );
  1625. }
  1626. };
  1627. PromiseSpawn.prototype._throw = function (reason) {
  1628. this._promise._attachExtraTrace(reason);
  1629. this._promise._pushContext();
  1630. var result = tryCatch(this._generator["throw"])
  1631. .call(this._generator, reason);
  1632. this._promise._popContext();
  1633. this._continue(result);
  1634. };
  1635. PromiseSpawn.prototype._next = function (value) {
  1636. this._promise._pushContext();
  1637. var result = tryCatch(this._generator.next).call(this._generator, value);
  1638. this._promise._popContext();
  1639. this._continue(result);
  1640. };
  1641. Promise.coroutine = function (generatorFunction, options) {
  1642. if (typeof generatorFunction !== "function") {
  1643. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
  1644. }
  1645. var yieldHandler = Object(options).yieldHandler;
  1646. var PromiseSpawn$ = PromiseSpawn;
  1647. var stack = new Error().stack;
  1648. return function () {
  1649. var generator = generatorFunction.apply(this, arguments);
  1650. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  1651. stack);
  1652. spawn._generator = generator;
  1653. spawn._next(undefined);
  1654. return spawn.promise();
  1655. };
  1656. };
  1657. Promise.coroutine.addYieldHandler = function(fn) {
  1658. if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1659. yieldHandlers.push(fn);
  1660. };
  1661. Promise.spawn = function (generatorFunction) {
  1662. if (typeof generatorFunction !== "function") {
  1663. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
  1664. }
  1665. var spawn = new PromiseSpawn(generatorFunction, this);
  1666. var ret = spawn.promise();
  1667. spawn._run(Promise.spawn);
  1668. return ret;
  1669. };
  1670. };
  1671. },{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
  1672. "use strict";
  1673. module.exports =
  1674. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
  1675. var util = _dereq_("./util.js");
  1676. var canEvaluate = util.canEvaluate;
  1677. var tryCatch = util.tryCatch;
  1678. var errorObj = util.errorObj;
  1679. var reject;
  1680. if (!true) {
  1681. if (canEvaluate) {
  1682. var thenCallback = function(i) {
  1683. return new Function("value", "holder", " \n\
  1684. 'use strict'; \n\
  1685. holder.pIndex = value; \n\
  1686. holder.checkFulfillment(this); \n\
  1687. ".replace(/Index/g, i));
  1688. };
  1689. var caller = function(count) {
  1690. var values = [];
  1691. for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
  1692. return new Function("holder", " \n\
  1693. 'use strict'; \n\
  1694. var callback = holder.fn; \n\
  1695. return callback(values); \n\
  1696. ".replace(/values/g, values.join(", ")));
  1697. };
  1698. var thenCallbacks = [];
  1699. var callers = [undefined];
  1700. for (var i = 1; i <= 5; ++i) {
  1701. thenCallbacks.push(thenCallback(i));
  1702. callers.push(caller(i));
  1703. }
  1704. var Holder = function(total, fn) {
  1705. this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
  1706. this.fn = fn;
  1707. this.total = total;
  1708. this.now = 0;
  1709. };
  1710. Holder.prototype.callers = callers;
  1711. Holder.prototype.checkFulfillment = function(promise) {
  1712. var now = this.now;
  1713. now++;
  1714. var total = this.total;
  1715. if (now >= total) {
  1716. var handler = this.callers[total];
  1717. promise._pushContext();
  1718. var ret = tryCatch(handler)(this);
  1719. promise._popContext();
  1720. if (ret === errorObj) {
  1721. promise._rejectCallback(ret.e, false, true);
  1722. } else {
  1723. promise._resolveCallback(ret);
  1724. }
  1725. } else {
  1726. this.now = now;
  1727. }
  1728. };
  1729. var reject = function (reason) {
  1730. this._reject(reason);
  1731. };
  1732. }
  1733. }
  1734. Promise.join = function () {
  1735. var last = arguments.length - 1;
  1736. var fn;
  1737. if (last > 0 && typeof arguments[last] === "function") {
  1738. fn = arguments[last];
  1739. if (!true) {
  1740. if (last < 6 && canEvaluate) {
  1741. var ret = new Promise(INTERNAL);
  1742. ret._captureStackTrace();
  1743. var holder = new Holder(last, fn);
  1744. var callbacks = thenCallbacks;
  1745. for (var i = 0; i < last; ++i) {
  1746. var maybePromise = tryConvertToPromise(arguments[i], ret);
  1747. if (maybePromise instanceof Promise) {
  1748. maybePromise = maybePromise._target();
  1749. if (maybePromise._isPending()) {
  1750. maybePromise._then(callbacks[i], reject,
  1751. undefined, ret, holder);
  1752. } else if (maybePromise._isFulfilled()) {
  1753. callbacks[i].call(ret,
  1754. maybePromise._value(), holder);
  1755. } else {
  1756. ret._reject(maybePromise._reason());
  1757. }
  1758. } else {
  1759. callbacks[i].call(ret, maybePromise, holder);
  1760. }
  1761. }
  1762. return ret;
  1763. }
  1764. }
  1765. }
  1766. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
  1767. if (fn) args.pop();
  1768. var ret = new PromiseArray(args).promise();
  1769. return fn !== undefined ? ret.spread(fn) : ret;
  1770. };
  1771. };
  1772. },{"./util.js":38}],19:[function(_dereq_,module,exports){
  1773. "use strict";
  1774. module.exports = function(Promise,
  1775. PromiseArray,
  1776. apiRejection,
  1777. tryConvertToPromise,
  1778. INTERNAL) {
  1779. var getDomain = Promise._getDomain;
  1780. var async = _dereq_("./async.js");
  1781. var util = _dereq_("./util.js");
  1782. var tryCatch = util.tryCatch;
  1783. var errorObj = util.errorObj;
  1784. var PENDING = {};
  1785. var EMPTY_ARRAY = [];
  1786. function MappingPromiseArray(promises, fn, limit, _filter) {
  1787. this.constructor$(promises);
  1788. this._promise._captureStackTrace();
  1789. var domain = getDomain();
  1790. this._callback = domain === null ? fn : domain.bind(fn);
  1791. this._preservedValues = _filter === INTERNAL
  1792. ? new Array(this.length())
  1793. : null;
  1794. this._limit = limit;
  1795. this._inFlight = 0;
  1796. this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
  1797. async.invoke(init, this, undefined);
  1798. }
  1799. util.inherits(MappingPromiseArray, PromiseArray);
  1800. function init() {this._init$(undefined, -2);}
  1801. MappingPromiseArray.prototype._init = function () {};
  1802. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  1803. var values = this._values;
  1804. var length = this.length();
  1805. var preservedValues = this._preservedValues;
  1806. var limit = this._limit;
  1807. if (values[index] === PENDING) {
  1808. values[index] = value;
  1809. if (limit >= 1) {
  1810. this._inFlight--;
  1811. this._drainQueue();
  1812. if (this._isResolved()) return;
  1813. }
  1814. } else {
  1815. if (limit >= 1 && this._inFlight >= limit) {
  1816. values[index] = value;
  1817. this._queue.push(index);
  1818. return;
  1819. }
  1820. if (preservedValues !== null) preservedValues[index] = value;
  1821. var callback = this._callback;
  1822. var receiver = this._promise._boundValue();
  1823. this._promise._pushContext();
  1824. var ret = tryCatch(callback).call(receiver, value, index, length);
  1825. this._promise._popContext();
  1826. if (ret === errorObj) return this._reject(ret.e);
  1827. var maybePromise = tryConvertToPromise(ret, this._promise);
  1828. if (maybePromise instanceof Promise) {
  1829. maybePromise = maybePromise._target();
  1830. if (maybePromise._isPending()) {
  1831. if (limit >= 1) this._inFlight++;
  1832. values[index] = PENDING;
  1833. return maybePromise._proxyPromiseArray(this, index);
  1834. } else if (maybePromise._isFulfilled()) {
  1835. ret = maybePromise._value();
  1836. } else {
  1837. return this._reject(maybePromise._reason());
  1838. }
  1839. }
  1840. values[index] = ret;
  1841. }
  1842. var totalResolved = ++this._totalResolved;
  1843. if (totalResolved >= length) {
  1844. if (preservedValues !== null) {
  1845. this._filter(values, preservedValues);
  1846. } else {
  1847. this._resolve(values);
  1848. }
  1849. }
  1850. };
  1851. MappingPromiseArray.prototype._drainQueue = function () {
  1852. var queue = this._queue;
  1853. var limit = this._limit;
  1854. var values = this._values;
  1855. while (queue.length > 0 && this._inFlight < limit) {
  1856. if (this._isResolved()) return;
  1857. var index = queue.pop();
  1858. this._promiseFulfilled(values[index], index);
  1859. }
  1860. };
  1861. MappingPromiseArray.prototype._filter = function (booleans, values) {
  1862. var len = values.length;
  1863. var ret = new Array(len);
  1864. var j = 0;
  1865. for (var i = 0; i < len; ++i) {
  1866. if (booleans[i]) ret[j++] = values[i];
  1867. }
  1868. ret.length = j;
  1869. this._resolve(ret);
  1870. };
  1871. MappingPromiseArray.prototype.preservedValues = function () {
  1872. return this._preservedValues;
  1873. };
  1874. function map(promises, fn, options, _filter) {
  1875. var limit = typeof options === "object" && options !== null
  1876. ? options.concurrency
  1877. : 0;
  1878. limit = typeof limit === "number" &&
  1879. isFinite(limit) && limit >= 1 ? limit : 0;
  1880. return new MappingPromiseArray(promises, fn, limit, _filter);
  1881. }
  1882. Promise.prototype.map = function (fn, options) {
  1883. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1884. return map(this, fn, options, null).promise();
  1885. };
  1886. Promise.map = function (promises, fn, options, _filter) {
  1887. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1888. return map(promises, fn, options, _filter).promise();
  1889. };
  1890. };
  1891. },{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
  1892. "use strict";
  1893. module.exports =
  1894. function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  1895. var util = _dereq_("./util.js");
  1896. var tryCatch = util.tryCatch;
  1897. Promise.method = function (fn) {
  1898. if (typeof fn !== "function") {
  1899. throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1900. }
  1901. return function () {
  1902. var ret = new Promise(INTERNAL);
  1903. ret._captureStackTrace();
  1904. ret._pushContext();
  1905. var value = tryCatch(fn).apply(this, arguments);
  1906. ret._popContext();
  1907. ret._resolveFromSyncValue(value);
  1908. return ret;
  1909. };
  1910. };
  1911. Promise.attempt = Promise["try"] = function (fn, args, ctx) {
  1912. if (typeof fn !== "function") {
  1913. return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  1914. }
  1915. var ret = new Promise(INTERNAL);
  1916. ret._captureStackTrace();
  1917. ret._pushContext();
  1918. var value = util.isArray(args)
  1919. ? tryCatch(fn).apply(ctx, args)
  1920. : tryCatch(fn).call(ctx, args);
  1921. ret._popContext();
  1922. ret._resolveFromSyncValue(value);
  1923. return ret;
  1924. };
  1925. Promise.prototype._resolveFromSyncValue = function (value) {
  1926. if (value === util.errorObj) {
  1927. this._rejectCallback(value.e, false, true);
  1928. } else {
  1929. this._resolveCallback(value, true);
  1930. }
  1931. };
  1932. };
  1933. },{"./util.js":38}],21:[function(_dereq_,module,exports){
  1934. "use strict";
  1935. module.exports = function(Promise) {
  1936. var util = _dereq_("./util.js");
  1937. var async = _dereq_("./async.js");
  1938. var tryCatch = util.tryCatch;
  1939. var errorObj = util.errorObj;
  1940. function spreadAdapter(val, nodeback) {
  1941. var promise = this;
  1942. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  1943. var ret =
  1944. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  1945. if (ret === errorObj) {
  1946. async.throwLater(ret.e);
  1947. }
  1948. }
  1949. function successAdapter(val, nodeback) {
  1950. var promise = this;
  1951. var receiver = promise._boundValue();
  1952. var ret = val === undefined
  1953. ? tryCatch(nodeback).call(receiver, null)
  1954. : tryCatch(nodeback).call(receiver, null, val);
  1955. if (ret === errorObj) {
  1956. async.throwLater(ret.e);
  1957. }
  1958. }
  1959. function errorAdapter(reason, nodeback) {
  1960. var promise = this;
  1961. if (!reason) {
  1962. var target = promise._target();
  1963. var newReason = target._getCarriedStackTrace();
  1964. newReason.cause = reason;
  1965. reason = newReason;
  1966. }
  1967. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  1968. if (ret === errorObj) {
  1969. async.throwLater(ret.e);
  1970. }
  1971. }
  1972. Promise.prototype.asCallback =
  1973. Promise.prototype.nodeify = function (nodeback, options) {
  1974. if (typeof nodeback == "function") {
  1975. var adapter = successAdapter;
  1976. if (options !== undefined && Object(options).spread) {
  1977. adapter = spreadAdapter;
  1978. }
  1979. this._then(
  1980. adapter,
  1981. errorAdapter,
  1982. undefined,
  1983. this,
  1984. nodeback
  1985. );
  1986. }
  1987. return this;
  1988. };
  1989. };
  1990. },{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
  1991. "use strict";
  1992. module.exports = function(Promise, PromiseArray) {
  1993. var util = _dereq_("./util.js");
  1994. var async = _dereq_("./async.js");
  1995. var tryCatch = util.tryCatch;
  1996. var errorObj = util.errorObj;
  1997. Promise.prototype.progressed = function (handler) {
  1998. return this._then(undefined, undefined, handler, undefined, undefined);
  1999. };
  2000. Promise.prototype._progress = function (progressValue) {
  2001. if (this._isFollowingOrFulfilledOrRejected()) return;
  2002. this._target()._progressUnchecked(progressValue);
  2003. };
  2004. Promise.prototype._progressHandlerAt = function (index) {
  2005. return index === 0
  2006. ? this._progressHandler0
  2007. : this[(index << 2) + index - 5 + 2];
  2008. };
  2009. Promise.prototype._doProgressWith = function (progression) {
  2010. var progressValue = progression.value;
  2011. var handler = progression.handler;
  2012. var promise = progression.promise;
  2013. var receiver = progression.receiver;
  2014. var ret = tryCatch(handler).call(receiver, progressValue);
  2015. if (ret === errorObj) {
  2016. if (ret.e != null &&
  2017. ret.e.name !== "StopProgressPropagation") {
  2018. var trace = util.canAttachTrace(ret.e)
  2019. ? ret.e : new Error(util.toString(ret.e));
  2020. promise._attachExtraTrace(trace);
  2021. promise._progress(ret.e);
  2022. }
  2023. } else if (ret instanceof Promise) {
  2024. ret._then(promise._progress, null, null, promise, undefined);
  2025. } else {
  2026. promise._progress(ret);
  2027. }
  2028. };
  2029. Promise.prototype._progressUnchecked = function (progressValue) {
  2030. var len = this._length();
  2031. var progress = this._progress;
  2032. for (var i = 0; i < len; i++) {
  2033. var handler = this._progressHandlerAt(i);
  2034. var promise = this._promiseAt(i);
  2035. if (!(promise instanceof Promise)) {
  2036. var receiver = this._receiverAt(i);
  2037. if (typeof handler === "function") {
  2038. handler.call(receiver, progressValue, promise);
  2039. } else if (receiver instanceof PromiseArray &&
  2040. !receiver._isResolved()) {
  2041. receiver._promiseProgressed(progressValue, promise);
  2042. }
  2043. continue;
  2044. }
  2045. if (typeof handler === "function") {
  2046. async.invoke(this._doProgressWith, this, {
  2047. handler: handler,
  2048. promise: promise,
  2049. receiver: this._receiverAt(i),
  2050. value: progressValue
  2051. });
  2052. } else {
  2053. async.invoke(progress, promise, progressValue);
  2054. }
  2055. }
  2056. };
  2057. };
  2058. },{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
  2059. "use strict";
  2060. module.exports = function() {
  2061. var makeSelfResolutionError = function () {
  2062. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a");
  2063. };
  2064. var reflect = function() {
  2065. return new Promise.PromiseInspection(this._target());
  2066. };
  2067. var apiRejection = function(msg) {
  2068. return Promise.reject(new TypeError(msg));
  2069. };
  2070. var util = _dereq_("./util.js");
  2071. var getDomain;
  2072. if (util.isNode) {
  2073. getDomain = function() {
  2074. var ret = process.domain;
  2075. if (ret === undefined) ret = null;
  2076. return ret;
  2077. };
  2078. } else {
  2079. getDomain = function() {
  2080. return null;
  2081. };
  2082. }
  2083. util.notEnumerableProp(Promise, "_getDomain", getDomain);
  2084. var UNDEFINED_BINDING = {};
  2085. var async = _dereq_("./async.js");
  2086. var errors = _dereq_("./errors.js");
  2087. var TypeError = Promise.TypeError = errors.TypeError;
  2088. Promise.RangeError = errors.RangeError;
  2089. Promise.CancellationError = errors.CancellationError;
  2090. Promise.TimeoutError = errors.TimeoutError;
  2091. Promise.OperationalError = errors.OperationalError;
  2092. Promise.RejectionError = errors.OperationalError;
  2093. Promise.AggregateError = errors.AggregateError;
  2094. var INTERNAL = function(){};
  2095. var APPLY = {};
  2096. var NEXT_FILTER = {e: null};
  2097. var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
  2098. var PromiseArray =
  2099. _dereq_("./promise_array.js")(Promise, INTERNAL,
  2100. tryConvertToPromise, apiRejection);
  2101. var CapturedTrace = _dereq_("./captured_trace.js")();
  2102. var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
  2103. /*jshint unused:false*/
  2104. var createContext =
  2105. _dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
  2106. var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
  2107. var PromiseResolver = _dereq_("./promise_resolver.js");
  2108. var nodebackForPromise = PromiseResolver._nodebackForPromise;
  2109. var errorObj = util.errorObj;
  2110. var tryCatch = util.tryCatch;
  2111. function Promise(resolver) {
  2112. if (typeof resolver !== "function") {
  2113. throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a");
  2114. }
  2115. if (this.constructor !== Promise) {
  2116. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a");
  2117. }
  2118. this._bitField = 0;
  2119. this._fulfillmentHandler0 = undefined;
  2120. this._rejectionHandler0 = undefined;
  2121. this._progressHandler0 = undefined;
  2122. this._promise0 = undefined;
  2123. this._receiver0 = undefined;
  2124. this._settledValue = undefined;
  2125. if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
  2126. }
  2127. Promise.prototype.toString = function () {
  2128. return "[object Promise]";
  2129. };
  2130. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  2131. var len = arguments.length;
  2132. if (len > 1) {
  2133. var catchInstances = new Array(len - 1),
  2134. j = 0, i;
  2135. for (i = 0; i < len - 1; ++i) {
  2136. var item = arguments[i];
  2137. if (typeof item === "function") {
  2138. catchInstances[j++] = item;
  2139. } else {
  2140. return Promise.reject(
  2141. new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"));
  2142. }
  2143. }
  2144. catchInstances.length = j;
  2145. fn = arguments[i];
  2146. var catchFilter = new CatchFilter(catchInstances, fn, this);
  2147. return this._then(undefined, catchFilter.doFilter, undefined,
  2148. catchFilter, undefined);
  2149. }
  2150. return this._then(undefined, fn, undefined, undefined, undefined);
  2151. };
  2152. Promise.prototype.reflect = function () {
  2153. return this._then(reflect, reflect, undefined, this, undefined);
  2154. };
  2155. Promise.prototype.then = function (didFulfill, didReject, didProgress) {
  2156. if (isDebugging() && arguments.length > 0 &&
  2157. typeof didFulfill !== "function" &&
  2158. typeof didReject !== "function") {
  2159. var msg = ".then() only accepts functions but was passed: " +
  2160. util.classString(didFulfill);
  2161. if (arguments.length > 1) {
  2162. msg += ", " + util.classString(didReject);
  2163. }
  2164. this._warn(msg);
  2165. }
  2166. return this._then(didFulfill, didReject, didProgress,
  2167. undefined, undefined);
  2168. };
  2169. Promise.prototype.done = function (didFulfill, didReject, didProgress) {
  2170. var promise = this._then(didFulfill, didReject, didProgress,
  2171. undefined, undefined);
  2172. promise._setIsFinal();
  2173. };
  2174. Promise.prototype.spread = function (didFulfill, didReject) {
  2175. return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
  2176. };
  2177. Promise.prototype.isCancellable = function () {
  2178. return !this.isResolved() &&
  2179. this._cancellable();
  2180. };
  2181. Promise.prototype.toJSON = function () {
  2182. var ret = {
  2183. isFulfilled: false,
  2184. isRejected: false,
  2185. fulfillmentValue: undefined,
  2186. rejectionReason: undefined
  2187. };
  2188. if (this.isFulfilled()) {
  2189. ret.fulfillmentValue = this.value();
  2190. ret.isFulfilled = true;
  2191. } else if (this.isRejected()) {
  2192. ret.rejectionReason = this.reason();
  2193. ret.isRejected = true;
  2194. }
  2195. return ret;
  2196. };
  2197. Promise.prototype.all = function () {
  2198. return new PromiseArray(this).promise();
  2199. };
  2200. Promise.prototype.error = function (fn) {
  2201. return this.caught(util.originatesFromRejection, fn);
  2202. };
  2203. Promise.getNewLibraryCopy = module.exports;
  2204. Promise.is = function (val) {
  2205. return val instanceof Promise;
  2206. };
  2207. Promise.fromNode = function(fn) {
  2208. var ret = new Promise(INTERNAL);
  2209. var result = tryCatch(fn)(nodebackForPromise(ret));
  2210. if (result === errorObj) {
  2211. ret._rejectCallback(result.e, true, true);
  2212. }
  2213. return ret;
  2214. };
  2215. Promise.all = function (promises) {
  2216. return new PromiseArray(promises).promise();
  2217. };
  2218. Promise.defer = Promise.pending = function () {
  2219. var promise = new Promise(INTERNAL);
  2220. return new PromiseResolver(promise);
  2221. };
  2222. Promise.cast = function (obj) {
  2223. var ret = tryConvertToPromise(obj);
  2224. if (!(ret instanceof Promise)) {
  2225. var val = ret;
  2226. ret = new Promise(INTERNAL);
  2227. ret._fulfillUnchecked(val);
  2228. }
  2229. return ret;
  2230. };
  2231. Promise.resolve = Promise.fulfilled = Promise.cast;
  2232. Promise.reject = Promise.rejected = function (reason) {
  2233. var ret = new Promise(INTERNAL);
  2234. ret._captureStackTrace();
  2235. ret._rejectCallback(reason, true);
  2236. return ret;
  2237. };
  2238. Promise.setScheduler = function(fn) {
  2239. if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  2240. var prev = async._schedule;
  2241. async._schedule = fn;
  2242. return prev;
  2243. };
  2244. Promise.prototype._then = function (
  2245. didFulfill,
  2246. didReject,
  2247. didProgress,
  2248. receiver,
  2249. internalData
  2250. ) {
  2251. var haveInternalData = internalData !== undefined;
  2252. var ret = haveInternalData ? internalData : new Promise(INTERNAL);
  2253. if (!haveInternalData) {
  2254. ret._propagateFrom(this, 4 | 1);
  2255. ret._captureStackTrace();
  2256. }
  2257. var target = this._target();
  2258. if (target !== this) {
  2259. if (receiver === undefined) receiver = this._boundTo;
  2260. if (!haveInternalData) ret._setIsMigrated();
  2261. }
  2262. var callbackIndex = target._addCallbacks(didFulfill,
  2263. didReject,
  2264. didProgress,
  2265. ret,
  2266. receiver,
  2267. getDomain());
  2268. if (target._isResolved() && !target._isSettlePromisesQueued()) {
  2269. async.invoke(
  2270. target._settlePromiseAtPostResolution, target, callbackIndex);
  2271. }
  2272. return ret;
  2273. };
  2274. Promise.prototype._settlePromiseAtPostResolution = function (index) {
  2275. if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
  2276. this._settlePromiseAt(index);
  2277. };
  2278. Promise.prototype._length = function () {
  2279. return this._bitField & 131071;
  2280. };
  2281. Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
  2282. return (this._bitField & 939524096) > 0;
  2283. };
  2284. Promise.prototype._isFollowing = function () {
  2285. return (this._bitField & 536870912) === 536870912;
  2286. };
  2287. Promise.prototype._setLength = function (len) {
  2288. this._bitField = (this._bitField & -131072) |
  2289. (len & 131071);
  2290. };
  2291. Promise.prototype._setFulfilled = function () {
  2292. this._bitField = this._bitField | 268435456;
  2293. };
  2294. Promise.prototype._setRejected = function () {
  2295. this._bitField = this._bitField | 134217728;
  2296. };
  2297. Promise.prototype._setFollowing = function () {
  2298. this._bitField = this._bitField | 536870912;
  2299. };
  2300. Promise.prototype._setIsFinal = function () {
  2301. this._bitField = this._bitField | 33554432;
  2302. };
  2303. Promise.prototype._isFinal = function () {
  2304. return (this._bitField & 33554432) > 0;
  2305. };
  2306. Promise.prototype._cancellable = function () {
  2307. return (this._bitField & 67108864) > 0;
  2308. };
  2309. Promise.prototype._setCancellable = function () {
  2310. this._bitField = this._bitField | 67108864;
  2311. };
  2312. Promise.prototype._unsetCancellable = function () {
  2313. this._bitField = this._bitField & (~67108864);
  2314. };
  2315. Promise.prototype._setIsMigrated = function () {
  2316. this._bitField = this._bitField | 4194304;
  2317. };
  2318. Promise.prototype._unsetIsMigrated = function () {
  2319. this._bitField = this._bitField & (~4194304);
  2320. };
  2321. Promise.prototype._isMigrated = function () {
  2322. return (this._bitField & 4194304) > 0;
  2323. };
  2324. Promise.prototype._receiverAt = function (index) {
  2325. var ret = index === 0
  2326. ? this._receiver0
  2327. : this[
  2328. index * 5 - 5 + 4];
  2329. if (ret === UNDEFINED_BINDING) {
  2330. return undefined;
  2331. } else if (ret === undefined && this._isBound()) {
  2332. return this._boundValue();
  2333. }
  2334. return ret;
  2335. };
  2336. Promise.prototype._promiseAt = function (index) {
  2337. return index === 0
  2338. ? this._promise0
  2339. : this[index * 5 - 5 + 3];
  2340. };
  2341. Promise.prototype._fulfillmentHandlerAt = function (index) {
  2342. return index === 0
  2343. ? this._fulfillmentHandler0
  2344. : this[index * 5 - 5 + 0];
  2345. };
  2346. Promise.prototype._rejectionHandlerAt = function (index) {
  2347. return index === 0
  2348. ? this._rejectionHandler0
  2349. : this[index * 5 - 5 + 1];
  2350. };
  2351. Promise.prototype._boundValue = function() {
  2352. var ret = this._boundTo;
  2353. if (ret !== undefined) {
  2354. if (ret instanceof Promise) {
  2355. if (ret.isFulfilled()) {
  2356. return ret.value();
  2357. } else {
  2358. return undefined;
  2359. }
  2360. }
  2361. }
  2362. return ret;
  2363. };
  2364. Promise.prototype._migrateCallbacks = function (follower, index) {
  2365. var fulfill = follower._fulfillmentHandlerAt(index);
  2366. var reject = follower._rejectionHandlerAt(index);
  2367. var progress = follower._progressHandlerAt(index);
  2368. var promise = follower._promiseAt(index);
  2369. var receiver = follower._receiverAt(index);
  2370. if (promise instanceof Promise) promise._setIsMigrated();
  2371. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  2372. this._addCallbacks(fulfill, reject, progress, promise, receiver, null);
  2373. };
  2374. Promise.prototype._addCallbacks = function (
  2375. fulfill,
  2376. reject,
  2377. progress,
  2378. promise,
  2379. receiver,
  2380. domain
  2381. ) {
  2382. var index = this._length();
  2383. if (index >= 131071 - 5) {
  2384. index = 0;
  2385. this._setLength(0);
  2386. }
  2387. if (index === 0) {
  2388. this._promise0 = promise;
  2389. if (receiver !== undefined) this._receiver0 = receiver;
  2390. if (typeof fulfill === "function" && !this._isCarryingStackTrace()) {
  2391. this._fulfillmentHandler0 =
  2392. domain === null ? fulfill : domain.bind(fulfill);
  2393. }
  2394. if (typeof reject === "function") {
  2395. this._rejectionHandler0 =
  2396. domain === null ? reject : domain.bind(reject);
  2397. }
  2398. if (typeof progress === "function") {
  2399. this._progressHandler0 =
  2400. domain === null ? progress : domain.bind(progress);
  2401. }
  2402. } else {
  2403. var base = index * 5 - 5;
  2404. this[base + 3] = promise;
  2405. this[base + 4] = receiver;
  2406. if (typeof fulfill === "function") {
  2407. this[base + 0] =
  2408. domain === null ? fulfill : domain.bind(fulfill);
  2409. }
  2410. if (typeof reject === "function") {
  2411. this[base + 1] =
  2412. domain === null ? reject : domain.bind(reject);
  2413. }
  2414. if (typeof progress === "function") {
  2415. this[base + 2] =
  2416. domain === null ? progress : domain.bind(progress);
  2417. }
  2418. }
  2419. this._setLength(index + 1);
  2420. return index;
  2421. };
  2422. Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
  2423. var index = this._length();
  2424. if (index >= 131071 - 5) {
  2425. index = 0;
  2426. this._setLength(0);
  2427. }
  2428. if (index === 0) {
  2429. this._promise0 = promiseSlotValue;
  2430. this._receiver0 = receiver;
  2431. } else {
  2432. var base = index * 5 - 5;
  2433. this[base + 3] = promiseSlotValue;
  2434. this[base + 4] = receiver;
  2435. }
  2436. this._setLength(index + 1);
  2437. };
  2438. Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
  2439. this._setProxyHandlers(promiseArray, index);
  2440. };
  2441. Promise.prototype._resolveCallback = function(value, shouldBind) {
  2442. if (this._isFollowingOrFulfilledOrRejected()) return;
  2443. if (value === this)
  2444. return this._rejectCallback(makeSelfResolutionError(), false, true);
  2445. var maybePromise = tryConvertToPromise(value, this);
  2446. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  2447. var propagationFlags = 1 | (shouldBind ? 4 : 0);
  2448. this._propagateFrom(maybePromise, propagationFlags);
  2449. var promise = maybePromise._target();
  2450. if (promise._isPending()) {
  2451. var len = this._length();
  2452. for (var i = 0; i < len; ++i) {
  2453. promise._migrateCallbacks(this, i);
  2454. }
  2455. this._setFollowing();
  2456. this._setLength(0);
  2457. this._setFollowee(promise);
  2458. } else if (promise._isFulfilled()) {
  2459. this._fulfillUnchecked(promise._value());
  2460. } else {
  2461. this._rejectUnchecked(promise._reason(),
  2462. promise._getCarriedStackTrace());
  2463. }
  2464. };
  2465. Promise.prototype._rejectCallback =
  2466. function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
  2467. if (!shouldNotMarkOriginatingFromRejection) {
  2468. util.markAsOriginatingFromRejection(reason);
  2469. }
  2470. var trace = util.ensureErrorObject(reason);
  2471. var hasStack = trace === reason;
  2472. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  2473. this._reject(reason, hasStack ? undefined : trace);
  2474. };
  2475. Promise.prototype._resolveFromResolver = function (resolver) {
  2476. var promise = this;
  2477. this._captureStackTrace();
  2478. this._pushContext();
  2479. var synchronous = true;
  2480. var r = tryCatch(resolver)(function(value) {
  2481. if (promise === null) return;
  2482. promise._resolveCallback(value);
  2483. promise = null;
  2484. }, function (reason) {
  2485. if (promise === null) return;
  2486. promise._rejectCallback(reason, synchronous);
  2487. promise = null;
  2488. });
  2489. synchronous = false;
  2490. this._popContext();
  2491. if (r !== undefined && r === errorObj && promise !== null) {
  2492. promise._rejectCallback(r.e, true, true);
  2493. promise = null;
  2494. }
  2495. };
  2496. Promise.prototype._settlePromiseFromHandler = function (
  2497. handler, receiver, value, promise
  2498. ) {
  2499. if (promise._isRejected()) return;
  2500. promise._pushContext();
  2501. var x;
  2502. if (receiver === APPLY && !this._isRejected()) {
  2503. x = tryCatch(handler).apply(this._boundValue(), value);
  2504. } else {
  2505. x = tryCatch(handler).call(receiver, value);
  2506. }
  2507. promise._popContext();
  2508. if (x === errorObj || x === promise || x === NEXT_FILTER) {
  2509. var err = x === promise ? makeSelfResolutionError() : x.e;
  2510. promise._rejectCallback(err, false, true);
  2511. } else {
  2512. promise._resolveCallback(x);
  2513. }
  2514. };
  2515. Promise.prototype._target = function() {
  2516. var ret = this;
  2517. while (ret._isFollowing()) ret = ret._followee();
  2518. return ret;
  2519. };
  2520. Promise.prototype._followee = function() {
  2521. return this._rejectionHandler0;
  2522. };
  2523. Promise.prototype._setFollowee = function(promise) {
  2524. this._rejectionHandler0 = promise;
  2525. };
  2526. Promise.prototype._cleanValues = function () {
  2527. if (this._cancellable()) {
  2528. this._cancellationParent = undefined;
  2529. }
  2530. };
  2531. Promise.prototype._propagateFrom = function (parent, flags) {
  2532. if ((flags & 1) > 0 && parent._cancellable()) {
  2533. this._setCancellable();
  2534. this._cancellationParent = parent;
  2535. }
  2536. if ((flags & 4) > 0 && parent._isBound()) {
  2537. this._setBoundTo(parent._boundTo);
  2538. }
  2539. };
  2540. Promise.prototype._fulfill = function (value) {
  2541. if (this._isFollowingOrFulfilledOrRejected()) return;
  2542. this._fulfillUnchecked(value);
  2543. };
  2544. Promise.prototype._reject = function (reason, carriedStackTrace) {
  2545. if (this._isFollowingOrFulfilledOrRejected()) return;
  2546. this._rejectUnchecked(reason, carriedStackTrace);
  2547. };
  2548. Promise.prototype._settlePromiseAt = function (index) {
  2549. var promise = this._promiseAt(index);
  2550. var isPromise = promise instanceof Promise;
  2551. if (isPromise && promise._isMigrated()) {
  2552. promise._unsetIsMigrated();
  2553. return async.invoke(this._settlePromiseAt, this, index);
  2554. }
  2555. var handler = this._isFulfilled()
  2556. ? this._fulfillmentHandlerAt(index)
  2557. : this._rejectionHandlerAt(index);
  2558. var carriedStackTrace =
  2559. this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
  2560. var value = this._settledValue;
  2561. var receiver = this._receiverAt(index);
  2562. this._clearCallbackDataAtIndex(index);
  2563. if (typeof handler === "function") {
  2564. if (!isPromise) {
  2565. handler.call(receiver, value, promise);
  2566. } else {
  2567. this._settlePromiseFromHandler(handler, receiver, value, promise);
  2568. }
  2569. } else if (receiver instanceof PromiseArray) {
  2570. if (!receiver._isResolved()) {
  2571. if (this._isFulfilled()) {
  2572. receiver._promiseFulfilled(value, promise);
  2573. }
  2574. else {
  2575. receiver._promiseRejected(value, promise);
  2576. }
  2577. }
  2578. } else if (isPromise) {
  2579. if (this._isFulfilled()) {
  2580. promise._fulfill(value);
  2581. } else {
  2582. promise._reject(value, carriedStackTrace);
  2583. }
  2584. }
  2585. if (index >= 4 && (index & 31) === 4)
  2586. async.invokeLater(this._setLength, this, 0);
  2587. };
  2588. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  2589. if (index === 0) {
  2590. if (!this._isCarryingStackTrace()) {
  2591. this._fulfillmentHandler0 = undefined;
  2592. }
  2593. this._rejectionHandler0 =
  2594. this._progressHandler0 =
  2595. this._receiver0 =
  2596. this._promise0 = undefined;
  2597. } else {
  2598. var base = index * 5 - 5;
  2599. this[base + 3] =
  2600. this[base + 4] =
  2601. this[base + 0] =
  2602. this[base + 1] =
  2603. this[base + 2] = undefined;
  2604. }
  2605. };
  2606. Promise.prototype._isSettlePromisesQueued = function () {
  2607. return (this._bitField &
  2608. -1073741824) === -1073741824;
  2609. };
  2610. Promise.prototype._setSettlePromisesQueued = function () {
  2611. this._bitField = this._bitField | -1073741824;
  2612. };
  2613. Promise.prototype._unsetSettlePromisesQueued = function () {
  2614. this._bitField = this._bitField & (~-1073741824);
  2615. };
  2616. Promise.prototype._queueSettlePromises = function() {
  2617. async.settlePromises(this);
  2618. this._setSettlePromisesQueued();
  2619. };
  2620. Promise.prototype._fulfillUnchecked = function (value) {
  2621. if (value === this) {
  2622. var err = makeSelfResolutionError();
  2623. this._attachExtraTrace(err);
  2624. return this._rejectUnchecked(err, undefined);
  2625. }
  2626. this._setFulfilled();
  2627. this._settledValue = value;
  2628. this._cleanValues();
  2629. if (this._length() > 0) {
  2630. this._queueSettlePromises();
  2631. }
  2632. };
  2633. Promise.prototype._rejectUncheckedCheckError = function (reason) {
  2634. var trace = util.ensureErrorObject(reason);
  2635. this._rejectUnchecked(reason, trace === reason ? undefined : trace);
  2636. };
  2637. Promise.prototype._rejectUnchecked = function (reason, trace) {
  2638. if (reason === this) {
  2639. var err = makeSelfResolutionError();
  2640. this._attachExtraTrace(err);
  2641. return this._rejectUnchecked(err);
  2642. }
  2643. this._setRejected();
  2644. this._settledValue = reason;
  2645. this._cleanValues();
  2646. if (this._isFinal()) {
  2647. async.throwLater(function(e) {
  2648. if ("stack" in e) {
  2649. async.invokeFirst(
  2650. CapturedTrace.unhandledRejection, undefined, e);
  2651. }
  2652. throw e;
  2653. }, trace === undefined ? reason : trace);
  2654. return;
  2655. }
  2656. if (trace !== undefined && trace !== reason) {
  2657. this._setCarriedStackTrace(trace);
  2658. }
  2659. if (this._length() > 0) {
  2660. this._queueSettlePromises();
  2661. } else {
  2662. this._ensurePossibleRejectionHandled();
  2663. }
  2664. };
  2665. Promise.prototype._settlePromises = function () {
  2666. this._unsetSettlePromisesQueued();
  2667. var len = this._length();
  2668. for (var i = 0; i < len; i++) {
  2669. this._settlePromiseAt(i);
  2670. }
  2671. };
  2672. util.notEnumerableProp(Promise,
  2673. "_makeSelfResolutionError",
  2674. makeSelfResolutionError);
  2675. _dereq_("./progress.js")(Promise, PromiseArray);
  2676. _dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  2677. _dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
  2678. _dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
  2679. _dereq_("./direct_resolve.js")(Promise);
  2680. _dereq_("./synchronous_inspection.js")(Promise);
  2681. _dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
  2682. Promise.version = "2.11.0";
  2683. Promise.Promise = Promise;
  2684. _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
  2685. _dereq_('./cancel.js')(Promise);
  2686. _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
  2687. _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
  2688. _dereq_('./nodeify.js')(Promise);
  2689. _dereq_('./call_get.js')(Promise);
  2690. _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  2691. _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  2692. _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
  2693. _dereq_('./settle.js')(Promise, PromiseArray);
  2694. _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
  2695. _dereq_('./promisify.js')(Promise, INTERNAL);
  2696. _dereq_('./any.js')(Promise);
  2697. _dereq_('./each.js')(Promise, INTERNAL);
  2698. _dereq_('./timers.js')(Promise, INTERNAL);
  2699. _dereq_('./filter.js')(Promise, INTERNAL);
  2700. util.toFastProperties(Promise);
  2701. util.toFastProperties(Promise.prototype);
  2702. function fillTypes(value) {
  2703. var p = new Promise(INTERNAL);
  2704. p._fulfillmentHandler0 = value;
  2705. p._rejectionHandler0 = value;
  2706. p._progressHandler0 = value;
  2707. p._promise0 = value;
  2708. p._receiver0 = value;
  2709. p._settledValue = value;
  2710. }
  2711. // Complete slack tracking, opt out of field-type tracking and
  2712. // stabilize map
  2713. fillTypes({a: 1});
  2714. fillTypes({b: 2});
  2715. fillTypes({c: 3});
  2716. fillTypes(1);
  2717. fillTypes(function(){});
  2718. fillTypes(undefined);
  2719. fillTypes(false);
  2720. fillTypes(new Promise(INTERNAL));
  2721. CapturedTrace.setBounds(async.firstLineError, util.lastLineError);
  2722. return Promise;
  2723. };
  2724. },{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){
  2725. "use strict";
  2726. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  2727. apiRejection) {
  2728. var util = _dereq_("./util.js");
  2729. var isArray = util.isArray;
  2730. function toResolutionValue(val) {
  2731. switch(val) {
  2732. case -2: return [];
  2733. case -3: return {};
  2734. }
  2735. }
  2736. function PromiseArray(values) {
  2737. var promise = this._promise = new Promise(INTERNAL);
  2738. var parent;
  2739. if (values instanceof Promise) {
  2740. parent = values;
  2741. promise._propagateFrom(parent, 1 | 4);
  2742. }
  2743. this._values = values;
  2744. this._length = 0;
  2745. this._totalResolved = 0;
  2746. this._init(undefined, -2);
  2747. }
  2748. PromiseArray.prototype.length = function () {
  2749. return this._length;
  2750. };
  2751. PromiseArray.prototype.promise = function () {
  2752. return this._promise;
  2753. };
  2754. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  2755. var values = tryConvertToPromise(this._values, this._promise);
  2756. if (values instanceof Promise) {
  2757. values = values._target();
  2758. this._values = values;
  2759. if (values._isFulfilled()) {
  2760. values = values._value();
  2761. if (!isArray(values)) {
  2762. var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
  2763. this.__hardReject__(err);
  2764. return;
  2765. }
  2766. } else if (values._isPending()) {
  2767. values._then(
  2768. init,
  2769. this._reject,
  2770. undefined,
  2771. this,
  2772. resolveValueIfEmpty
  2773. );
  2774. return;
  2775. } else {
  2776. this._reject(values._reason());
  2777. return;
  2778. }
  2779. } else if (!isArray(values)) {
  2780. this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason());
  2781. return;
  2782. }
  2783. if (values.length === 0) {
  2784. if (resolveValueIfEmpty === -5) {
  2785. this._resolveEmptyArray();
  2786. }
  2787. else {
  2788. this._resolve(toResolutionValue(resolveValueIfEmpty));
  2789. }
  2790. return;
  2791. }
  2792. var len = this.getActualLength(values.length);
  2793. this._length = len;
  2794. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  2795. var promise = this._promise;
  2796. for (var i = 0; i < len; ++i) {
  2797. var isResolved = this._isResolved();
  2798. var maybePromise = tryConvertToPromise(values[i], promise);
  2799. if (maybePromise instanceof Promise) {
  2800. maybePromise = maybePromise._target();
  2801. if (isResolved) {
  2802. maybePromise._ignoreRejections();
  2803. } else if (maybePromise._isPending()) {
  2804. maybePromise._proxyPromiseArray(this, i);
  2805. } else if (maybePromise._isFulfilled()) {
  2806. this._promiseFulfilled(maybePromise._value(), i);
  2807. } else {
  2808. this._promiseRejected(maybePromise._reason(), i);
  2809. }
  2810. } else if (!isResolved) {
  2811. this._promiseFulfilled(maybePromise, i);
  2812. }
  2813. }
  2814. };
  2815. PromiseArray.prototype._isResolved = function () {
  2816. return this._values === null;
  2817. };
  2818. PromiseArray.prototype._resolve = function (value) {
  2819. this._values = null;
  2820. this._promise._fulfill(value);
  2821. };
  2822. PromiseArray.prototype.__hardReject__ =
  2823. PromiseArray.prototype._reject = function (reason) {
  2824. this._values = null;
  2825. this._promise._rejectCallback(reason, false, true);
  2826. };
  2827. PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
  2828. this._promise._progress({
  2829. index: index,
  2830. value: progressValue
  2831. });
  2832. };
  2833. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  2834. this._values[index] = value;
  2835. var totalResolved = ++this._totalResolved;
  2836. if (totalResolved >= this._length) {
  2837. this._resolve(this._values);
  2838. }
  2839. };
  2840. PromiseArray.prototype._promiseRejected = function (reason, index) {
  2841. this._totalResolved++;
  2842. this._reject(reason);
  2843. };
  2844. PromiseArray.prototype.shouldCopyValues = function () {
  2845. return true;
  2846. };
  2847. PromiseArray.prototype.getActualLength = function (len) {
  2848. return len;
  2849. };
  2850. return PromiseArray;
  2851. };
  2852. },{"./util.js":38}],25:[function(_dereq_,module,exports){
  2853. "use strict";
  2854. var util = _dereq_("./util.js");
  2855. var maybeWrapAsError = util.maybeWrapAsError;
  2856. var errors = _dereq_("./errors.js");
  2857. var TimeoutError = errors.TimeoutError;
  2858. var OperationalError = errors.OperationalError;
  2859. var haveGetters = util.haveGetters;
  2860. var es5 = _dereq_("./es5.js");
  2861. function isUntypedError(obj) {
  2862. return obj instanceof Error &&
  2863. es5.getPrototypeOf(obj) === Error.prototype;
  2864. }
  2865. var rErrorKey = /^(?:name|message|stack|cause)$/;
  2866. function wrapAsOperationalError(obj) {
  2867. var ret;
  2868. if (isUntypedError(obj)) {
  2869. ret = new OperationalError(obj);
  2870. ret.name = obj.name;
  2871. ret.message = obj.message;
  2872. ret.stack = obj.stack;
  2873. var keys = es5.keys(obj);
  2874. for (var i = 0; i < keys.length; ++i) {
  2875. var key = keys[i];
  2876. if (!rErrorKey.test(key)) {
  2877. ret[key] = obj[key];
  2878. }
  2879. }
  2880. return ret;
  2881. }
  2882. util.markAsOriginatingFromRejection(obj);
  2883. return obj;
  2884. }
  2885. function nodebackForPromise(promise) {
  2886. return function(err, value) {
  2887. if (promise === null) return;
  2888. if (err) {
  2889. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  2890. promise._attachExtraTrace(wrapped);
  2891. promise._reject(wrapped);
  2892. } else if (arguments.length > 2) {
  2893. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  2894. promise._fulfill(args);
  2895. } else {
  2896. promise._fulfill(value);
  2897. }
  2898. promise = null;
  2899. };
  2900. }
  2901. var PromiseResolver;
  2902. if (!haveGetters) {
  2903. PromiseResolver = function (promise) {
  2904. this.promise = promise;
  2905. this.asCallback = nodebackForPromise(promise);
  2906. this.callback = this.asCallback;
  2907. };
  2908. }
  2909. else {
  2910. PromiseResolver = function (promise) {
  2911. this.promise = promise;
  2912. };
  2913. }
  2914. if (haveGetters) {
  2915. var prop = {
  2916. get: function() {
  2917. return nodebackForPromise(this.promise);
  2918. }
  2919. };
  2920. es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
  2921. es5.defineProperty(PromiseResolver.prototype, "callback", prop);
  2922. }
  2923. PromiseResolver._nodebackForPromise = nodebackForPromise;
  2924. PromiseResolver.prototype.toString = function () {
  2925. return "[object PromiseResolver]";
  2926. };
  2927. PromiseResolver.prototype.resolve =
  2928. PromiseResolver.prototype.fulfill = function (value) {
  2929. if (!(this instanceof PromiseResolver)) {
  2930. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
  2931. }
  2932. this.promise._resolveCallback(value);
  2933. };
  2934. PromiseResolver.prototype.reject = function (reason) {
  2935. if (!(this instanceof PromiseResolver)) {
  2936. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
  2937. }
  2938. this.promise._rejectCallback(reason);
  2939. };
  2940. PromiseResolver.prototype.progress = function (value) {
  2941. if (!(this instanceof PromiseResolver)) {
  2942. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
  2943. }
  2944. this.promise._progress(value);
  2945. };
  2946. PromiseResolver.prototype.cancel = function (err) {
  2947. this.promise.cancel(err);
  2948. };
  2949. PromiseResolver.prototype.timeout = function () {
  2950. this.reject(new TimeoutError("timeout"));
  2951. };
  2952. PromiseResolver.prototype.isResolved = function () {
  2953. return this.promise.isResolved();
  2954. };
  2955. PromiseResolver.prototype.toJSON = function () {
  2956. return this.promise.toJSON();
  2957. };
  2958. module.exports = PromiseResolver;
  2959. },{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
  2960. "use strict";
  2961. module.exports = function(Promise, INTERNAL) {
  2962. var THIS = {};
  2963. var util = _dereq_("./util.js");
  2964. var nodebackForPromise = _dereq_("./promise_resolver.js")
  2965. ._nodebackForPromise;
  2966. var withAppended = util.withAppended;
  2967. var maybeWrapAsError = util.maybeWrapAsError;
  2968. var canEvaluate = util.canEvaluate;
  2969. var TypeError = _dereq_("./errors").TypeError;
  2970. var defaultSuffix = "Async";
  2971. var defaultPromisified = {__isPromisified__: true};
  2972. var noCopyProps = [
  2973. "arity", "length",
  2974. "name",
  2975. "arguments",
  2976. "caller",
  2977. "callee",
  2978. "prototype",
  2979. "__isPromisified__"
  2980. ];
  2981. var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  2982. var defaultFilter = function(name) {
  2983. return util.isIdentifier(name) &&
  2984. name.charAt(0) !== "_" &&
  2985. name !== "constructor";
  2986. };
  2987. function propsFilter(key) {
  2988. return !noCopyPropsPattern.test(key);
  2989. }
  2990. function isPromisified(fn) {
  2991. try {
  2992. return fn.__isPromisified__ === true;
  2993. }
  2994. catch (e) {
  2995. return false;
  2996. }
  2997. }
  2998. function hasPromisified(obj, key, suffix) {
  2999. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  3000. defaultPromisified);
  3001. return val ? isPromisified(val) : false;
  3002. }
  3003. function checkValid(ret, suffix, suffixRegexp) {
  3004. for (var i = 0; i < ret.length; i += 2) {
  3005. var key = ret[i];
  3006. if (suffixRegexp.test(key)) {
  3007. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  3008. for (var j = 0; j < ret.length; j += 2) {
  3009. if (ret[j] === keyWithoutAsyncSuffix) {
  3010. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a"
  3011. .replace("%s", suffix));
  3012. }
  3013. }
  3014. }
  3015. }
  3016. }
  3017. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  3018. var keys = util.inheritedDataKeys(obj);
  3019. var ret = [];
  3020. for (var i = 0; i < keys.length; ++i) {
  3021. var key = keys[i];
  3022. var value = obj[key];
  3023. var passesDefaultFilter = filter === defaultFilter
  3024. ? true : defaultFilter(key, value, obj);
  3025. if (typeof value === "function" &&
  3026. !isPromisified(value) &&
  3027. !hasPromisified(obj, key, suffix) &&
  3028. filter(key, value, obj, passesDefaultFilter)) {
  3029. ret.push(key, value);
  3030. }
  3031. }
  3032. checkValid(ret, suffix, suffixRegexp);
  3033. return ret;
  3034. }
  3035. var escapeIdentRegex = function(str) {
  3036. return str.replace(/([$])/, "\\$");
  3037. };
  3038. var makeNodePromisifiedEval;
  3039. if (!true) {
  3040. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  3041. var ret = [likelyArgumentCount];
  3042. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  3043. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  3044. ret.push(i);
  3045. }
  3046. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  3047. ret.push(i);
  3048. }
  3049. return ret;
  3050. };
  3051. var argumentSequence = function(argumentCount) {
  3052. return util.filledRange(argumentCount, "_arg", "");
  3053. };
  3054. var parameterDeclaration = function(parameterCount) {
  3055. return util.filledRange(
  3056. Math.max(parameterCount, 3), "_arg", "");
  3057. };
  3058. var parameterCount = function(fn) {
  3059. if (typeof fn.length === "number") {
  3060. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  3061. }
  3062. return 0;
  3063. };
  3064. makeNodePromisifiedEval =
  3065. function(callback, receiver, originalName, fn) {
  3066. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  3067. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  3068. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  3069. function generateCallForArgumentCount(count) {
  3070. var args = argumentSequence(count).join(", ");
  3071. var comma = count > 0 ? ", " : "";
  3072. var ret;
  3073. if (shouldProxyThis) {
  3074. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  3075. } else {
  3076. ret = receiver === undefined
  3077. ? "ret = callback({{args}}, nodeback); break;\n"
  3078. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  3079. }
  3080. return ret.replace("{{args}}", args).replace(", ", comma);
  3081. }
  3082. function generateArgumentSwitchCase() {
  3083. var ret = "";
  3084. for (var i = 0; i < argumentOrder.length; ++i) {
  3085. ret += "case " + argumentOrder[i] +":" +
  3086. generateCallForArgumentCount(argumentOrder[i]);
  3087. }
  3088. ret += " \n\
  3089. default: \n\
  3090. var args = new Array(len + 1); \n\
  3091. var i = 0; \n\
  3092. for (var i = 0; i < len; ++i) { \n\
  3093. args[i] = arguments[i]; \n\
  3094. } \n\
  3095. args[i] = nodeback; \n\
  3096. [CodeForCall] \n\
  3097. break; \n\
  3098. ".replace("[CodeForCall]", (shouldProxyThis
  3099. ? "ret = callback.apply(this, args);\n"
  3100. : "ret = callback.apply(receiver, args);\n"));
  3101. return ret;
  3102. }
  3103. var getFunctionCode = typeof callback === "string"
  3104. ? ("this != null ? this['"+callback+"'] : fn")
  3105. : "fn";
  3106. return new Function("Promise",
  3107. "fn",
  3108. "receiver",
  3109. "withAppended",
  3110. "maybeWrapAsError",
  3111. "nodebackForPromise",
  3112. "tryCatch",
  3113. "errorObj",
  3114. "notEnumerableProp",
  3115. "INTERNAL","'use strict'; \n\
  3116. var ret = function (Parameters) { \n\
  3117. 'use strict'; \n\
  3118. var len = arguments.length; \n\
  3119. var promise = new Promise(INTERNAL); \n\
  3120. promise._captureStackTrace(); \n\
  3121. var nodeback = nodebackForPromise(promise); \n\
  3122. var ret; \n\
  3123. var callback = tryCatch([GetFunctionCode]); \n\
  3124. switch(len) { \n\
  3125. [CodeForSwitchCase] \n\
  3126. } \n\
  3127. if (ret === errorObj) { \n\
  3128. promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
  3129. } \n\
  3130. return promise; \n\
  3131. }; \n\
  3132. notEnumerableProp(ret, '__isPromisified__', true); \n\
  3133. return ret; \n\
  3134. "
  3135. .replace("Parameters", parameterDeclaration(newParameterCount))
  3136. .replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  3137. .replace("[GetFunctionCode]", getFunctionCode))(
  3138. Promise,
  3139. fn,
  3140. receiver,
  3141. withAppended,
  3142. maybeWrapAsError,
  3143. nodebackForPromise,
  3144. util.tryCatch,
  3145. util.errorObj,
  3146. util.notEnumerableProp,
  3147. INTERNAL
  3148. );
  3149. };
  3150. }
  3151. function makeNodePromisifiedClosure(callback, receiver, _, fn) {
  3152. var defaultThis = (function() {return this;})();
  3153. var method = callback;
  3154. if (typeof method === "string") {
  3155. callback = fn;
  3156. }
  3157. function promisified() {
  3158. var _receiver = receiver;
  3159. if (receiver === THIS) _receiver = this;
  3160. var promise = new Promise(INTERNAL);
  3161. promise._captureStackTrace();
  3162. var cb = typeof method === "string" && this !== defaultThis
  3163. ? this[method] : callback;
  3164. var fn = nodebackForPromise(promise);
  3165. try {
  3166. cb.apply(_receiver, withAppended(arguments, fn));
  3167. } catch(e) {
  3168. promise._rejectCallback(maybeWrapAsError(e), true, true);
  3169. }
  3170. return promise;
  3171. }
  3172. util.notEnumerableProp(promisified, "__isPromisified__", true);
  3173. return promisified;
  3174. }
  3175. var makeNodePromisified = canEvaluate
  3176. ? makeNodePromisifiedEval
  3177. : makeNodePromisifiedClosure;
  3178. function promisifyAll(obj, suffix, filter, promisifier) {
  3179. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  3180. var methods =
  3181. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  3182. for (var i = 0, len = methods.length; i < len; i+= 2) {
  3183. var key = methods[i];
  3184. var fn = methods[i+1];
  3185. var promisifiedKey = key + suffix;
  3186. if (promisifier === makeNodePromisified) {
  3187. obj[promisifiedKey] =
  3188. makeNodePromisified(key, THIS, key, fn, suffix);
  3189. } else {
  3190. var promisified = promisifier(fn, function() {
  3191. return makeNodePromisified(key, THIS, key, fn, suffix);
  3192. });
  3193. util.notEnumerableProp(promisified, "__isPromisified__", true);
  3194. obj[promisifiedKey] = promisified;
  3195. }
  3196. }
  3197. util.toFastProperties(obj);
  3198. return obj;
  3199. }
  3200. function promisify(callback, receiver) {
  3201. return makeNodePromisified(callback, receiver, undefined, callback);
  3202. }
  3203. Promise.promisify = function (fn, receiver) {
  3204. if (typeof fn !== "function") {
  3205. throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  3206. }
  3207. if (isPromisified(fn)) {
  3208. return fn;
  3209. }
  3210. var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
  3211. util.copyDescriptors(fn, ret, propsFilter);
  3212. return ret;
  3213. };
  3214. Promise.promisifyAll = function (target, options) {
  3215. if (typeof target !== "function" && typeof target !== "object") {
  3216. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a");
  3217. }
  3218. options = Object(options);
  3219. var suffix = options.suffix;
  3220. if (typeof suffix !== "string") suffix = defaultSuffix;
  3221. var filter = options.filter;
  3222. if (typeof filter !== "function") filter = defaultFilter;
  3223. var promisifier = options.promisifier;
  3224. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  3225. if (!util.isIdentifier(suffix)) {
  3226. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a");
  3227. }
  3228. var keys = util.inheritedDataKeys(target);
  3229. for (var i = 0; i < keys.length; ++i) {
  3230. var value = target[keys[i]];
  3231. if (keys[i] !== "constructor" &&
  3232. util.isClass(value)) {
  3233. promisifyAll(value.prototype, suffix, filter, promisifier);
  3234. promisifyAll(value, suffix, filter, promisifier);
  3235. }
  3236. }
  3237. return promisifyAll(target, suffix, filter, promisifier);
  3238. };
  3239. };
  3240. },{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
  3241. "use strict";
  3242. module.exports = function(
  3243. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  3244. var util = _dereq_("./util.js");
  3245. var isObject = util.isObject;
  3246. var es5 = _dereq_("./es5.js");
  3247. function PropertiesPromiseArray(obj) {
  3248. var keys = es5.keys(obj);
  3249. var len = keys.length;
  3250. var values = new Array(len * 2);
  3251. for (var i = 0; i < len; ++i) {
  3252. var key = keys[i];
  3253. values[i] = obj[key];
  3254. values[i + len] = key;
  3255. }
  3256. this.constructor$(values);
  3257. }
  3258. util.inherits(PropertiesPromiseArray, PromiseArray);
  3259. PropertiesPromiseArray.prototype._init = function () {
  3260. this._init$(undefined, -3) ;
  3261. };
  3262. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3263. this._values[index] = value;
  3264. var totalResolved = ++this._totalResolved;
  3265. if (totalResolved >= this._length) {
  3266. var val = {};
  3267. var keyOffset = this.length();
  3268. for (var i = 0, len = this.length(); i < len; ++i) {
  3269. val[this._values[i + keyOffset]] = this._values[i];
  3270. }
  3271. this._resolve(val);
  3272. }
  3273. };
  3274. PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
  3275. this._promise._progress({
  3276. key: this._values[index + this.length()],
  3277. value: value
  3278. });
  3279. };
  3280. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  3281. return false;
  3282. };
  3283. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  3284. return len >> 1;
  3285. };
  3286. function props(promises) {
  3287. var ret;
  3288. var castValue = tryConvertToPromise(promises);
  3289. if (!isObject(castValue)) {
  3290. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
  3291. } else if (castValue instanceof Promise) {
  3292. ret = castValue._then(
  3293. Promise.props, undefined, undefined, undefined, undefined);
  3294. } else {
  3295. ret = new PropertiesPromiseArray(castValue).promise();
  3296. }
  3297. if (castValue instanceof Promise) {
  3298. ret._propagateFrom(castValue, 4);
  3299. }
  3300. return ret;
  3301. }
  3302. Promise.prototype.props = function () {
  3303. return props(this);
  3304. };
  3305. Promise.props = function (promises) {
  3306. return props(promises);
  3307. };
  3308. };
  3309. },{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
  3310. "use strict";
  3311. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  3312. for (var j = 0; j < len; ++j) {
  3313. dst[j + dstIndex] = src[j + srcIndex];
  3314. src[j + srcIndex] = void 0;
  3315. }
  3316. }
  3317. function Queue(capacity) {
  3318. this._capacity = capacity;
  3319. this._length = 0;
  3320. this._front = 0;
  3321. }
  3322. Queue.prototype._willBeOverCapacity = function (size) {
  3323. return this._capacity < size;
  3324. };
  3325. Queue.prototype._pushOne = function (arg) {
  3326. var length = this.length();
  3327. this._checkCapacity(length + 1);
  3328. var i = (this._front + length) & (this._capacity - 1);
  3329. this[i] = arg;
  3330. this._length = length + 1;
  3331. };
  3332. Queue.prototype._unshiftOne = function(value) {
  3333. var capacity = this._capacity;
  3334. this._checkCapacity(this.length() + 1);
  3335. var front = this._front;
  3336. var i = (((( front - 1 ) &
  3337. ( capacity - 1) ) ^ capacity ) - capacity );
  3338. this[i] = value;
  3339. this._front = i;
  3340. this._length = this.length() + 1;
  3341. };
  3342. Queue.prototype.unshift = function(fn, receiver, arg) {
  3343. this._unshiftOne(arg);
  3344. this._unshiftOne(receiver);
  3345. this._unshiftOne(fn);
  3346. };
  3347. Queue.prototype.push = function (fn, receiver, arg) {
  3348. var length = this.length() + 3;
  3349. if (this._willBeOverCapacity(length)) {
  3350. this._pushOne(fn);
  3351. this._pushOne(receiver);
  3352. this._pushOne(arg);
  3353. return;
  3354. }
  3355. var j = this._front + length - 3;
  3356. this._checkCapacity(length);
  3357. var wrapMask = this._capacity - 1;
  3358. this[(j + 0) & wrapMask] = fn;
  3359. this[(j + 1) & wrapMask] = receiver;
  3360. this[(j + 2) & wrapMask] = arg;
  3361. this._length = length;
  3362. };
  3363. Queue.prototype.shift = function () {
  3364. var front = this._front,
  3365. ret = this[front];
  3366. this[front] = undefined;
  3367. this._front = (front + 1) & (this._capacity - 1);
  3368. this._length--;
  3369. return ret;
  3370. };
  3371. Queue.prototype.length = function () {
  3372. return this._length;
  3373. };
  3374. Queue.prototype._checkCapacity = function (size) {
  3375. if (this._capacity < size) {
  3376. this._resizeTo(this._capacity << 1);
  3377. }
  3378. };
  3379. Queue.prototype._resizeTo = function (capacity) {
  3380. var oldCapacity = this._capacity;
  3381. this._capacity = capacity;
  3382. var front = this._front;
  3383. var length = this._length;
  3384. var moveItemsCount = (front + length) & (oldCapacity - 1);
  3385. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  3386. };
  3387. module.exports = Queue;
  3388. },{}],29:[function(_dereq_,module,exports){
  3389. "use strict";
  3390. module.exports = function(
  3391. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  3392. var isArray = _dereq_("./util.js").isArray;
  3393. var raceLater = function (promise) {
  3394. return promise.then(function(array) {
  3395. return race(array, promise);
  3396. });
  3397. };
  3398. function race(promises, parent) {
  3399. var maybePromise = tryConvertToPromise(promises);
  3400. if (maybePromise instanceof Promise) {
  3401. return raceLater(maybePromise);
  3402. } else if (!isArray(promises)) {
  3403. return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
  3404. }
  3405. var ret = new Promise(INTERNAL);
  3406. if (parent !== undefined) {
  3407. ret._propagateFrom(parent, 4 | 1);
  3408. }
  3409. var fulfill = ret._fulfill;
  3410. var reject = ret._reject;
  3411. for (var i = 0, len = promises.length; i < len; ++i) {
  3412. var val = promises[i];
  3413. if (val === undefined && !(i in promises)) {
  3414. continue;
  3415. }
  3416. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  3417. }
  3418. return ret;
  3419. }
  3420. Promise.race = function (promises) {
  3421. return race(promises, undefined);
  3422. };
  3423. Promise.prototype.race = function () {
  3424. return race(this, undefined);
  3425. };
  3426. };
  3427. },{"./util.js":38}],30:[function(_dereq_,module,exports){
  3428. "use strict";
  3429. module.exports = function(Promise,
  3430. PromiseArray,
  3431. apiRejection,
  3432. tryConvertToPromise,
  3433. INTERNAL) {
  3434. var getDomain = Promise._getDomain;
  3435. var async = _dereq_("./async.js");
  3436. var util = _dereq_("./util.js");
  3437. var tryCatch = util.tryCatch;
  3438. var errorObj = util.errorObj;
  3439. function ReductionPromiseArray(promises, fn, accum, _each) {
  3440. this.constructor$(promises);
  3441. this._promise._captureStackTrace();
  3442. this._preservedValues = _each === INTERNAL ? [] : null;
  3443. this._zerothIsAccum = (accum === undefined);
  3444. this._gotAccum = false;
  3445. this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
  3446. this._valuesPhase = undefined;
  3447. var maybePromise = tryConvertToPromise(accum, this._promise);
  3448. var rejected = false;
  3449. var isPromise = maybePromise instanceof Promise;
  3450. if (isPromise) {
  3451. maybePromise = maybePromise._target();
  3452. if (maybePromise._isPending()) {
  3453. maybePromise._proxyPromiseArray(this, -1);
  3454. } else if (maybePromise._isFulfilled()) {
  3455. accum = maybePromise._value();
  3456. this._gotAccum = true;
  3457. } else {
  3458. this._reject(maybePromise._reason());
  3459. rejected = true;
  3460. }
  3461. }
  3462. if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
  3463. var domain = getDomain();
  3464. this._callback = domain === null ? fn : domain.bind(fn);
  3465. this._accum = accum;
  3466. if (!rejected) async.invoke(init, this, undefined);
  3467. }
  3468. function init() {
  3469. this._init$(undefined, -5);
  3470. }
  3471. util.inherits(ReductionPromiseArray, PromiseArray);
  3472. ReductionPromiseArray.prototype._init = function () {};
  3473. ReductionPromiseArray.prototype._resolveEmptyArray = function () {
  3474. if (this._gotAccum || this._zerothIsAccum) {
  3475. this._resolve(this._preservedValues !== null
  3476. ? [] : this._accum);
  3477. }
  3478. };
  3479. ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3480. var values = this._values;
  3481. values[index] = value;
  3482. var length = this.length();
  3483. var preservedValues = this._preservedValues;
  3484. var isEach = preservedValues !== null;
  3485. var gotAccum = this._gotAccum;
  3486. var valuesPhase = this._valuesPhase;
  3487. var valuesPhaseIndex;
  3488. if (!valuesPhase) {
  3489. valuesPhase = this._valuesPhase = new Array(length);
  3490. for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
  3491. valuesPhase[valuesPhaseIndex] = 0;
  3492. }
  3493. }
  3494. valuesPhaseIndex = valuesPhase[index];
  3495. if (index === 0 && this._zerothIsAccum) {
  3496. this._accum = value;
  3497. this._gotAccum = gotAccum = true;
  3498. valuesPhase[index] = ((valuesPhaseIndex === 0)
  3499. ? 1 : 2);
  3500. } else if (index === -1) {
  3501. this._accum = value;
  3502. this._gotAccum = gotAccum = true;
  3503. } else {
  3504. if (valuesPhaseIndex === 0) {
  3505. valuesPhase[index] = 1;
  3506. } else {
  3507. valuesPhase[index] = 2;
  3508. this._accum = value;
  3509. }
  3510. }
  3511. if (!gotAccum) return;
  3512. var callback = this._callback;
  3513. var receiver = this._promise._boundValue();
  3514. var ret;
  3515. for (var i = this._reducingIndex; i < length; ++i) {
  3516. valuesPhaseIndex = valuesPhase[i];
  3517. if (valuesPhaseIndex === 2) {
  3518. this._reducingIndex = i + 1;
  3519. continue;
  3520. }
  3521. if (valuesPhaseIndex !== 1) return;
  3522. value = values[i];
  3523. this._promise._pushContext();
  3524. if (isEach) {
  3525. preservedValues.push(value);
  3526. ret = tryCatch(callback).call(receiver, value, i, length);
  3527. }
  3528. else {
  3529. ret = tryCatch(callback)
  3530. .call(receiver, this._accum, value, i, length);
  3531. }
  3532. this._promise._popContext();
  3533. if (ret === errorObj) return this._reject(ret.e);
  3534. var maybePromise = tryConvertToPromise(ret, this._promise);
  3535. if (maybePromise instanceof Promise) {
  3536. maybePromise = maybePromise._target();
  3537. if (maybePromise._isPending()) {
  3538. valuesPhase[i] = 4;
  3539. return maybePromise._proxyPromiseArray(this, i);
  3540. } else if (maybePromise._isFulfilled()) {
  3541. ret = maybePromise._value();
  3542. } else {
  3543. return this._reject(maybePromise._reason());
  3544. }
  3545. }
  3546. this._reducingIndex = i + 1;
  3547. this._accum = ret;
  3548. }
  3549. this._resolve(isEach ? preservedValues : this._accum);
  3550. };
  3551. function reduce(promises, fn, initialValue, _each) {
  3552. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  3553. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  3554. return array.promise();
  3555. }
  3556. Promise.prototype.reduce = function (fn, initialValue) {
  3557. return reduce(this, fn, initialValue, null);
  3558. };
  3559. Promise.reduce = function (promises, fn, initialValue, _each) {
  3560. return reduce(promises, fn, initialValue, _each);
  3561. };
  3562. };
  3563. },{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
  3564. "use strict";
  3565. var schedule;
  3566. var util = _dereq_("./util");
  3567. var noAsyncScheduler = function() {
  3568. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
  3569. };
  3570. if (util.isNode && typeof MutationObserver === "undefined") {
  3571. var GlobalSetImmediate = global.setImmediate;
  3572. var ProcessNextTick = process.nextTick;
  3573. schedule = util.isRecentNode
  3574. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  3575. : function(fn) { ProcessNextTick.call(process, fn); };
  3576. } else if ((typeof MutationObserver !== "undefined") &&
  3577. !(typeof window !== "undefined" &&
  3578. window.navigator &&
  3579. window.navigator.standalone)) {
  3580. schedule = function(fn) {
  3581. var div = document.createElement("div");
  3582. var observer = new MutationObserver(fn);
  3583. observer.observe(div, {attributes: true});
  3584. return function() { div.classList.toggle("foo"); };
  3585. };
  3586. schedule.isStatic = true;
  3587. } else if (typeof setImmediate !== "undefined") {
  3588. schedule = function (fn) {
  3589. setImmediate(fn);
  3590. };
  3591. } else if (typeof setTimeout !== "undefined") {
  3592. schedule = function (fn) {
  3593. setTimeout(fn, 0);
  3594. };
  3595. } else {
  3596. schedule = noAsyncScheduler;
  3597. }
  3598. module.exports = schedule;
  3599. },{"./util":38}],32:[function(_dereq_,module,exports){
  3600. "use strict";
  3601. module.exports =
  3602. function(Promise, PromiseArray) {
  3603. var PromiseInspection = Promise.PromiseInspection;
  3604. var util = _dereq_("./util.js");
  3605. function SettledPromiseArray(values) {
  3606. this.constructor$(values);
  3607. }
  3608. util.inherits(SettledPromiseArray, PromiseArray);
  3609. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  3610. this._values[index] = inspection;
  3611. var totalResolved = ++this._totalResolved;
  3612. if (totalResolved >= this._length) {
  3613. this._resolve(this._values);
  3614. }
  3615. };
  3616. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3617. var ret = new PromiseInspection();
  3618. ret._bitField = 268435456;
  3619. ret._settledValue = value;
  3620. this._promiseResolved(index, ret);
  3621. };
  3622. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  3623. var ret = new PromiseInspection();
  3624. ret._bitField = 134217728;
  3625. ret._settledValue = reason;
  3626. this._promiseResolved(index, ret);
  3627. };
  3628. Promise.settle = function (promises) {
  3629. return new SettledPromiseArray(promises).promise();
  3630. };
  3631. Promise.prototype.settle = function () {
  3632. return new SettledPromiseArray(this).promise();
  3633. };
  3634. };
  3635. },{"./util.js":38}],33:[function(_dereq_,module,exports){
  3636. "use strict";
  3637. module.exports =
  3638. function(Promise, PromiseArray, apiRejection) {
  3639. var util = _dereq_("./util.js");
  3640. var RangeError = _dereq_("./errors.js").RangeError;
  3641. var AggregateError = _dereq_("./errors.js").AggregateError;
  3642. var isArray = util.isArray;
  3643. function SomePromiseArray(values) {
  3644. this.constructor$(values);
  3645. this._howMany = 0;
  3646. this._unwrap = false;
  3647. this._initialized = false;
  3648. }
  3649. util.inherits(SomePromiseArray, PromiseArray);
  3650. SomePromiseArray.prototype._init = function () {
  3651. if (!this._initialized) {
  3652. return;
  3653. }
  3654. if (this._howMany === 0) {
  3655. this._resolve([]);
  3656. return;
  3657. }
  3658. this._init$(undefined, -5);
  3659. var isArrayResolved = isArray(this._values);
  3660. if (!this._isResolved() &&
  3661. isArrayResolved &&
  3662. this._howMany > this._canPossiblyFulfill()) {
  3663. this._reject(this._getRangeError(this.length()));
  3664. }
  3665. };
  3666. SomePromiseArray.prototype.init = function () {
  3667. this._initialized = true;
  3668. this._init();
  3669. };
  3670. SomePromiseArray.prototype.setUnwrap = function () {
  3671. this._unwrap = true;
  3672. };
  3673. SomePromiseArray.prototype.howMany = function () {
  3674. return this._howMany;
  3675. };
  3676. SomePromiseArray.prototype.setHowMany = function (count) {
  3677. this._howMany = count;
  3678. };
  3679. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  3680. this._addFulfilled(value);
  3681. if (this._fulfilled() === this.howMany()) {
  3682. this._values.length = this.howMany();
  3683. if (this.howMany() === 1 && this._unwrap) {
  3684. this._resolve(this._values[0]);
  3685. } else {
  3686. this._resolve(this._values);
  3687. }
  3688. }
  3689. };
  3690. SomePromiseArray.prototype._promiseRejected = function (reason) {
  3691. this._addRejected(reason);
  3692. if (this.howMany() > this._canPossiblyFulfill()) {
  3693. var e = new AggregateError();
  3694. for (var i = this.length(); i < this._values.length; ++i) {
  3695. e.push(this._values[i]);
  3696. }
  3697. this._reject(e);
  3698. }
  3699. };
  3700. SomePromiseArray.prototype._fulfilled = function () {
  3701. return this._totalResolved;
  3702. };
  3703. SomePromiseArray.prototype._rejected = function () {
  3704. return this._values.length - this.length();
  3705. };
  3706. SomePromiseArray.prototype._addRejected = function (reason) {
  3707. this._values.push(reason);
  3708. };
  3709. SomePromiseArray.prototype._addFulfilled = function (value) {
  3710. this._values[this._totalResolved++] = value;
  3711. };
  3712. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  3713. return this.length() - this._rejected();
  3714. };
  3715. SomePromiseArray.prototype._getRangeError = function (count) {
  3716. var message = "Input array must contain at least " +
  3717. this._howMany + " items but contains only " + count + " items";
  3718. return new RangeError(message);
  3719. };
  3720. SomePromiseArray.prototype._resolveEmptyArray = function () {
  3721. this._reject(this._getRangeError(0));
  3722. };
  3723. function some(promises, howMany) {
  3724. if ((howMany | 0) !== howMany || howMany < 0) {
  3725. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a");
  3726. }
  3727. var ret = new SomePromiseArray(promises);
  3728. var promise = ret.promise();
  3729. ret.setHowMany(howMany);
  3730. ret.init();
  3731. return promise;
  3732. }
  3733. Promise.some = function (promises, howMany) {
  3734. return some(promises, howMany);
  3735. };
  3736. Promise.prototype.some = function (howMany) {
  3737. return some(this, howMany);
  3738. };
  3739. Promise._SomePromiseArray = SomePromiseArray;
  3740. };
  3741. },{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
  3742. "use strict";
  3743. module.exports = function(Promise) {
  3744. function PromiseInspection(promise) {
  3745. if (promise !== undefined) {
  3746. promise = promise._target();
  3747. this._bitField = promise._bitField;
  3748. this._settledValue = promise._settledValue;
  3749. }
  3750. else {
  3751. this._bitField = 0;
  3752. this._settledValue = undefined;
  3753. }
  3754. }
  3755. PromiseInspection.prototype.value = function () {
  3756. if (!this.isFulfilled()) {
  3757. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
  3758. }
  3759. return this._settledValue;
  3760. };
  3761. PromiseInspection.prototype.error =
  3762. PromiseInspection.prototype.reason = function () {
  3763. if (!this.isRejected()) {
  3764. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
  3765. }
  3766. return this._settledValue;
  3767. };
  3768. PromiseInspection.prototype.isFulfilled =
  3769. Promise.prototype._isFulfilled = function () {
  3770. return (this._bitField & 268435456) > 0;
  3771. };
  3772. PromiseInspection.prototype.isRejected =
  3773. Promise.prototype._isRejected = function () {
  3774. return (this._bitField & 134217728) > 0;
  3775. };
  3776. PromiseInspection.prototype.isPending =
  3777. Promise.prototype._isPending = function () {
  3778. return (this._bitField & 402653184) === 0;
  3779. };
  3780. PromiseInspection.prototype.isResolved =
  3781. Promise.prototype._isResolved = function () {
  3782. return (this._bitField & 402653184) > 0;
  3783. };
  3784. Promise.prototype.isPending = function() {
  3785. return this._target()._isPending();
  3786. };
  3787. Promise.prototype.isRejected = function() {
  3788. return this._target()._isRejected();
  3789. };
  3790. Promise.prototype.isFulfilled = function() {
  3791. return this._target()._isFulfilled();
  3792. };
  3793. Promise.prototype.isResolved = function() {
  3794. return this._target()._isResolved();
  3795. };
  3796. Promise.prototype._value = function() {
  3797. return this._settledValue;
  3798. };
  3799. Promise.prototype._reason = function() {
  3800. this._unsetRejectionIsUnhandled();
  3801. return this._settledValue;
  3802. };
  3803. Promise.prototype.value = function() {
  3804. var target = this._target();
  3805. if (!target.isFulfilled()) {
  3806. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
  3807. }
  3808. return target._settledValue;
  3809. };
  3810. Promise.prototype.reason = function() {
  3811. var target = this._target();
  3812. if (!target.isRejected()) {
  3813. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
  3814. }
  3815. target._unsetRejectionIsUnhandled();
  3816. return target._settledValue;
  3817. };
  3818. Promise.PromiseInspection = PromiseInspection;
  3819. };
  3820. },{}],35:[function(_dereq_,module,exports){
  3821. "use strict";
  3822. module.exports = function(Promise, INTERNAL) {
  3823. var util = _dereq_("./util.js");
  3824. var errorObj = util.errorObj;
  3825. var isObject = util.isObject;
  3826. function tryConvertToPromise(obj, context) {
  3827. if (isObject(obj)) {
  3828. if (obj instanceof Promise) {
  3829. return obj;
  3830. }
  3831. else if (isAnyBluebirdPromise(obj)) {
  3832. var ret = new Promise(INTERNAL);
  3833. obj._then(
  3834. ret._fulfillUnchecked,
  3835. ret._rejectUncheckedCheckError,
  3836. ret._progressUnchecked,
  3837. ret,
  3838. null
  3839. );
  3840. return ret;
  3841. }
  3842. var then = util.tryCatch(getThen)(obj);
  3843. if (then === errorObj) {
  3844. if (context) context._pushContext();
  3845. var ret = Promise.reject(then.e);
  3846. if (context) context._popContext();
  3847. return ret;
  3848. } else if (typeof then === "function") {
  3849. return doThenable(obj, then, context);
  3850. }
  3851. }
  3852. return obj;
  3853. }
  3854. function getThen(obj) {
  3855. return obj.then;
  3856. }
  3857. var hasProp = {}.hasOwnProperty;
  3858. function isAnyBluebirdPromise(obj) {
  3859. return hasProp.call(obj, "_promise0");
  3860. }
  3861. function doThenable(x, then, context) {
  3862. var promise = new Promise(INTERNAL);
  3863. var ret = promise;
  3864. if (context) context._pushContext();
  3865. promise._captureStackTrace();
  3866. if (context) context._popContext();
  3867. var synchronous = true;
  3868. var result = util.tryCatch(then).call(x,
  3869. resolveFromThenable,
  3870. rejectFromThenable,
  3871. progressFromThenable);
  3872. synchronous = false;
  3873. if (promise && result === errorObj) {
  3874. promise._rejectCallback(result.e, true, true);
  3875. promise = null;
  3876. }
  3877. function resolveFromThenable(value) {
  3878. if (!promise) return;
  3879. promise._resolveCallback(value);
  3880. promise = null;
  3881. }
  3882. function rejectFromThenable(reason) {
  3883. if (!promise) return;
  3884. promise._rejectCallback(reason, synchronous, true);
  3885. promise = null;
  3886. }
  3887. function progressFromThenable(value) {
  3888. if (!promise) return;
  3889. if (typeof promise._progress === "function") {
  3890. promise._progress(value);
  3891. }
  3892. }
  3893. return ret;
  3894. }
  3895. return tryConvertToPromise;
  3896. };
  3897. },{"./util.js":38}],36:[function(_dereq_,module,exports){
  3898. "use strict";
  3899. module.exports = function(Promise, INTERNAL) {
  3900. var util = _dereq_("./util.js");
  3901. var TimeoutError = Promise.TimeoutError;
  3902. var afterTimeout = function (promise, message) {
  3903. if (!promise.isPending()) return;
  3904. var err;
  3905. if(!util.isPrimitive(message) && (message instanceof Error)) {
  3906. err = message;
  3907. } else {
  3908. if (typeof message !== "string") {
  3909. message = "operation timed out";
  3910. }
  3911. err = new TimeoutError(message);
  3912. }
  3913. util.markAsOriginatingFromRejection(err);
  3914. promise._attachExtraTrace(err);
  3915. promise._cancel(err);
  3916. };
  3917. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  3918. var delay = Promise.delay = function (value, ms) {
  3919. if (ms === undefined) {
  3920. ms = value;
  3921. value = undefined;
  3922. var ret = new Promise(INTERNAL);
  3923. setTimeout(function() { ret._fulfill(); }, ms);
  3924. return ret;
  3925. }
  3926. ms = +ms;
  3927. return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
  3928. };
  3929. Promise.prototype.delay = function (ms) {
  3930. return delay(this, ms);
  3931. };
  3932. function successClear(value) {
  3933. var handle = this;
  3934. if (handle instanceof Number) handle = +handle;
  3935. clearTimeout(handle);
  3936. return value;
  3937. }
  3938. function failureClear(reason) {
  3939. var handle = this;
  3940. if (handle instanceof Number) handle = +handle;
  3941. clearTimeout(handle);
  3942. throw reason;
  3943. }
  3944. Promise.prototype.timeout = function (ms, message) {
  3945. ms = +ms;
  3946. var ret = this.then().cancellable();
  3947. ret._cancellationParent = this;
  3948. var handle = setTimeout(function timeoutTimeout() {
  3949. afterTimeout(ret, message);
  3950. }, ms);
  3951. return ret._then(successClear, failureClear, undefined, handle, undefined);
  3952. };
  3953. };
  3954. },{"./util.js":38}],37:[function(_dereq_,module,exports){
  3955. "use strict";
  3956. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  3957. createContext) {
  3958. var TypeError = _dereq_("./errors.js").TypeError;
  3959. var inherits = _dereq_("./util.js").inherits;
  3960. var PromiseInspection = Promise.PromiseInspection;
  3961. function inspectionMapper(inspections) {
  3962. var len = inspections.length;
  3963. for (var i = 0; i < len; ++i) {
  3964. var inspection = inspections[i];
  3965. if (inspection.isRejected()) {
  3966. return Promise.reject(inspection.error());
  3967. }
  3968. inspections[i] = inspection._settledValue;
  3969. }
  3970. return inspections;
  3971. }
  3972. function thrower(e) {
  3973. setTimeout(function(){throw e;}, 0);
  3974. }
  3975. function castPreservingDisposable(thenable) {
  3976. var maybePromise = tryConvertToPromise(thenable);
  3977. if (maybePromise !== thenable &&
  3978. typeof thenable._isDisposable === "function" &&
  3979. typeof thenable._getDisposer === "function" &&
  3980. thenable._isDisposable()) {
  3981. maybePromise._setDisposable(thenable._getDisposer());
  3982. }
  3983. return maybePromise;
  3984. }
  3985. function dispose(resources, inspection) {
  3986. var i = 0;
  3987. var len = resources.length;
  3988. var ret = Promise.defer();
  3989. function iterator() {
  3990. if (i >= len) return ret.resolve();
  3991. var maybePromise = castPreservingDisposable(resources[i++]);
  3992. if (maybePromise instanceof Promise &&
  3993. maybePromise._isDisposable()) {
  3994. try {
  3995. maybePromise = tryConvertToPromise(
  3996. maybePromise._getDisposer().tryDispose(inspection),
  3997. resources.promise);
  3998. } catch (e) {
  3999. return thrower(e);
  4000. }
  4001. if (maybePromise instanceof Promise) {
  4002. return maybePromise._then(iterator, thrower,
  4003. null, null, null);
  4004. }
  4005. }
  4006. iterator();
  4007. }
  4008. iterator();
  4009. return ret.promise;
  4010. }
  4011. function disposerSuccess(value) {
  4012. var inspection = new PromiseInspection();
  4013. inspection._settledValue = value;
  4014. inspection._bitField = 268435456;
  4015. return dispose(this, inspection).thenReturn(value);
  4016. }
  4017. function disposerFail(reason) {
  4018. var inspection = new PromiseInspection();
  4019. inspection._settledValue = reason;
  4020. inspection._bitField = 134217728;
  4021. return dispose(this, inspection).thenThrow(reason);
  4022. }
  4023. function Disposer(data, promise, context) {
  4024. this._data = data;
  4025. this._promise = promise;
  4026. this._context = context;
  4027. }
  4028. Disposer.prototype.data = function () {
  4029. return this._data;
  4030. };
  4031. Disposer.prototype.promise = function () {
  4032. return this._promise;
  4033. };
  4034. Disposer.prototype.resource = function () {
  4035. if (this.promise().isFulfilled()) {
  4036. return this.promise().value();
  4037. }
  4038. return null;
  4039. };
  4040. Disposer.prototype.tryDispose = function(inspection) {
  4041. var resource = this.resource();
  4042. var context = this._context;
  4043. if (context !== undefined) context._pushContext();
  4044. var ret = resource !== null
  4045. ? this.doDispose(resource, inspection) : null;
  4046. if (context !== undefined) context._popContext();
  4047. this._promise._unsetDisposable();
  4048. this._data = null;
  4049. return ret;
  4050. };
  4051. Disposer.isDisposer = function (d) {
  4052. return (d != null &&
  4053. typeof d.resource === "function" &&
  4054. typeof d.tryDispose === "function");
  4055. };
  4056. function FunctionDisposer(fn, promise, context) {
  4057. this.constructor$(fn, promise, context);
  4058. }
  4059. inherits(FunctionDisposer, Disposer);
  4060. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  4061. var fn = this.data();
  4062. return fn.call(resource, resource, inspection);
  4063. };
  4064. function maybeUnwrapDisposer(value) {
  4065. if (Disposer.isDisposer(value)) {
  4066. this.resources[this.index]._setDisposable(value);
  4067. return value.promise();
  4068. }
  4069. return value;
  4070. }
  4071. Promise.using = function () {
  4072. var len = arguments.length;
  4073. if (len < 2) return apiRejection(
  4074. "you must pass at least 2 arguments to Promise.using");
  4075. var fn = arguments[len - 1];
  4076. if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  4077. var input;
  4078. var spreadArgs = true;
  4079. if (len === 2 && Array.isArray(arguments[0])) {
  4080. input = arguments[0];
  4081. len = input.length;
  4082. spreadArgs = false;
  4083. } else {
  4084. input = arguments;
  4085. len--;
  4086. }
  4087. var resources = new Array(len);
  4088. for (var i = 0; i < len; ++i) {
  4089. var resource = input[i];
  4090. if (Disposer.isDisposer(resource)) {
  4091. var disposer = resource;
  4092. resource = resource.promise();
  4093. resource._setDisposable(disposer);
  4094. } else {
  4095. var maybePromise = tryConvertToPromise(resource);
  4096. if (maybePromise instanceof Promise) {
  4097. resource =
  4098. maybePromise._then(maybeUnwrapDisposer, null, null, {
  4099. resources: resources,
  4100. index: i
  4101. }, undefined);
  4102. }
  4103. }
  4104. resources[i] = resource;
  4105. }
  4106. var promise = Promise.settle(resources)
  4107. .then(inspectionMapper)
  4108. .then(function(vals) {
  4109. promise._pushContext();
  4110. var ret;
  4111. try {
  4112. ret = spreadArgs
  4113. ? fn.apply(undefined, vals) : fn.call(undefined, vals);
  4114. } finally {
  4115. promise._popContext();
  4116. }
  4117. return ret;
  4118. })
  4119. ._then(
  4120. disposerSuccess, disposerFail, undefined, resources, undefined);
  4121. resources.promise = promise;
  4122. return promise;
  4123. };
  4124. Promise.prototype._setDisposable = function (disposer) {
  4125. this._bitField = this._bitField | 262144;
  4126. this._disposer = disposer;
  4127. };
  4128. Promise.prototype._isDisposable = function () {
  4129. return (this._bitField & 262144) > 0;
  4130. };
  4131. Promise.prototype._getDisposer = function () {
  4132. return this._disposer;
  4133. };
  4134. Promise.prototype._unsetDisposable = function () {
  4135. this._bitField = this._bitField & (~262144);
  4136. this._disposer = undefined;
  4137. };
  4138. Promise.prototype.disposer = function (fn) {
  4139. if (typeof fn === "function") {
  4140. return new FunctionDisposer(fn, this, createContext());
  4141. }
  4142. throw new TypeError();
  4143. };
  4144. };
  4145. },{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
  4146. "use strict";
  4147. var es5 = _dereq_("./es5.js");
  4148. var canEvaluate = typeof navigator == "undefined";
  4149. var haveGetters = (function(){
  4150. try {
  4151. var o = {};
  4152. es5.defineProperty(o, "f", {
  4153. get: function () {
  4154. return 3;
  4155. }
  4156. });
  4157. return o.f === 3;
  4158. }
  4159. catch (e) {
  4160. return false;
  4161. }
  4162. })();
  4163. var errorObj = {e: {}};
  4164. var tryCatchTarget;
  4165. function tryCatcher() {
  4166. try {
  4167. var target = tryCatchTarget;
  4168. tryCatchTarget = null;
  4169. return target.apply(this, arguments);
  4170. } catch (e) {
  4171. errorObj.e = e;
  4172. return errorObj;
  4173. }
  4174. }
  4175. function tryCatch(fn) {
  4176. tryCatchTarget = fn;
  4177. return tryCatcher;
  4178. }
  4179. var inherits = function(Child, Parent) {
  4180. var hasProp = {}.hasOwnProperty;
  4181. function T() {
  4182. this.constructor = Child;
  4183. this.constructor$ = Parent;
  4184. for (var propertyName in Parent.prototype) {
  4185. if (hasProp.call(Parent.prototype, propertyName) &&
  4186. propertyName.charAt(propertyName.length-1) !== "$"
  4187. ) {
  4188. this[propertyName + "$"] = Parent.prototype[propertyName];
  4189. }
  4190. }
  4191. }
  4192. T.prototype = Parent.prototype;
  4193. Child.prototype = new T();
  4194. return Child.prototype;
  4195. };
  4196. function isPrimitive(val) {
  4197. return val == null || val === true || val === false ||
  4198. typeof val === "string" || typeof val === "number";
  4199. }
  4200. function isObject(value) {
  4201. return !isPrimitive(value);
  4202. }
  4203. function maybeWrapAsError(maybeError) {
  4204. if (!isPrimitive(maybeError)) return maybeError;
  4205. return new Error(safeToString(maybeError));
  4206. }
  4207. function withAppended(target, appendee) {
  4208. var len = target.length;
  4209. var ret = new Array(len + 1);
  4210. var i;
  4211. for (i = 0; i < len; ++i) {
  4212. ret[i] = target[i];
  4213. }
  4214. ret[i] = appendee;
  4215. return ret;
  4216. }
  4217. function getDataPropertyOrDefault(obj, key, defaultValue) {
  4218. if (es5.isES5) {
  4219. var desc = Object.getOwnPropertyDescriptor(obj, key);
  4220. if (desc != null) {
  4221. return desc.get == null && desc.set == null
  4222. ? desc.value
  4223. : defaultValue;
  4224. }
  4225. } else {
  4226. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  4227. }
  4228. }
  4229. function notEnumerableProp(obj, name, value) {
  4230. if (isPrimitive(obj)) return obj;
  4231. var descriptor = {
  4232. value: value,
  4233. configurable: true,
  4234. enumerable: false,
  4235. writable: true
  4236. };
  4237. es5.defineProperty(obj, name, descriptor);
  4238. return obj;
  4239. }
  4240. function thrower(r) {
  4241. throw r;
  4242. }
  4243. var inheritedDataKeys = (function() {
  4244. var excludedPrototypes = [
  4245. Array.prototype,
  4246. Object.prototype,
  4247. Function.prototype
  4248. ];
  4249. var isExcludedProto = function(val) {
  4250. for (var i = 0; i < excludedPrototypes.length; ++i) {
  4251. if (excludedPrototypes[i] === val) {
  4252. return true;
  4253. }
  4254. }
  4255. return false;
  4256. };
  4257. if (es5.isES5) {
  4258. var getKeys = Object.getOwnPropertyNames;
  4259. return function(obj) {
  4260. var ret = [];
  4261. var visitedKeys = Object.create(null);
  4262. while (obj != null && !isExcludedProto(obj)) {
  4263. var keys;
  4264. try {
  4265. keys = getKeys(obj);
  4266. } catch (e) {
  4267. return ret;
  4268. }
  4269. for (var i = 0; i < keys.length; ++i) {
  4270. var key = keys[i];
  4271. if (visitedKeys[key]) continue;
  4272. visitedKeys[key] = true;
  4273. var desc = Object.getOwnPropertyDescriptor(obj, key);
  4274. if (desc != null && desc.get == null && desc.set == null) {
  4275. ret.push(key);
  4276. }
  4277. }
  4278. obj = es5.getPrototypeOf(obj);
  4279. }
  4280. return ret;
  4281. };
  4282. } else {
  4283. var hasProp = {}.hasOwnProperty;
  4284. return function(obj) {
  4285. if (isExcludedProto(obj)) return [];
  4286. var ret = [];
  4287. /*jshint forin:false */
  4288. enumeration: for (var key in obj) {
  4289. if (hasProp.call(obj, key)) {
  4290. ret.push(key);
  4291. } else {
  4292. for (var i = 0; i < excludedPrototypes.length; ++i) {
  4293. if (hasProp.call(excludedPrototypes[i], key)) {
  4294. continue enumeration;
  4295. }
  4296. }
  4297. ret.push(key);
  4298. }
  4299. }
  4300. return ret;
  4301. };
  4302. }
  4303. })();
  4304. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  4305. function isClass(fn) {
  4306. try {
  4307. if (typeof fn === "function") {
  4308. var keys = es5.names(fn.prototype);
  4309. var hasMethods = es5.isES5 && keys.length > 1;
  4310. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  4311. !(keys.length === 1 && keys[0] === "constructor");
  4312. var hasThisAssignmentAndStaticMethods =
  4313. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  4314. if (hasMethods || hasMethodsOtherThanConstructor ||
  4315. hasThisAssignmentAndStaticMethods) {
  4316. return true;
  4317. }
  4318. }
  4319. return false;
  4320. } catch (e) {
  4321. return false;
  4322. }
  4323. }
  4324. function toFastProperties(obj) {
  4325. /*jshint -W027,-W055,-W031*/
  4326. function f() {}
  4327. f.prototype = obj;
  4328. var l = 8;
  4329. while (l--) new f();
  4330. return obj;
  4331. eval(obj);
  4332. }
  4333. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  4334. function isIdentifier(str) {
  4335. return rident.test(str);
  4336. }
  4337. function filledRange(count, prefix, suffix) {
  4338. var ret = new Array(count);
  4339. for(var i = 0; i < count; ++i) {
  4340. ret[i] = prefix + i + suffix;
  4341. }
  4342. return ret;
  4343. }
  4344. function safeToString(obj) {
  4345. try {
  4346. return obj + "";
  4347. } catch (e) {
  4348. return "[no string representation]";
  4349. }
  4350. }
  4351. function markAsOriginatingFromRejection(e) {
  4352. try {
  4353. notEnumerableProp(e, "isOperational", true);
  4354. }
  4355. catch(ignore) {}
  4356. }
  4357. function originatesFromRejection(e) {
  4358. if (e == null) return false;
  4359. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  4360. e["isOperational"] === true);
  4361. }
  4362. function canAttachTrace(obj) {
  4363. return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
  4364. }
  4365. var ensureErrorObject = (function() {
  4366. if (!("stack" in new Error())) {
  4367. return function(value) {
  4368. if (canAttachTrace(value)) return value;
  4369. try {throw new Error(safeToString(value));}
  4370. catch(err) {return err;}
  4371. };
  4372. } else {
  4373. return function(value) {
  4374. if (canAttachTrace(value)) return value;
  4375. return new Error(safeToString(value));
  4376. };
  4377. }
  4378. })();
  4379. function classString(obj) {
  4380. return {}.toString.call(obj);
  4381. }
  4382. function copyDescriptors(from, to, filter) {
  4383. var keys = es5.names(from);
  4384. for (var i = 0; i < keys.length; ++i) {
  4385. var key = keys[i];
  4386. if (filter(key)) {
  4387. try {
  4388. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  4389. } catch (ignore) {}
  4390. }
  4391. }
  4392. }
  4393. var ret = {
  4394. isClass: isClass,
  4395. isIdentifier: isIdentifier,
  4396. inheritedDataKeys: inheritedDataKeys,
  4397. getDataPropertyOrDefault: getDataPropertyOrDefault,
  4398. thrower: thrower,
  4399. isArray: es5.isArray,
  4400. haveGetters: haveGetters,
  4401. notEnumerableProp: notEnumerableProp,
  4402. isPrimitive: isPrimitive,
  4403. isObject: isObject,
  4404. canEvaluate: canEvaluate,
  4405. errorObj: errorObj,
  4406. tryCatch: tryCatch,
  4407. inherits: inherits,
  4408. withAppended: withAppended,
  4409. maybeWrapAsError: maybeWrapAsError,
  4410. toFastProperties: toFastProperties,
  4411. filledRange: filledRange,
  4412. toString: safeToString,
  4413. canAttachTrace: canAttachTrace,
  4414. ensureErrorObject: ensureErrorObject,
  4415. originatesFromRejection: originatesFromRejection,
  4416. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  4417. classString: classString,
  4418. copyDescriptors: copyDescriptors,
  4419. hasDevTools: typeof chrome !== "undefined" && chrome &&
  4420. typeof chrome.loadTimes === "function",
  4421. isNode: typeof process !== "undefined" &&
  4422. classString(process).toLowerCase() === "[object process]"
  4423. };
  4424. ret.isRecentNode = ret.isNode && (function() {
  4425. var version = process.versions.node.split(".").map(Number);
  4426. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  4427. })();
  4428. if (ret.isNode) ret.toFastProperties(process);
  4429. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  4430. module.exports = ret;
  4431. },{"./es5.js":14}]},{},[4])(4)
  4432. }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
  4433. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4434. },{"_process":26}],3:[function(require,module,exports){
  4435. (function (global){
  4436. /*!
  4437. * The buffer module from node.js, for the browser.
  4438. *
  4439. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  4440. * @license MIT
  4441. */
  4442. /* eslint-disable no-proto */
  4443. 'use strict'
  4444. var base64 = require('base64-js')
  4445. var ieee754 = require('ieee754')
  4446. var isArray = require('isarray')
  4447. exports.Buffer = Buffer
  4448. exports.SlowBuffer = SlowBuffer
  4449. exports.INSPECT_MAX_BYTES = 50
  4450. Buffer.poolSize = 8192 // not used by this implementation
  4451. var rootParent = {}
  4452. /**
  4453. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  4454. * === true Use Uint8Array implementation (fastest)
  4455. * === false Use Object implementation (most compatible, even IE6)
  4456. *
  4457. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  4458. * Opera 11.6+, iOS 4.2+.
  4459. *
  4460. * Due to various browser bugs, sometimes the Object implementation will be used even
  4461. * when the browser supports typed arrays.
  4462. *
  4463. * Note:
  4464. *
  4465. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  4466. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  4467. *
  4468. * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
  4469. * on objects.
  4470. *
  4471. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  4472. *
  4473. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  4474. * incorrect length in some situations.
  4475. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  4476. * get the Object implementation, which is slower but behaves correctly.
  4477. */
  4478. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  4479. ? global.TYPED_ARRAY_SUPPORT
  4480. : typedArraySupport()
  4481. function typedArraySupport () {
  4482. function Bar () {}
  4483. try {
  4484. var arr = new Uint8Array(1)
  4485. arr.foo = function () { return 42 }
  4486. arr.constructor = Bar
  4487. return arr.foo() === 42 && // typed array instances can be augmented
  4488. arr.constructor === Bar && // constructor can be set
  4489. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  4490. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  4491. } catch (e) {
  4492. return false
  4493. }
  4494. }
  4495. function kMaxLength () {
  4496. return Buffer.TYPED_ARRAY_SUPPORT
  4497. ? 0x7fffffff
  4498. : 0x3fffffff
  4499. }
  4500. /**
  4501. * Class: Buffer
  4502. * =============
  4503. *
  4504. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  4505. * with function properties for all the node `Buffer` API functions. We use
  4506. * `Uint8Array` so that square bracket notation works as expected -- it returns
  4507. * a single octet.
  4508. *
  4509. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  4510. * prototype.
  4511. */
  4512. function Buffer (arg) {
  4513. if (!(this instanceof Buffer)) {
  4514. // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
  4515. if (arguments.length > 1) return new Buffer(arg, arguments[1])
  4516. return new Buffer(arg)
  4517. }
  4518. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  4519. this.length = 0
  4520. this.parent = undefined
  4521. }
  4522. // Common case.
  4523. if (typeof arg === 'number') {
  4524. return fromNumber(this, arg)
  4525. }
  4526. // Slightly less common case.
  4527. if (typeof arg === 'string') {
  4528. return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
  4529. }
  4530. // Unusual.
  4531. return fromObject(this, arg)
  4532. }
  4533. function fromNumber (that, length) {
  4534. that = allocate(that, length < 0 ? 0 : checked(length) | 0)
  4535. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  4536. for (var i = 0; i < length; i++) {
  4537. that[i] = 0
  4538. }
  4539. }
  4540. return that
  4541. }
  4542. function fromString (that, string, encoding) {
  4543. if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
  4544. // Assumption: byteLength() return value is always < kMaxLength.
  4545. var length = byteLength(string, encoding) | 0
  4546. that = allocate(that, length)
  4547. that.write(string, encoding)
  4548. return that
  4549. }
  4550. function fromObject (that, object) {
  4551. if (Buffer.isBuffer(object)) return fromBuffer(that, object)
  4552. if (isArray(object)) return fromArray(that, object)
  4553. if (object == null) {
  4554. throw new TypeError('must start with number, buffer, array or string')
  4555. }
  4556. if (typeof ArrayBuffer !== 'undefined') {
  4557. if (object.buffer instanceof ArrayBuffer) {
  4558. return fromTypedArray(that, object)
  4559. }
  4560. if (object instanceof ArrayBuffer) {
  4561. return fromArrayBuffer(that, object)
  4562. }
  4563. }
  4564. if (object.length) return fromArrayLike(that, object)
  4565. return fromJsonObject(that, object)
  4566. }
  4567. function fromBuffer (that, buffer) {
  4568. var length = checked(buffer.length) | 0
  4569. that = allocate(that, length)
  4570. buffer.copy(that, 0, 0, length)
  4571. return that
  4572. }
  4573. function fromArray (that, array) {
  4574. var length = checked(array.length) | 0
  4575. that = allocate(that, length)
  4576. for (var i = 0; i < length; i += 1) {
  4577. that[i] = array[i] & 255
  4578. }
  4579. return that
  4580. }
  4581. // Duplicate of fromArray() to keep fromArray() monomorphic.
  4582. function fromTypedArray (that, array) {
  4583. var length = checked(array.length) | 0
  4584. that = allocate(that, length)
  4585. // Truncating the elements is probably not what people expect from typed
  4586. // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
  4587. // of the old Buffer constructor.
  4588. for (var i = 0; i < length; i += 1) {
  4589. that[i] = array[i] & 255
  4590. }
  4591. return that
  4592. }
  4593. function fromArrayBuffer (that, array) {
  4594. if (Buffer.TYPED_ARRAY_SUPPORT) {
  4595. // Return an augmented `Uint8Array` instance, for best performance
  4596. array.byteLength
  4597. that = Buffer._augment(new Uint8Array(array))
  4598. } else {
  4599. // Fallback: Return an object instance of the Buffer class
  4600. that = fromTypedArray(that, new Uint8Array(array))
  4601. }
  4602. return that
  4603. }
  4604. function fromArrayLike (that, array) {
  4605. var length = checked(array.length) | 0
  4606. that = allocate(that, length)
  4607. for (var i = 0; i < length; i += 1) {
  4608. that[i] = array[i] & 255
  4609. }
  4610. return that
  4611. }
  4612. // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
  4613. // Returns a zero-length buffer for inputs that don't conform to the spec.
  4614. function fromJsonObject (that, object) {
  4615. var array
  4616. var length = 0
  4617. if (object.type === 'Buffer' && isArray(object.data)) {
  4618. array = object.data
  4619. length = checked(array.length) | 0
  4620. }
  4621. that = allocate(that, length)
  4622. for (var i = 0; i < length; i += 1) {
  4623. that[i] = array[i] & 255
  4624. }
  4625. return that
  4626. }
  4627. if (Buffer.TYPED_ARRAY_SUPPORT) {
  4628. Buffer.prototype.__proto__ = Uint8Array.prototype
  4629. Buffer.__proto__ = Uint8Array
  4630. } else {
  4631. // pre-set for values that may exist in the future
  4632. Buffer.prototype.length = undefined
  4633. Buffer.prototype.parent = undefined
  4634. }
  4635. function allocate (that, length) {
  4636. if (Buffer.TYPED_ARRAY_SUPPORT) {
  4637. // Return an augmented `Uint8Array` instance, for best performance
  4638. that = Buffer._augment(new Uint8Array(length))
  4639. that.__proto__ = Buffer.prototype
  4640. } else {
  4641. // Fallback: Return an object instance of the Buffer class
  4642. that.length = length
  4643. that._isBuffer = true
  4644. }
  4645. var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
  4646. if (fromPool) that.parent = rootParent
  4647. return that
  4648. }
  4649. function checked (length) {
  4650. // Note: cannot use `length < kMaxLength` here because that fails when
  4651. // length is NaN (which is otherwise coerced to zero.)
  4652. if (length >= kMaxLength()) {
  4653. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  4654. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  4655. }
  4656. return length | 0
  4657. }
  4658. function SlowBuffer (subject, encoding) {
  4659. if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
  4660. var buf = new Buffer(subject, encoding)
  4661. delete buf.parent
  4662. return buf
  4663. }
  4664. Buffer.isBuffer = function isBuffer (b) {
  4665. return !!(b != null && b._isBuffer)
  4666. }
  4667. Buffer.compare = function compare (a, b) {
  4668. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  4669. throw new TypeError('Arguments must be Buffers')
  4670. }
  4671. if (a === b) return 0
  4672. var x = a.length
  4673. var y = b.length
  4674. var i = 0
  4675. var len = Math.min(x, y)
  4676. while (i < len) {
  4677. if (a[i] !== b[i]) break
  4678. ++i
  4679. }
  4680. if (i !== len) {
  4681. x = a[i]
  4682. y = b[i]
  4683. }
  4684. if (x < y) return -1
  4685. if (y < x) return 1
  4686. return 0
  4687. }
  4688. Buffer.isEncoding = function isEncoding (encoding) {
  4689. switch (String(encoding).toLowerCase()) {
  4690. case 'hex':
  4691. case 'utf8':
  4692. case 'utf-8':
  4693. case 'ascii':
  4694. case 'binary':
  4695. case 'base64':
  4696. case 'raw':
  4697. case 'ucs2':
  4698. case 'ucs-2':
  4699. case 'utf16le':
  4700. case 'utf-16le':
  4701. return true
  4702. default:
  4703. return false
  4704. }
  4705. }
  4706. Buffer.concat = function concat (list, length) {
  4707. if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
  4708. if (list.length === 0) {
  4709. return new Buffer(0)
  4710. }
  4711. var i
  4712. if (length === undefined) {
  4713. length = 0
  4714. for (i = 0; i < list.length; i++) {
  4715. length += list[i].length
  4716. }
  4717. }
  4718. var buf = new Buffer(length)
  4719. var pos = 0
  4720. for (i = 0; i < list.length; i++) {
  4721. var item = list[i]
  4722. item.copy(buf, pos)
  4723. pos += item.length
  4724. }
  4725. return buf
  4726. }
  4727. function byteLength (string, encoding) {
  4728. if (typeof string !== 'string') string = '' + string
  4729. var len = string.length
  4730. if (len === 0) return 0
  4731. // Use a for loop to avoid recursion
  4732. var loweredCase = false
  4733. for (;;) {
  4734. switch (encoding) {
  4735. case 'ascii':
  4736. case 'binary':
  4737. // Deprecated
  4738. case 'raw':
  4739. case 'raws':
  4740. return len
  4741. case 'utf8':
  4742. case 'utf-8':
  4743. return utf8ToBytes(string).length
  4744. case 'ucs2':
  4745. case 'ucs-2':
  4746. case 'utf16le':
  4747. case 'utf-16le':
  4748. return len * 2
  4749. case 'hex':
  4750. return len >>> 1
  4751. case 'base64':
  4752. return base64ToBytes(string).length
  4753. default:
  4754. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  4755. encoding = ('' + encoding).toLowerCase()
  4756. loweredCase = true
  4757. }
  4758. }
  4759. }
  4760. Buffer.byteLength = byteLength
  4761. function slowToString (encoding, start, end) {
  4762. var loweredCase = false
  4763. start = start | 0
  4764. end = end === undefined || end === Infinity ? this.length : end | 0
  4765. if (!encoding) encoding = 'utf8'
  4766. if (start < 0) start = 0
  4767. if (end > this.length) end = this.length
  4768. if (end <= start) return ''
  4769. while (true) {
  4770. switch (encoding) {
  4771. case 'hex':
  4772. return hexSlice(this, start, end)
  4773. case 'utf8':
  4774. case 'utf-8':
  4775. return utf8Slice(this, start, end)
  4776. case 'ascii':
  4777. return asciiSlice(this, start, end)
  4778. case 'binary':
  4779. return binarySlice(this, start, end)
  4780. case 'base64':
  4781. return base64Slice(this, start, end)
  4782. case 'ucs2':
  4783. case 'ucs-2':
  4784. case 'utf16le':
  4785. case 'utf-16le':
  4786. return utf16leSlice(this, start, end)
  4787. default:
  4788. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  4789. encoding = (encoding + '').toLowerCase()
  4790. loweredCase = true
  4791. }
  4792. }
  4793. }
  4794. Buffer.prototype.toString = function toString () {
  4795. var length = this.length | 0
  4796. if (length === 0) return ''
  4797. if (arguments.length === 0) return utf8Slice(this, 0, length)
  4798. return slowToString.apply(this, arguments)
  4799. }
  4800. Buffer.prototype.equals = function equals (b) {
  4801. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  4802. if (this === b) return true
  4803. return Buffer.compare(this, b) === 0
  4804. }
  4805. Buffer.prototype.inspect = function inspect () {
  4806. var str = ''
  4807. var max = exports.INSPECT_MAX_BYTES
  4808. if (this.length > 0) {
  4809. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  4810. if (this.length > max) str += ' ... '
  4811. }
  4812. return '<Buffer ' + str + '>'
  4813. }
  4814. Buffer.prototype.compare = function compare (b) {
  4815. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  4816. if (this === b) return 0
  4817. return Buffer.compare(this, b)
  4818. }
  4819. Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
  4820. if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
  4821. else if (byteOffset < -0x80000000) byteOffset = -0x80000000
  4822. byteOffset >>= 0
  4823. if (this.length === 0) return -1
  4824. if (byteOffset >= this.length) return -1
  4825. // Negative offsets start from the end of the buffer
  4826. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  4827. if (typeof val === 'string') {
  4828. if (val.length === 0) return -1 // special case: looking for empty string always fails
  4829. return String.prototype.indexOf.call(this, val, byteOffset)
  4830. }
  4831. if (Buffer.isBuffer(val)) {
  4832. return arrayIndexOf(this, val, byteOffset)
  4833. }
  4834. if (typeof val === 'number') {
  4835. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  4836. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  4837. }
  4838. return arrayIndexOf(this, [ val ], byteOffset)
  4839. }
  4840. function arrayIndexOf (arr, val, byteOffset) {
  4841. var foundIndex = -1
  4842. for (var i = 0; byteOffset + i < arr.length; i++) {
  4843. if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
  4844. if (foundIndex === -1) foundIndex = i
  4845. if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
  4846. } else {
  4847. foundIndex = -1
  4848. }
  4849. }
  4850. return -1
  4851. }
  4852. throw new TypeError('val must be string, number or Buffer')
  4853. }
  4854. // `get` is deprecated
  4855. Buffer.prototype.get = function get (offset) {
  4856. console.log('.get() is deprecated. Access using array indexes instead.')
  4857. return this.readUInt8(offset)
  4858. }
  4859. // `set` is deprecated
  4860. Buffer.prototype.set = function set (v, offset) {
  4861. console.log('.set() is deprecated. Access using array indexes instead.')
  4862. return this.writeUInt8(v, offset)
  4863. }
  4864. function hexWrite (buf, string, offset, length) {
  4865. offset = Number(offset) || 0
  4866. var remaining = buf.length - offset
  4867. if (!length) {
  4868. length = remaining
  4869. } else {
  4870. length = Number(length)
  4871. if (length > remaining) {
  4872. length = remaining
  4873. }
  4874. }
  4875. // must be an even number of digits
  4876. var strLen = string.length
  4877. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  4878. if (length > strLen / 2) {
  4879. length = strLen / 2
  4880. }
  4881. for (var i = 0; i < length; i++) {
  4882. var parsed = parseInt(string.substr(i * 2, 2), 16)
  4883. if (isNaN(parsed)) throw new Error('Invalid hex string')
  4884. buf[offset + i] = parsed
  4885. }
  4886. return i
  4887. }
  4888. function utf8Write (buf, string, offset, length) {
  4889. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  4890. }
  4891. function asciiWrite (buf, string, offset, length) {
  4892. return blitBuffer(asciiToBytes(string), buf, offset, length)
  4893. }
  4894. function binaryWrite (buf, string, offset, length) {
  4895. return asciiWrite(buf, string, offset, length)
  4896. }
  4897. function base64Write (buf, string, offset, length) {
  4898. return blitBuffer(base64ToBytes(string), buf, offset, length)
  4899. }
  4900. function ucs2Write (buf, string, offset, length) {
  4901. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  4902. }
  4903. Buffer.prototype.write = function write (string, offset, length, encoding) {
  4904. // Buffer#write(string)
  4905. if (offset === undefined) {
  4906. encoding = 'utf8'
  4907. length = this.length
  4908. offset = 0
  4909. // Buffer#write(string, encoding)
  4910. } else if (length === undefined && typeof offset === 'string') {
  4911. encoding = offset
  4912. length = this.length
  4913. offset = 0
  4914. // Buffer#write(string, offset[, length][, encoding])
  4915. } else if (isFinite(offset)) {
  4916. offset = offset | 0
  4917. if (isFinite(length)) {
  4918. length = length | 0
  4919. if (encoding === undefined) encoding = 'utf8'
  4920. } else {
  4921. encoding = length
  4922. length = undefined
  4923. }
  4924. // legacy write(string, encoding, offset, length) - remove in v0.13
  4925. } else {
  4926. var swap = encoding
  4927. encoding = offset
  4928. offset = length | 0
  4929. length = swap
  4930. }
  4931. var remaining = this.length - offset
  4932. if (length === undefined || length > remaining) length = remaining
  4933. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  4934. throw new RangeError('attempt to write outside buffer bounds')
  4935. }
  4936. if (!encoding) encoding = 'utf8'
  4937. var loweredCase = false
  4938. for (;;) {
  4939. switch (encoding) {
  4940. case 'hex':
  4941. return hexWrite(this, string, offset, length)
  4942. case 'utf8':
  4943. case 'utf-8':
  4944. return utf8Write(this, string, offset, length)
  4945. case 'ascii':
  4946. return asciiWrite(this, string, offset, length)
  4947. case 'binary':
  4948. return binaryWrite(this, string, offset, length)
  4949. case 'base64':
  4950. // Warning: maxLength not taken into account in base64Write
  4951. return base64Write(this, string, offset, length)
  4952. case 'ucs2':
  4953. case 'ucs-2':
  4954. case 'utf16le':
  4955. case 'utf-16le':
  4956. return ucs2Write(this, string, offset, length)
  4957. default:
  4958. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  4959. encoding = ('' + encoding).toLowerCase()
  4960. loweredCase = true
  4961. }
  4962. }
  4963. }
  4964. Buffer.prototype.toJSON = function toJSON () {
  4965. return {
  4966. type: 'Buffer',
  4967. data: Array.prototype.slice.call(this._arr || this, 0)
  4968. }
  4969. }
  4970. function base64Slice (buf, start, end) {
  4971. if (start === 0 && end === buf.length) {
  4972. return base64.fromByteArray(buf)
  4973. } else {
  4974. return base64.fromByteArray(buf.slice(start, end))
  4975. }
  4976. }
  4977. function utf8Slice (buf, start, end) {
  4978. end = Math.min(buf.length, end)
  4979. var res = []
  4980. var i = start
  4981. while (i < end) {
  4982. var firstByte = buf[i]
  4983. var codePoint = null
  4984. var bytesPerSequence = (firstByte > 0xEF) ? 4
  4985. : (firstByte > 0xDF) ? 3
  4986. : (firstByte > 0xBF) ? 2
  4987. : 1
  4988. if (i + bytesPerSequence <= end) {
  4989. var secondByte, thirdByte, fourthByte, tempCodePoint
  4990. switch (bytesPerSequence) {
  4991. case 1:
  4992. if (firstByte < 0x80) {
  4993. codePoint = firstByte
  4994. }
  4995. break
  4996. case 2:
  4997. secondByte = buf[i + 1]
  4998. if ((secondByte & 0xC0) === 0x80) {
  4999. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  5000. if (tempCodePoint > 0x7F) {
  5001. codePoint = tempCodePoint
  5002. }
  5003. }
  5004. break
  5005. case 3:
  5006. secondByte = buf[i + 1]
  5007. thirdByte = buf[i + 2]
  5008. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  5009. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  5010. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  5011. codePoint = tempCodePoint
  5012. }
  5013. }
  5014. break
  5015. case 4:
  5016. secondByte = buf[i + 1]
  5017. thirdByte = buf[i + 2]
  5018. fourthByte = buf[i + 3]
  5019. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  5020. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  5021. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  5022. codePoint = tempCodePoint
  5023. }
  5024. }
  5025. }
  5026. }
  5027. if (codePoint === null) {
  5028. // we did not generate a valid codePoint so insert a
  5029. // replacement char (U+FFFD) and advance only 1 byte
  5030. codePoint = 0xFFFD
  5031. bytesPerSequence = 1
  5032. } else if (codePoint > 0xFFFF) {
  5033. // encode to utf16 (surrogate pair dance)
  5034. codePoint -= 0x10000
  5035. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  5036. codePoint = 0xDC00 | codePoint & 0x3FF
  5037. }
  5038. res.push(codePoint)
  5039. i += bytesPerSequence
  5040. }
  5041. return decodeCodePointsArray(res)
  5042. }
  5043. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  5044. // the lowest limit is Chrome, with 0x10000 args.
  5045. // We go 1 magnitude less, for safety
  5046. var MAX_ARGUMENTS_LENGTH = 0x1000
  5047. function decodeCodePointsArray (codePoints) {
  5048. var len = codePoints.length
  5049. if (len <= MAX_ARGUMENTS_LENGTH) {
  5050. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  5051. }
  5052. // Decode in chunks to avoid "call stack size exceeded".
  5053. var res = ''
  5054. var i = 0
  5055. while (i < len) {
  5056. res += String.fromCharCode.apply(
  5057. String,
  5058. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  5059. )
  5060. }
  5061. return res
  5062. }
  5063. function asciiSlice (buf, start, end) {
  5064. var ret = ''
  5065. end = Math.min(buf.length, end)
  5066. for (var i = start; i < end; i++) {
  5067. ret += String.fromCharCode(buf[i] & 0x7F)
  5068. }
  5069. return ret
  5070. }
  5071. function binarySlice (buf, start, end) {
  5072. var ret = ''
  5073. end = Math.min(buf.length, end)
  5074. for (var i = start; i < end; i++) {
  5075. ret += String.fromCharCode(buf[i])
  5076. }
  5077. return ret
  5078. }
  5079. function hexSlice (buf, start, end) {
  5080. var len = buf.length
  5081. if (!start || start < 0) start = 0
  5082. if (!end || end < 0 || end > len) end = len
  5083. var out = ''
  5084. for (var i = start; i < end; i++) {
  5085. out += toHex(buf[i])
  5086. }
  5087. return out
  5088. }
  5089. function utf16leSlice (buf, start, end) {
  5090. var bytes = buf.slice(start, end)
  5091. var res = ''
  5092. for (var i = 0; i < bytes.length; i += 2) {
  5093. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  5094. }
  5095. return res
  5096. }
  5097. Buffer.prototype.slice = function slice (start, end) {
  5098. var len = this.length
  5099. start = ~~start
  5100. end = end === undefined ? len : ~~end
  5101. if (start < 0) {
  5102. start += len
  5103. if (start < 0) start = 0
  5104. } else if (start > len) {
  5105. start = len
  5106. }
  5107. if (end < 0) {
  5108. end += len
  5109. if (end < 0) end = 0
  5110. } else if (end > len) {
  5111. end = len
  5112. }
  5113. if (end < start) end = start
  5114. var newBuf
  5115. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5116. newBuf = Buffer._augment(this.subarray(start, end))
  5117. } else {
  5118. var sliceLen = end - start
  5119. newBuf = new Buffer(sliceLen, undefined)
  5120. for (var i = 0; i < sliceLen; i++) {
  5121. newBuf[i] = this[i + start]
  5122. }
  5123. }
  5124. if (newBuf.length) newBuf.parent = this.parent || this
  5125. return newBuf
  5126. }
  5127. /*
  5128. * Need to make sure that buffer isn't trying to write out of bounds.
  5129. */
  5130. function checkOffset (offset, ext, length) {
  5131. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  5132. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  5133. }
  5134. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  5135. offset = offset | 0
  5136. byteLength = byteLength | 0
  5137. if (!noAssert) checkOffset(offset, byteLength, this.length)
  5138. var val = this[offset]
  5139. var mul = 1
  5140. var i = 0
  5141. while (++i < byteLength && (mul *= 0x100)) {
  5142. val += this[offset + i] * mul
  5143. }
  5144. return val
  5145. }
  5146. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  5147. offset = offset | 0
  5148. byteLength = byteLength | 0
  5149. if (!noAssert) {
  5150. checkOffset(offset, byteLength, this.length)
  5151. }
  5152. var val = this[offset + --byteLength]
  5153. var mul = 1
  5154. while (byteLength > 0 && (mul *= 0x100)) {
  5155. val += this[offset + --byteLength] * mul
  5156. }
  5157. return val
  5158. }
  5159. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  5160. if (!noAssert) checkOffset(offset, 1, this.length)
  5161. return this[offset]
  5162. }
  5163. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  5164. if (!noAssert) checkOffset(offset, 2, this.length)
  5165. return this[offset] | (this[offset + 1] << 8)
  5166. }
  5167. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  5168. if (!noAssert) checkOffset(offset, 2, this.length)
  5169. return (this[offset] << 8) | this[offset + 1]
  5170. }
  5171. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  5172. if (!noAssert) checkOffset(offset, 4, this.length)
  5173. return ((this[offset]) |
  5174. (this[offset + 1] << 8) |
  5175. (this[offset + 2] << 16)) +
  5176. (this[offset + 3] * 0x1000000)
  5177. }
  5178. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  5179. if (!noAssert) checkOffset(offset, 4, this.length)
  5180. return (this[offset] * 0x1000000) +
  5181. ((this[offset + 1] << 16) |
  5182. (this[offset + 2] << 8) |
  5183. this[offset + 3])
  5184. }
  5185. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  5186. offset = offset | 0
  5187. byteLength = byteLength | 0
  5188. if (!noAssert) checkOffset(offset, byteLength, this.length)
  5189. var val = this[offset]
  5190. var mul = 1
  5191. var i = 0
  5192. while (++i < byteLength && (mul *= 0x100)) {
  5193. val += this[offset + i] * mul
  5194. }
  5195. mul *= 0x80
  5196. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  5197. return val
  5198. }
  5199. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  5200. offset = offset | 0
  5201. byteLength = byteLength | 0
  5202. if (!noAssert) checkOffset(offset, byteLength, this.length)
  5203. var i = byteLength
  5204. var mul = 1
  5205. var val = this[offset + --i]
  5206. while (i > 0 && (mul *= 0x100)) {
  5207. val += this[offset + --i] * mul
  5208. }
  5209. mul *= 0x80
  5210. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  5211. return val
  5212. }
  5213. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  5214. if (!noAssert) checkOffset(offset, 1, this.length)
  5215. if (!(this[offset] & 0x80)) return (this[offset])
  5216. return ((0xff - this[offset] + 1) * -1)
  5217. }
  5218. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  5219. if (!noAssert) checkOffset(offset, 2, this.length)
  5220. var val = this[offset] | (this[offset + 1] << 8)
  5221. return (val & 0x8000) ? val | 0xFFFF0000 : val
  5222. }
  5223. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  5224. if (!noAssert) checkOffset(offset, 2, this.length)
  5225. var val = this[offset + 1] | (this[offset] << 8)
  5226. return (val & 0x8000) ? val | 0xFFFF0000 : val
  5227. }
  5228. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  5229. if (!noAssert) checkOffset(offset, 4, this.length)
  5230. return (this[offset]) |
  5231. (this[offset + 1] << 8) |
  5232. (this[offset + 2] << 16) |
  5233. (this[offset + 3] << 24)
  5234. }
  5235. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  5236. if (!noAssert) checkOffset(offset, 4, this.length)
  5237. return (this[offset] << 24) |
  5238. (this[offset + 1] << 16) |
  5239. (this[offset + 2] << 8) |
  5240. (this[offset + 3])
  5241. }
  5242. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  5243. if (!noAssert) checkOffset(offset, 4, this.length)
  5244. return ieee754.read(this, offset, true, 23, 4)
  5245. }
  5246. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  5247. if (!noAssert) checkOffset(offset, 4, this.length)
  5248. return ieee754.read(this, offset, false, 23, 4)
  5249. }
  5250. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  5251. if (!noAssert) checkOffset(offset, 8, this.length)
  5252. return ieee754.read(this, offset, true, 52, 8)
  5253. }
  5254. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  5255. if (!noAssert) checkOffset(offset, 8, this.length)
  5256. return ieee754.read(this, offset, false, 52, 8)
  5257. }
  5258. function checkInt (buf, value, offset, ext, max, min) {
  5259. if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
  5260. if (value > max || value < min) throw new RangeError('value is out of bounds')
  5261. if (offset + ext > buf.length) throw new RangeError('index out of range')
  5262. }
  5263. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  5264. value = +value
  5265. offset = offset | 0
  5266. byteLength = byteLength | 0
  5267. if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  5268. var mul = 1
  5269. var i = 0
  5270. this[offset] = value & 0xFF
  5271. while (++i < byteLength && (mul *= 0x100)) {
  5272. this[offset + i] = (value / mul) & 0xFF
  5273. }
  5274. return offset + byteLength
  5275. }
  5276. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  5277. value = +value
  5278. offset = offset | 0
  5279. byteLength = byteLength | 0
  5280. if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  5281. var i = byteLength - 1
  5282. var mul = 1
  5283. this[offset + i] = value & 0xFF
  5284. while (--i >= 0 && (mul *= 0x100)) {
  5285. this[offset + i] = (value / mul) & 0xFF
  5286. }
  5287. return offset + byteLength
  5288. }
  5289. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  5290. value = +value
  5291. offset = offset | 0
  5292. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  5293. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  5294. this[offset] = (value & 0xff)
  5295. return offset + 1
  5296. }
  5297. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  5298. if (value < 0) value = 0xffff + value + 1
  5299. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  5300. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  5301. (littleEndian ? i : 1 - i) * 8
  5302. }
  5303. }
  5304. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  5305. value = +value
  5306. offset = offset | 0
  5307. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  5308. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5309. this[offset] = (value & 0xff)
  5310. this[offset + 1] = (value >>> 8)
  5311. } else {
  5312. objectWriteUInt16(this, value, offset, true)
  5313. }
  5314. return offset + 2
  5315. }
  5316. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  5317. value = +value
  5318. offset = offset | 0
  5319. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  5320. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5321. this[offset] = (value >>> 8)
  5322. this[offset + 1] = (value & 0xff)
  5323. } else {
  5324. objectWriteUInt16(this, value, offset, false)
  5325. }
  5326. return offset + 2
  5327. }
  5328. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  5329. if (value < 0) value = 0xffffffff + value + 1
  5330. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  5331. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  5332. }
  5333. }
  5334. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  5335. value = +value
  5336. offset = offset | 0
  5337. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  5338. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5339. this[offset + 3] = (value >>> 24)
  5340. this[offset + 2] = (value >>> 16)
  5341. this[offset + 1] = (value >>> 8)
  5342. this[offset] = (value & 0xff)
  5343. } else {
  5344. objectWriteUInt32(this, value, offset, true)
  5345. }
  5346. return offset + 4
  5347. }
  5348. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  5349. value = +value
  5350. offset = offset | 0
  5351. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  5352. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5353. this[offset] = (value >>> 24)
  5354. this[offset + 1] = (value >>> 16)
  5355. this[offset + 2] = (value >>> 8)
  5356. this[offset + 3] = (value & 0xff)
  5357. } else {
  5358. objectWriteUInt32(this, value, offset, false)
  5359. }
  5360. return offset + 4
  5361. }
  5362. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  5363. value = +value
  5364. offset = offset | 0
  5365. if (!noAssert) {
  5366. var limit = Math.pow(2, 8 * byteLength - 1)
  5367. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  5368. }
  5369. var i = 0
  5370. var mul = 1
  5371. var sub = value < 0 ? 1 : 0
  5372. this[offset] = value & 0xFF
  5373. while (++i < byteLength && (mul *= 0x100)) {
  5374. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  5375. }
  5376. return offset + byteLength
  5377. }
  5378. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  5379. value = +value
  5380. offset = offset | 0
  5381. if (!noAssert) {
  5382. var limit = Math.pow(2, 8 * byteLength - 1)
  5383. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  5384. }
  5385. var i = byteLength - 1
  5386. var mul = 1
  5387. var sub = value < 0 ? 1 : 0
  5388. this[offset + i] = value & 0xFF
  5389. while (--i >= 0 && (mul *= 0x100)) {
  5390. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  5391. }
  5392. return offset + byteLength
  5393. }
  5394. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  5395. value = +value
  5396. offset = offset | 0
  5397. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  5398. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  5399. if (value < 0) value = 0xff + value + 1
  5400. this[offset] = (value & 0xff)
  5401. return offset + 1
  5402. }
  5403. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  5404. value = +value
  5405. offset = offset | 0
  5406. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  5407. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5408. this[offset] = (value & 0xff)
  5409. this[offset + 1] = (value >>> 8)
  5410. } else {
  5411. objectWriteUInt16(this, value, offset, true)
  5412. }
  5413. return offset + 2
  5414. }
  5415. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  5416. value = +value
  5417. offset = offset | 0
  5418. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  5419. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5420. this[offset] = (value >>> 8)
  5421. this[offset + 1] = (value & 0xff)
  5422. } else {
  5423. objectWriteUInt16(this, value, offset, false)
  5424. }
  5425. return offset + 2
  5426. }
  5427. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  5428. value = +value
  5429. offset = offset | 0
  5430. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  5431. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5432. this[offset] = (value & 0xff)
  5433. this[offset + 1] = (value >>> 8)
  5434. this[offset + 2] = (value >>> 16)
  5435. this[offset + 3] = (value >>> 24)
  5436. } else {
  5437. objectWriteUInt32(this, value, offset, true)
  5438. }
  5439. return offset + 4
  5440. }
  5441. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  5442. value = +value
  5443. offset = offset | 0
  5444. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  5445. if (value < 0) value = 0xffffffff + value + 1
  5446. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5447. this[offset] = (value >>> 24)
  5448. this[offset + 1] = (value >>> 16)
  5449. this[offset + 2] = (value >>> 8)
  5450. this[offset + 3] = (value & 0xff)
  5451. } else {
  5452. objectWriteUInt32(this, value, offset, false)
  5453. }
  5454. return offset + 4
  5455. }
  5456. function checkIEEE754 (buf, value, offset, ext, max, min) {
  5457. if (value > max || value < min) throw new RangeError('value is out of bounds')
  5458. if (offset + ext > buf.length) throw new RangeError('index out of range')
  5459. if (offset < 0) throw new RangeError('index out of range')
  5460. }
  5461. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  5462. if (!noAssert) {
  5463. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  5464. }
  5465. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  5466. return offset + 4
  5467. }
  5468. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  5469. return writeFloat(this, value, offset, true, noAssert)
  5470. }
  5471. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  5472. return writeFloat(this, value, offset, false, noAssert)
  5473. }
  5474. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  5475. if (!noAssert) {
  5476. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  5477. }
  5478. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  5479. return offset + 8
  5480. }
  5481. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  5482. return writeDouble(this, value, offset, true, noAssert)
  5483. }
  5484. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  5485. return writeDouble(this, value, offset, false, noAssert)
  5486. }
  5487. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  5488. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  5489. if (!start) start = 0
  5490. if (!end && end !== 0) end = this.length
  5491. if (targetStart >= target.length) targetStart = target.length
  5492. if (!targetStart) targetStart = 0
  5493. if (end > 0 && end < start) end = start
  5494. // Copy 0 bytes; we're done
  5495. if (end === start) return 0
  5496. if (target.length === 0 || this.length === 0) return 0
  5497. // Fatal error conditions
  5498. if (targetStart < 0) {
  5499. throw new RangeError('targetStart out of bounds')
  5500. }
  5501. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  5502. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  5503. // Are we oob?
  5504. if (end > this.length) end = this.length
  5505. if (target.length - targetStart < end - start) {
  5506. end = target.length - targetStart + start
  5507. }
  5508. var len = end - start
  5509. var i
  5510. if (this === target && start < targetStart && targetStart < end) {
  5511. // descending copy from end
  5512. for (i = len - 1; i >= 0; i--) {
  5513. target[i + targetStart] = this[i + start]
  5514. }
  5515. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  5516. // ascending copy from start
  5517. for (i = 0; i < len; i++) {
  5518. target[i + targetStart] = this[i + start]
  5519. }
  5520. } else {
  5521. target._set(this.subarray(start, start + len), targetStart)
  5522. }
  5523. return len
  5524. }
  5525. // fill(value, start=0, end=buffer.length)
  5526. Buffer.prototype.fill = function fill (value, start, end) {
  5527. if (!value) value = 0
  5528. if (!start) start = 0
  5529. if (!end) end = this.length
  5530. if (end < start) throw new RangeError('end < start')
  5531. // Fill 0 bytes; we're done
  5532. if (end === start) return
  5533. if (this.length === 0) return
  5534. if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
  5535. if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
  5536. var i
  5537. if (typeof value === 'number') {
  5538. for (i = start; i < end; i++) {
  5539. this[i] = value
  5540. }
  5541. } else {
  5542. var bytes = utf8ToBytes(value.toString())
  5543. var len = bytes.length
  5544. for (i = start; i < end; i++) {
  5545. this[i] = bytes[i % len]
  5546. }
  5547. }
  5548. return this
  5549. }
  5550. /**
  5551. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  5552. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  5553. */
  5554. Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
  5555. if (typeof Uint8Array !== 'undefined') {
  5556. if (Buffer.TYPED_ARRAY_SUPPORT) {
  5557. return (new Buffer(this)).buffer
  5558. } else {
  5559. var buf = new Uint8Array(this.length)
  5560. for (var i = 0, len = buf.length; i < len; i += 1) {
  5561. buf[i] = this[i]
  5562. }
  5563. return buf.buffer
  5564. }
  5565. } else {
  5566. throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
  5567. }
  5568. }
  5569. // HELPER FUNCTIONS
  5570. // ================
  5571. var BP = Buffer.prototype
  5572. /**
  5573. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  5574. */
  5575. Buffer._augment = function _augment (arr) {
  5576. arr.constructor = Buffer
  5577. arr._isBuffer = true
  5578. // save reference to original Uint8Array set method before overwriting
  5579. arr._set = arr.set
  5580. // deprecated
  5581. arr.get = BP.get
  5582. arr.set = BP.set
  5583. arr.write = BP.write
  5584. arr.toString = BP.toString
  5585. arr.toLocaleString = BP.toString
  5586. arr.toJSON = BP.toJSON
  5587. arr.equals = BP.equals
  5588. arr.compare = BP.compare
  5589. arr.indexOf = BP.indexOf
  5590. arr.copy = BP.copy
  5591. arr.slice = BP.slice
  5592. arr.readUIntLE = BP.readUIntLE
  5593. arr.readUIntBE = BP.readUIntBE
  5594. arr.readUInt8 = BP.readUInt8
  5595. arr.readUInt16LE = BP.readUInt16LE
  5596. arr.readUInt16BE = BP.readUInt16BE
  5597. arr.readUInt32LE = BP.readUInt32LE
  5598. arr.readUInt32BE = BP.readUInt32BE
  5599. arr.readIntLE = BP.readIntLE
  5600. arr.readIntBE = BP.readIntBE
  5601. arr.readInt8 = BP.readInt8
  5602. arr.readInt16LE = BP.readInt16LE
  5603. arr.readInt16BE = BP.readInt16BE
  5604. arr.readInt32LE = BP.readInt32LE
  5605. arr.readInt32BE = BP.readInt32BE
  5606. arr.readFloatLE = BP.readFloatLE
  5607. arr.readFloatBE = BP.readFloatBE
  5608. arr.readDoubleLE = BP.readDoubleLE
  5609. arr.readDoubleBE = BP.readDoubleBE
  5610. arr.writeUInt8 = BP.writeUInt8
  5611. arr.writeUIntLE = BP.writeUIntLE
  5612. arr.writeUIntBE = BP.writeUIntBE
  5613. arr.writeUInt16LE = BP.writeUInt16LE
  5614. arr.writeUInt16BE = BP.writeUInt16BE
  5615. arr.writeUInt32LE = BP.writeUInt32LE
  5616. arr.writeUInt32BE = BP.writeUInt32BE
  5617. arr.writeIntLE = BP.writeIntLE
  5618. arr.writeIntBE = BP.writeIntBE
  5619. arr.writeInt8 = BP.writeInt8
  5620. arr.writeInt16LE = BP.writeInt16LE
  5621. arr.writeInt16BE = BP.writeInt16BE
  5622. arr.writeInt32LE = BP.writeInt32LE
  5623. arr.writeInt32BE = BP.writeInt32BE
  5624. arr.writeFloatLE = BP.writeFloatLE
  5625. arr.writeFloatBE = BP.writeFloatBE
  5626. arr.writeDoubleLE = BP.writeDoubleLE
  5627. arr.writeDoubleBE = BP.writeDoubleBE
  5628. arr.fill = BP.fill
  5629. arr.inspect = BP.inspect
  5630. arr.toArrayBuffer = BP.toArrayBuffer
  5631. return arr
  5632. }
  5633. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  5634. function base64clean (str) {
  5635. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  5636. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  5637. // Node converts strings with length < 2 to ''
  5638. if (str.length < 2) return ''
  5639. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  5640. while (str.length % 4 !== 0) {
  5641. str = str + '='
  5642. }
  5643. return str
  5644. }
  5645. function stringtrim (str) {
  5646. if (str.trim) return str.trim()
  5647. return str.replace(/^\s+|\s+$/g, '')
  5648. }
  5649. function toHex (n) {
  5650. if (n < 16) return '0' + n.toString(16)
  5651. return n.toString(16)
  5652. }
  5653. function utf8ToBytes (string, units) {
  5654. units = units || Infinity
  5655. var codePoint
  5656. var length = string.length
  5657. var leadSurrogate = null
  5658. var bytes = []
  5659. for (var i = 0; i < length; i++) {
  5660. codePoint = string.charCodeAt(i)
  5661. // is surrogate component
  5662. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  5663. // last char was a lead
  5664. if (!leadSurrogate) {
  5665. // no lead yet
  5666. if (codePoint > 0xDBFF) {
  5667. // unexpected trail
  5668. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5669. continue
  5670. } else if (i + 1 === length) {
  5671. // unpaired lead
  5672. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5673. continue
  5674. }
  5675. // valid lead
  5676. leadSurrogate = codePoint
  5677. continue
  5678. }
  5679. // 2 leads in a row
  5680. if (codePoint < 0xDC00) {
  5681. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5682. leadSurrogate = codePoint
  5683. continue
  5684. }
  5685. // valid surrogate pair
  5686. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  5687. } else if (leadSurrogate) {
  5688. // valid bmp char, but last char was a lead
  5689. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5690. }
  5691. leadSurrogate = null
  5692. // encode utf8
  5693. if (codePoint < 0x80) {
  5694. if ((units -= 1) < 0) break
  5695. bytes.push(codePoint)
  5696. } else if (codePoint < 0x800) {
  5697. if ((units -= 2) < 0) break
  5698. bytes.push(
  5699. codePoint >> 0x6 | 0xC0,
  5700. codePoint & 0x3F | 0x80
  5701. )
  5702. } else if (codePoint < 0x10000) {
  5703. if ((units -= 3) < 0) break
  5704. bytes.push(
  5705. codePoint >> 0xC | 0xE0,
  5706. codePoint >> 0x6 & 0x3F | 0x80,
  5707. codePoint & 0x3F | 0x80
  5708. )
  5709. } else if (codePoint < 0x110000) {
  5710. if ((units -= 4) < 0) break
  5711. bytes.push(
  5712. codePoint >> 0x12 | 0xF0,
  5713. codePoint >> 0xC & 0x3F | 0x80,
  5714. codePoint >> 0x6 & 0x3F | 0x80,
  5715. codePoint & 0x3F | 0x80
  5716. )
  5717. } else {
  5718. throw new Error('Invalid code point')
  5719. }
  5720. }
  5721. return bytes
  5722. }
  5723. function asciiToBytes (str) {
  5724. var byteArray = []
  5725. for (var i = 0; i < str.length; i++) {
  5726. // Node's code seems to be doing this and not & 0x7F..
  5727. byteArray.push(str.charCodeAt(i) & 0xFF)
  5728. }
  5729. return byteArray
  5730. }
  5731. function utf16leToBytes (str, units) {
  5732. var c, hi, lo
  5733. var byteArray = []
  5734. for (var i = 0; i < str.length; i++) {
  5735. if ((units -= 2) < 0) break
  5736. c = str.charCodeAt(i)
  5737. hi = c >> 8
  5738. lo = c % 256
  5739. byteArray.push(lo)
  5740. byteArray.push(hi)
  5741. }
  5742. return byteArray
  5743. }
  5744. function base64ToBytes (str) {
  5745. return base64.toByteArray(base64clean(str))
  5746. }
  5747. function blitBuffer (src, dst, offset, length) {
  5748. for (var i = 0; i < length; i++) {
  5749. if ((i + offset >= dst.length) || (i >= src.length)) break
  5750. dst[i + offset] = src[i]
  5751. }
  5752. return i
  5753. }
  5754. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5755. },{"base64-js":1,"ieee754":5,"isarray":4}],4:[function(require,module,exports){
  5756. var toString = {}.toString;
  5757. module.exports = Array.isArray || function (arr) {
  5758. return toString.call(arr) == '[object Array]';
  5759. };
  5760. },{}],5:[function(require,module,exports){
  5761. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5762. var e, m
  5763. var eLen = (nBytes * 8) - mLen - 1
  5764. var eMax = (1 << eLen) - 1
  5765. var eBias = eMax >> 1
  5766. var nBits = -7
  5767. var i = isLE ? (nBytes - 1) : 0
  5768. var d = isLE ? -1 : 1
  5769. var s = buffer[offset + i]
  5770. i += d
  5771. e = s & ((1 << (-nBits)) - 1)
  5772. s >>= (-nBits)
  5773. nBits += eLen
  5774. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5775. m = e & ((1 << (-nBits)) - 1)
  5776. e >>= (-nBits)
  5777. nBits += mLen
  5778. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5779. if (e === 0) {
  5780. e = 1 - eBias
  5781. } else if (e === eMax) {
  5782. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5783. } else {
  5784. m = m + Math.pow(2, mLen)
  5785. e = e - eBias
  5786. }
  5787. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5788. }
  5789. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5790. var e, m, c
  5791. var eLen = (nBytes * 8) - mLen - 1
  5792. var eMax = (1 << eLen) - 1
  5793. var eBias = eMax >> 1
  5794. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5795. var i = isLE ? 0 : (nBytes - 1)
  5796. var d = isLE ? 1 : -1
  5797. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5798. value = Math.abs(value)
  5799. if (isNaN(value) || value === Infinity) {
  5800. m = isNaN(value) ? 1 : 0
  5801. e = eMax
  5802. } else {
  5803. e = Math.floor(Math.log(value) / Math.LN2)
  5804. if (value * (c = Math.pow(2, -e)) < 1) {
  5805. e--
  5806. c *= 2
  5807. }
  5808. if (e + eBias >= 1) {
  5809. value += rt / c
  5810. } else {
  5811. value += rt * Math.pow(2, 1 - eBias)
  5812. }
  5813. if (value * c >= 2) {
  5814. e++
  5815. c /= 2
  5816. }
  5817. if (e + eBias >= eMax) {
  5818. m = 0
  5819. e = eMax
  5820. } else if (e + eBias >= 1) {
  5821. m = ((value * c) - 1) * Math.pow(2, mLen)
  5822. e = e + eBias
  5823. } else {
  5824. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5825. e = 0
  5826. }
  5827. }
  5828. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5829. e = (e << mLen) | m
  5830. eLen += mLen
  5831. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5832. buffer[offset + i - d] |= s * 128
  5833. }
  5834. },{}],6:[function(require,module,exports){
  5835. var Pipe = require('../pipe').Pipe;
  5836. var Context = function Context(){
  5837. };
  5838. Context.prototype.setResult = function(result) {
  5839. this.result = result;
  5840. this.hasResult = true;
  5841. return this;
  5842. };
  5843. Context.prototype.exit = function() {
  5844. this.exiting = true;
  5845. return this;
  5846. };
  5847. Context.prototype.switchTo = function(next, pipe) {
  5848. if (typeof next === 'string' || next instanceof Pipe) {
  5849. this.nextPipe = next;
  5850. } else {
  5851. this.next = next;
  5852. if (pipe) {
  5853. this.nextPipe = pipe;
  5854. }
  5855. }
  5856. return this;
  5857. };
  5858. Context.prototype.push = function(child, name) {
  5859. child.parent = this;
  5860. if (typeof name !== 'undefined') {
  5861. child.childName = name;
  5862. }
  5863. child.root = this.root || this;
  5864. child.options = child.options || this.options;
  5865. if (!this.children) {
  5866. this.children = [child];
  5867. this.nextAfterChildren = this.next || null;
  5868. this.next = child;
  5869. } else {
  5870. this.children[this.children.length - 1].next = child;
  5871. this.children.push(child);
  5872. }
  5873. child.next = this;
  5874. return this;
  5875. };
  5876. exports.Context = Context;
  5877. },{"../pipe":20}],7:[function(require,module,exports){
  5878. var Context = require('./context').Context;
  5879. var dateReviver = require('../date-reviver');
  5880. var DiffContext = function DiffContext(left, right) {
  5881. this.left = left;
  5882. this.right = right;
  5883. this.pipe = 'diff';
  5884. };
  5885. DiffContext.prototype = new Context();
  5886. DiffContext.prototype.setResult = function(result) {
  5887. if (this.options.cloneDiffValues) {
  5888. var clone = typeof this.options.cloneDiffValues === 'function' ?
  5889. this.options.cloneDiffValues : function(value) {
  5890. return JSON.parse(JSON.stringify(value), dateReviver);
  5891. };
  5892. if (typeof result[0] === 'object') {
  5893. result[0] = clone(result[0]);
  5894. }
  5895. if (typeof result[1] === 'object') {
  5896. result[1] = clone(result[1]);
  5897. }
  5898. }
  5899. return Context.prototype.setResult.apply(this, arguments);
  5900. };
  5901. exports.DiffContext = DiffContext;
  5902. },{"../date-reviver":10,"./context":6}],8:[function(require,module,exports){
  5903. var Context = require('./context').Context;
  5904. var PatchContext = function PatchContext(left, delta) {
  5905. this.left = left;
  5906. this.delta = delta;
  5907. this.pipe = 'patch';
  5908. };
  5909. PatchContext.prototype = new Context();
  5910. exports.PatchContext = PatchContext;
  5911. },{"./context":6}],9:[function(require,module,exports){
  5912. var Context = require('./context').Context;
  5913. var ReverseContext = function ReverseContext(delta) {
  5914. this.delta = delta;
  5915. this.pipe = 'reverse';
  5916. };
  5917. ReverseContext.prototype = new Context();
  5918. exports.ReverseContext = ReverseContext;
  5919. },{"./context":6}],10:[function(require,module,exports){
  5920. // use as 2nd parameter for JSON.parse to revive Date instances
  5921. module.exports = function dateReviver(key, value) {
  5922. var parts;
  5923. if (typeof value === 'string') {
  5924. parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value);
  5925. if (parts) {
  5926. return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +(parts[7] || 0)));
  5927. }
  5928. }
  5929. return value;
  5930. };
  5931. },{}],11:[function(require,module,exports){
  5932. var Processor = require('./processor').Processor;
  5933. var Pipe = require('./pipe').Pipe;
  5934. var DiffContext = require('./contexts/diff').DiffContext;
  5935. var PatchContext = require('./contexts/patch').PatchContext;
  5936. var ReverseContext = require('./contexts/reverse').ReverseContext;
  5937. var trivial = require('./filters/trivial');
  5938. var nested = require('./filters/nested');
  5939. var arrays = require('./filters/arrays');
  5940. var dates = require('./filters/dates');
  5941. var texts = require('./filters/texts');
  5942. var DiffPatcher = function DiffPatcher(options) {
  5943. this.processor = new Processor(options);
  5944. this.processor.pipe(new Pipe('diff').append(
  5945. nested.collectChildrenDiffFilter,
  5946. trivial.diffFilter,
  5947. dates.diffFilter,
  5948. texts.diffFilter,
  5949. nested.objectsDiffFilter,
  5950. arrays.diffFilter
  5951. ).shouldHaveResult());
  5952. this.processor.pipe(new Pipe('patch').append(
  5953. nested.collectChildrenPatchFilter,
  5954. arrays.collectChildrenPatchFilter,
  5955. trivial.patchFilter,
  5956. texts.patchFilter,
  5957. nested.patchFilter,
  5958. arrays.patchFilter
  5959. ).shouldHaveResult());
  5960. this.processor.pipe(new Pipe('reverse').append(
  5961. nested.collectChildrenReverseFilter,
  5962. arrays.collectChildrenReverseFilter,
  5963. trivial.reverseFilter,
  5964. texts.reverseFilter,
  5965. nested.reverseFilter,
  5966. arrays.reverseFilter
  5967. ).shouldHaveResult());
  5968. };
  5969. DiffPatcher.prototype.options = function() {
  5970. return this.processor.options.apply(this.processor, arguments);
  5971. };
  5972. DiffPatcher.prototype.diff = function(left, right) {
  5973. return this.processor.process(new DiffContext(left, right));
  5974. };
  5975. DiffPatcher.prototype.patch = function(left, delta) {
  5976. return this.processor.process(new PatchContext(left, delta));
  5977. };
  5978. DiffPatcher.prototype.reverse = function(delta) {
  5979. return this.processor.process(new ReverseContext(delta));
  5980. };
  5981. DiffPatcher.prototype.unpatch = function(right, delta) {
  5982. return this.patch(right, this.reverse(delta));
  5983. };
  5984. exports.DiffPatcher = DiffPatcher;
  5985. },{"./contexts/diff":7,"./contexts/patch":8,"./contexts/reverse":9,"./filters/arrays":13,"./filters/dates":14,"./filters/nested":16,"./filters/texts":17,"./filters/trivial":18,"./pipe":20,"./processor":21}],12:[function(require,module,exports){
  5986. exports.isBrowser = typeof window !== 'undefined';
  5987. },{}],13:[function(require,module,exports){
  5988. var DiffContext = require('../contexts/diff').DiffContext;
  5989. var PatchContext = require('../contexts/patch').PatchContext;
  5990. var ReverseContext = require('../contexts/reverse').ReverseContext;
  5991. var lcs = require('./lcs');
  5992. var ARRAY_MOVE = 3;
  5993. var isArray = (typeof Array.isArray === 'function') ?
  5994. // use native function
  5995. Array.isArray :
  5996. // use instanceof operator
  5997. function(a) {
  5998. return a instanceof Array;
  5999. };
  6000. var arrayIndexOf = typeof Array.prototype.indexOf === 'function' ?
  6001. function(array, item) {
  6002. return array.indexOf(item);
  6003. } : function(array, item) {
  6004. var length = array.length;
  6005. for (var i = 0; i < length; i++) {
  6006. if (array[i] === item) {
  6007. return i;
  6008. }
  6009. }
  6010. return -1;
  6011. };
  6012. function arraysHaveMatchByRef(array1, array2, len1, len2) {
  6013. for (var index1 = 0; index1 < len1; index1++) {
  6014. var val1 = array1[index1];
  6015. for (var index2 = 0; index2 < len2; index2++) {
  6016. var val2 = array2[index2];
  6017. if (val1 === val2) {
  6018. return true;
  6019. }
  6020. }
  6021. }
  6022. }
  6023. function matchItems(array1, array2, index1, index2, context) {
  6024. var value1 = array1[index1];
  6025. var value2 = array2[index2];
  6026. if (value1 === value2) {
  6027. return true;
  6028. }
  6029. if (typeof value1 !== 'object' || typeof value2 !== 'object') {
  6030. return false;
  6031. }
  6032. var objectHash = context.objectHash;
  6033. if (!objectHash) {
  6034. // no way to match objects was provided, try match by position
  6035. return context.matchByPosition && index1 === index2;
  6036. }
  6037. var hash1;
  6038. var hash2;
  6039. if (typeof index1 === 'number') {
  6040. context.hashCache1 = context.hashCache1 || [];
  6041. hash1 = context.hashCache1[index1];
  6042. if (typeof hash1 === 'undefined') {
  6043. context.hashCache1[index1] = hash1 = objectHash(value1, index1);
  6044. }
  6045. } else {
  6046. hash1 = objectHash(value1);
  6047. }
  6048. if (typeof hash1 === 'undefined') {
  6049. return false;
  6050. }
  6051. if (typeof index2 === 'number') {
  6052. context.hashCache2 = context.hashCache2 || [];
  6053. hash2 = context.hashCache2[index2];
  6054. if (typeof hash2 === 'undefined') {
  6055. context.hashCache2[index2] = hash2 = objectHash(value2, index2);
  6056. }
  6057. } else {
  6058. hash2 = objectHash(value2);
  6059. }
  6060. if (typeof hash2 === 'undefined') {
  6061. return false;
  6062. }
  6063. return hash1 === hash2;
  6064. }
  6065. var diffFilter = function arraysDiffFilter(context) {
  6066. if (!context.leftIsArray) {
  6067. return;
  6068. }
  6069. var matchContext = {
  6070. objectHash: context.options && context.options.objectHash,
  6071. matchByPosition: context.options && context.options.matchByPosition
  6072. };
  6073. var commonHead = 0;
  6074. var commonTail = 0;
  6075. var index;
  6076. var index1;
  6077. var index2;
  6078. var array1 = context.left;
  6079. var array2 = context.right;
  6080. var len1 = array1.length;
  6081. var len2 = array2.length;
  6082. var child;
  6083. if (len1 > 0 && len2 > 0 && !matchContext.objectHash &&
  6084. typeof matchContext.matchByPosition !== 'boolean') {
  6085. matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
  6086. }
  6087. // separate common head
  6088. while (commonHead < len1 && commonHead < len2 &&
  6089. matchItems(array1, array2, commonHead, commonHead, matchContext)) {
  6090. index = commonHead;
  6091. child = new DiffContext(context.left[index], context.right[index]);
  6092. context.push(child, index);
  6093. commonHead++;
  6094. }
  6095. // separate common tail
  6096. while (commonTail + commonHead < len1 && commonTail + commonHead < len2 &&
  6097. matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
  6098. index1 = len1 - 1 - commonTail;
  6099. index2 = len2 - 1 - commonTail;
  6100. child = new DiffContext(context.left[index1], context.right[index2]);
  6101. context.push(child, index2);
  6102. commonTail++;
  6103. }
  6104. var result;
  6105. if (commonHead + commonTail === len1) {
  6106. if (len1 === len2) {
  6107. // arrays are identical
  6108. context.setResult(undefined).exit();
  6109. return;
  6110. }
  6111. // trivial case, a block (1 or more consecutive items) was added
  6112. result = result || {
  6113. _t: 'a'
  6114. };
  6115. for (index = commonHead; index < len2 - commonTail; index++) {
  6116. result[index] = [array2[index]];
  6117. }
  6118. context.setResult(result).exit();
  6119. return;
  6120. }
  6121. if (commonHead + commonTail === len2) {
  6122. // trivial case, a block (1 or more consecutive items) was removed
  6123. result = result || {
  6124. _t: 'a'
  6125. };
  6126. for (index = commonHead; index < len1 - commonTail; index++) {
  6127. result['_' + index] = [array1[index], 0, 0];
  6128. }
  6129. context.setResult(result).exit();
  6130. return;
  6131. }
  6132. // reset hash cache
  6133. delete matchContext.hashCache1;
  6134. delete matchContext.hashCache2;
  6135. // diff is not trivial, find the LCS (Longest Common Subsequence)
  6136. var trimmed1 = array1.slice(commonHead, len1 - commonTail);
  6137. var trimmed2 = array2.slice(commonHead, len2 - commonTail);
  6138. var seq = lcs.get(
  6139. trimmed1, trimmed2,
  6140. matchItems,
  6141. matchContext
  6142. );
  6143. var removedItems = [];
  6144. result = result || {
  6145. _t: 'a'
  6146. };
  6147. for (index = commonHead; index < len1 - commonTail; index++) {
  6148. if (arrayIndexOf(seq.indices1, index - commonHead) < 0) {
  6149. // removed
  6150. result['_' + index] = [array1[index], 0, 0];
  6151. removedItems.push(index);
  6152. }
  6153. }
  6154. var detectMove = true;
  6155. if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
  6156. detectMove = false;
  6157. }
  6158. var includeValueOnMove = false;
  6159. if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
  6160. includeValueOnMove = true;
  6161. }
  6162. var removedItemsLength = removedItems.length;
  6163. for (index = commonHead; index < len2 - commonTail; index++) {
  6164. var indexOnArray2 = arrayIndexOf(seq.indices2, index - commonHead);
  6165. if (indexOnArray2 < 0) {
  6166. // added, try to match with a removed item and register as position move
  6167. var isMove = false;
  6168. if (detectMove && removedItemsLength > 0) {
  6169. for (var removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
  6170. index1 = removedItems[removeItemIndex1];
  6171. if (matchItems(trimmed1, trimmed2, index1 - commonHead,
  6172. index - commonHead, matchContext)) {
  6173. // store position move as: [originalValue, newPosition, ARRAY_MOVE]
  6174. result['_' + index1].splice(1, 2, index, ARRAY_MOVE);
  6175. if (!includeValueOnMove) {
  6176. // don't include moved value on diff, to save bytes
  6177. result['_' + index1][0] = '';
  6178. }
  6179. index2 = index;
  6180. child = new DiffContext(context.left[index1], context.right[index2]);
  6181. context.push(child, index2);
  6182. removedItems.splice(removeItemIndex1, 1);
  6183. isMove = true;
  6184. break;
  6185. }
  6186. }
  6187. }
  6188. if (!isMove) {
  6189. // added
  6190. result[index] = [array2[index]];
  6191. }
  6192. } else {
  6193. // match, do inner diff
  6194. index1 = seq.indices1[indexOnArray2] + commonHead;
  6195. index2 = seq.indices2[indexOnArray2] + commonHead;
  6196. child = new DiffContext(context.left[index1], context.right[index2]);
  6197. context.push(child, index2);
  6198. }
  6199. }
  6200. context.setResult(result).exit();
  6201. };
  6202. diffFilter.filterName = 'arrays';
  6203. var compare = {
  6204. numerically: function(a, b) {
  6205. return a - b;
  6206. },
  6207. numericallyBy: function(name) {
  6208. return function(a, b) {
  6209. return a[name] - b[name];
  6210. };
  6211. }
  6212. };
  6213. var patchFilter = function nestedPatchFilter(context) {
  6214. if (!context.nested) {
  6215. return;
  6216. }
  6217. if (context.delta._t !== 'a') {
  6218. return;
  6219. }
  6220. var index, index1;
  6221. var delta = context.delta;
  6222. var array = context.left;
  6223. // first, separate removals, insertions and modifications
  6224. var toRemove = [];
  6225. var toInsert = [];
  6226. var toModify = [];
  6227. for (index in delta) {
  6228. if (index !== '_t') {
  6229. if (index[0] === '_') {
  6230. // removed item from original array
  6231. if (delta[index][2] === 0 || delta[index][2] === ARRAY_MOVE) {
  6232. toRemove.push(parseInt(index.slice(1), 10));
  6233. } else {
  6234. throw new Error('only removal or move can be applied at original array indices' +
  6235. ', invalid diff type: ' + delta[index][2]);
  6236. }
  6237. } else {
  6238. if (delta[index].length === 1) {
  6239. // added item at new array
  6240. toInsert.push({
  6241. index: parseInt(index, 10),
  6242. value: delta[index][0]
  6243. });
  6244. } else {
  6245. // modified item at new array
  6246. toModify.push({
  6247. index: parseInt(index, 10),
  6248. delta: delta[index]
  6249. });
  6250. }
  6251. }
  6252. }
  6253. }
  6254. // remove items, in reverse order to avoid sawing our own floor
  6255. toRemove = toRemove.sort(compare.numerically);
  6256. for (index = toRemove.length - 1; index >= 0; index--) {
  6257. index1 = toRemove[index];
  6258. var indexDiff = delta['_' + index1];
  6259. var removedValue = array.splice(index1, 1)[0];
  6260. if (indexDiff[2] === ARRAY_MOVE) {
  6261. // reinsert later
  6262. toInsert.push({
  6263. index: indexDiff[1],
  6264. value: removedValue
  6265. });
  6266. }
  6267. }
  6268. // insert items, in reverse order to avoid moving our own floor
  6269. toInsert = toInsert.sort(compare.numericallyBy('index'));
  6270. var toInsertLength = toInsert.length;
  6271. for (index = 0; index < toInsertLength; index++) {
  6272. var insertion = toInsert[index];
  6273. array.splice(insertion.index, 0, insertion.value);
  6274. }
  6275. // apply modifications
  6276. var toModifyLength = toModify.length;
  6277. var child;
  6278. if (toModifyLength > 0) {
  6279. for (index = 0; index < toModifyLength; index++) {
  6280. var modification = toModify[index];
  6281. child = new PatchContext(context.left[modification.index], modification.delta);
  6282. context.push(child, modification.index);
  6283. }
  6284. }
  6285. if (!context.children) {
  6286. context.setResult(context.left).exit();
  6287. return;
  6288. }
  6289. context.exit();
  6290. };
  6291. patchFilter.filterName = 'arrays';
  6292. var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
  6293. if (!context || !context.children) {
  6294. return;
  6295. }
  6296. if (context.delta._t !== 'a') {
  6297. return;
  6298. }
  6299. var length = context.children.length;
  6300. var child;
  6301. for (var index = 0; index < length; index++) {
  6302. child = context.children[index];
  6303. context.left[child.childName] = child.result;
  6304. }
  6305. context.setResult(context.left).exit();
  6306. };
  6307. collectChildrenPatchFilter.filterName = 'arraysCollectChildren';
  6308. var reverseFilter = function arraysReverseFilter(context) {
  6309. if (!context.nested) {
  6310. if (context.delta[2] === ARRAY_MOVE) {
  6311. context.newName = '_' + context.delta[1];
  6312. context.setResult([context.delta[0], parseInt(context.childName.substr(1), 10), ARRAY_MOVE]).exit();
  6313. }
  6314. return;
  6315. }
  6316. if (context.delta._t !== 'a') {
  6317. return;
  6318. }
  6319. var name, child;
  6320. for (name in context.delta) {
  6321. if (name === '_t') {
  6322. continue;
  6323. }
  6324. child = new ReverseContext(context.delta[name]);
  6325. context.push(child, name);
  6326. }
  6327. context.exit();
  6328. };
  6329. reverseFilter.filterName = 'arrays';
  6330. var reverseArrayDeltaIndex = function(delta, index, itemDelta) {
  6331. if (typeof index === 'string' && index[0] === '_') {
  6332. return parseInt(index.substr(1), 10);
  6333. } else if (isArray(itemDelta) && itemDelta[2] === 0) {
  6334. return '_' + index;
  6335. }
  6336. var reverseIndex = +index;
  6337. for (var deltaIndex in delta) {
  6338. var deltaItem = delta[deltaIndex];
  6339. if (isArray(deltaItem)) {
  6340. if (deltaItem[2] === ARRAY_MOVE) {
  6341. var moveFromIndex = parseInt(deltaIndex.substr(1), 10);
  6342. var moveToIndex = deltaItem[1];
  6343. if (moveToIndex === +index) {
  6344. return moveFromIndex;
  6345. }
  6346. if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
  6347. reverseIndex++;
  6348. } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
  6349. reverseIndex--;
  6350. }
  6351. } else if (deltaItem[2] === 0) {
  6352. var deleteIndex = parseInt(deltaIndex.substr(1), 10);
  6353. if (deleteIndex <= reverseIndex) {
  6354. reverseIndex++;
  6355. }
  6356. } else if (deltaItem.length === 1 && deltaIndex <= reverseIndex) {
  6357. reverseIndex--;
  6358. }
  6359. }
  6360. }
  6361. return reverseIndex;
  6362. };
  6363. var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) {
  6364. if (!context || !context.children) {
  6365. return;
  6366. }
  6367. if (context.delta._t !== 'a') {
  6368. return;
  6369. }
  6370. var length = context.children.length;
  6371. var child;
  6372. var delta = {
  6373. _t: 'a'
  6374. };
  6375. for (var index = 0; index < length; index++) {
  6376. child = context.children[index];
  6377. var name = child.newName;
  6378. if (typeof name === 'undefined') {
  6379. name = reverseArrayDeltaIndex(context.delta, child.childName, child.result);
  6380. }
  6381. if (delta[name] !== child.result) {
  6382. delta[name] = child.result;
  6383. }
  6384. }
  6385. context.setResult(delta).exit();
  6386. };
  6387. collectChildrenReverseFilter.filterName = 'arraysCollectChildren';
  6388. exports.diffFilter = diffFilter;
  6389. exports.patchFilter = patchFilter;
  6390. exports.collectChildrenPatchFilter = collectChildrenPatchFilter;
  6391. exports.reverseFilter = reverseFilter;
  6392. exports.collectChildrenReverseFilter = collectChildrenReverseFilter;
  6393. },{"../contexts/diff":7,"../contexts/patch":8,"../contexts/reverse":9,"./lcs":15}],14:[function(require,module,exports){
  6394. var diffFilter = function datesDiffFilter(context) {
  6395. if (context.left instanceof Date) {
  6396. if (context.right instanceof Date) {
  6397. if (context.left.getTime() !== context.right.getTime()) {
  6398. context.setResult([context.left, context.right]);
  6399. } else {
  6400. context.setResult(undefined);
  6401. }
  6402. } else {
  6403. context.setResult([context.left, context.right]);
  6404. }
  6405. context.exit();
  6406. } else if (context.right instanceof Date) {
  6407. context.setResult([context.left, context.right]).exit();
  6408. }
  6409. };
  6410. diffFilter.filterName = 'dates';
  6411. exports.diffFilter = diffFilter;
  6412. },{}],15:[function(require,module,exports){
  6413. /*
  6414. LCS implementation that supports arrays or strings
  6415. reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
  6416. */
  6417. var defaultMatch = function(array1, array2, index1, index2) {
  6418. return array1[index1] === array2[index2];
  6419. };
  6420. var lengthMatrix = function(array1, array2, match, context) {
  6421. var len1 = array1.length;
  6422. var len2 = array2.length;
  6423. var x, y;
  6424. // initialize empty matrix of len1+1 x len2+1
  6425. var matrix = [len1 + 1];
  6426. for (x = 0; x < len1 + 1; x++) {
  6427. matrix[x] = [len2 + 1];
  6428. for (y = 0; y < len2 + 1; y++) {
  6429. matrix[x][y] = 0;
  6430. }
  6431. }
  6432. matrix.match = match;
  6433. // save sequence lengths for each coordinate
  6434. for (x = 1; x < len1 + 1; x++) {
  6435. for (y = 1; y < len2 + 1; y++) {
  6436. if (match(array1, array2, x - 1, y - 1, context)) {
  6437. matrix[x][y] = matrix[x - 1][y - 1] + 1;
  6438. } else {
  6439. matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);
  6440. }
  6441. }
  6442. }
  6443. return matrix;
  6444. };
  6445. var backtrack = function(matrix, array1, array2, index1, index2, context) {
  6446. if (index1 === 0 || index2 === 0) {
  6447. return {
  6448. sequence: [],
  6449. indices1: [],
  6450. indices2: []
  6451. };
  6452. }
  6453. if (matrix.match(array1, array2, index1 - 1, index2 - 1, context)) {
  6454. var subsequence = backtrack(matrix, array1, array2, index1 - 1, index2 - 1, context);
  6455. subsequence.sequence.push(array1[index1 - 1]);
  6456. subsequence.indices1.push(index1 - 1);
  6457. subsequence.indices2.push(index2 - 1);
  6458. return subsequence;
  6459. }
  6460. if (matrix[index1][index2 - 1] > matrix[index1 - 1][index2]) {
  6461. return backtrack(matrix, array1, array2, index1, index2 - 1, context);
  6462. } else {
  6463. return backtrack(matrix, array1, array2, index1 - 1, index2, context);
  6464. }
  6465. };
  6466. var get = function(array1, array2, match, context) {
  6467. context = context || {};
  6468. var matrix = lengthMatrix(array1, array2, match || defaultMatch, context);
  6469. var result = backtrack(matrix, array1, array2, array1.length, array2.length, context);
  6470. if (typeof array1 === 'string' && typeof array2 === 'string') {
  6471. result.sequence = result.sequence.join('');
  6472. }
  6473. return result;
  6474. };
  6475. exports.get = get;
  6476. },{}],16:[function(require,module,exports){
  6477. var DiffContext = require('../contexts/diff').DiffContext;
  6478. var PatchContext = require('../contexts/patch').PatchContext;
  6479. var ReverseContext = require('../contexts/reverse').ReverseContext;
  6480. var collectChildrenDiffFilter = function collectChildrenDiffFilter(context) {
  6481. if (!context || !context.children) {
  6482. return;
  6483. }
  6484. var length = context.children.length;
  6485. var child;
  6486. var result = context.result;
  6487. for (var index = 0; index < length; index++) {
  6488. child = context.children[index];
  6489. if (typeof child.result === 'undefined') {
  6490. continue;
  6491. }
  6492. result = result || {};
  6493. result[child.childName] = child.result;
  6494. }
  6495. if (result && context.leftIsArray) {
  6496. result._t = 'a';
  6497. }
  6498. context.setResult(result).exit();
  6499. };
  6500. collectChildrenDiffFilter.filterName = 'collectChildren';
  6501. var objectsDiffFilter = function objectsDiffFilter(context) {
  6502. if (context.leftIsArray || context.leftType !== 'object') {
  6503. return;
  6504. }
  6505. var name, child, propertyFilter = context.options.propertyFilter;
  6506. for (name in context.left) {
  6507. if (!Object.prototype.hasOwnProperty.call(context.left, name)) {
  6508. continue;
  6509. }
  6510. if (propertyFilter && !propertyFilter(name, context)) {
  6511. continue;
  6512. }
  6513. child = new DiffContext(context.left[name], context.right[name]);
  6514. context.push(child, name);
  6515. }
  6516. for (name in context.right) {
  6517. if (!Object.prototype.hasOwnProperty.call(context.right, name)) {
  6518. continue;
  6519. }
  6520. if (propertyFilter && !propertyFilter(name, context)) {
  6521. continue;
  6522. }
  6523. if (typeof context.left[name] === 'undefined') {
  6524. child = new DiffContext(undefined, context.right[name]);
  6525. context.push(child, name);
  6526. }
  6527. }
  6528. if (!context.children || context.children.length === 0) {
  6529. context.setResult(undefined).exit();
  6530. return;
  6531. }
  6532. context.exit();
  6533. };
  6534. objectsDiffFilter.filterName = 'objects';
  6535. var patchFilter = function nestedPatchFilter(context) {
  6536. if (!context.nested) {
  6537. return;
  6538. }
  6539. if (context.delta._t) {
  6540. return;
  6541. }
  6542. var name, child;
  6543. for (name in context.delta) {
  6544. child = new PatchContext(context.left[name], context.delta[name]);
  6545. context.push(child, name);
  6546. }
  6547. context.exit();
  6548. };
  6549. patchFilter.filterName = 'objects';
  6550. var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
  6551. if (!context || !context.children) {
  6552. return;
  6553. }
  6554. if (context.delta._t) {
  6555. return;
  6556. }
  6557. var length = context.children.length;
  6558. var child;
  6559. for (var index = 0; index < length; index++) {
  6560. child = context.children[index];
  6561. if (Object.prototype.hasOwnProperty.call(context.left, child.childName) && child.result === undefined) {
  6562. delete context.left[child.childName];
  6563. } else if (context.left[child.childName] !== child.result) {
  6564. context.left[child.childName] = child.result;
  6565. }
  6566. }
  6567. context.setResult(context.left).exit();
  6568. };
  6569. collectChildrenPatchFilter.filterName = 'collectChildren';
  6570. var reverseFilter = function nestedReverseFilter(context) {
  6571. if (!context.nested) {
  6572. return;
  6573. }
  6574. if (context.delta._t) {
  6575. return;
  6576. }
  6577. var name, child;
  6578. for (name in context.delta) {
  6579. child = new ReverseContext(context.delta[name]);
  6580. context.push(child, name);
  6581. }
  6582. context.exit();
  6583. };
  6584. reverseFilter.filterName = 'objects';
  6585. var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) {
  6586. if (!context || !context.children) {
  6587. return;
  6588. }
  6589. if (context.delta._t) {
  6590. return;
  6591. }
  6592. var length = context.children.length;
  6593. var child;
  6594. var delta = {};
  6595. for (var index = 0; index < length; index++) {
  6596. child = context.children[index];
  6597. if (delta[child.childName] !== child.result) {
  6598. delta[child.childName] = child.result;
  6599. }
  6600. }
  6601. context.setResult(delta).exit();
  6602. };
  6603. collectChildrenReverseFilter.filterName = 'collectChildren';
  6604. exports.collectChildrenDiffFilter = collectChildrenDiffFilter;
  6605. exports.objectsDiffFilter = objectsDiffFilter;
  6606. exports.patchFilter = patchFilter;
  6607. exports.collectChildrenPatchFilter = collectChildrenPatchFilter;
  6608. exports.reverseFilter = reverseFilter;
  6609. exports.collectChildrenReverseFilter = collectChildrenReverseFilter;
  6610. },{"../contexts/diff":7,"../contexts/patch":8,"../contexts/reverse":9}],17:[function(require,module,exports){
  6611. /* global diff_match_patch */
  6612. var TEXT_DIFF = 2;
  6613. var DEFAULT_MIN_LENGTH = 60;
  6614. var cachedDiffPatch = null;
  6615. var getDiffMatchPatch = function(required) {
  6616. /*jshint camelcase: false */
  6617. if (!cachedDiffPatch) {
  6618. var instance;
  6619. if (typeof diff_match_patch !== 'undefined') {
  6620. // already loaded, probably a browser
  6621. instance = typeof diff_match_patch === 'function' ?
  6622. new diff_match_patch() : new diff_match_patch.diff_match_patch();
  6623. } else if (typeof require === 'function') {
  6624. try {
  6625. var dmpModuleName = 'diff_match_patch_uncompressed';
  6626. var dmp = require('../../public/external/' + dmpModuleName);
  6627. instance = new dmp.diff_match_patch();
  6628. } catch (err) {
  6629. instance = null;
  6630. }
  6631. }
  6632. if (!instance) {
  6633. if (!required) {
  6634. return null;
  6635. }
  6636. var error = new Error('text diff_match_patch library not found');
  6637. error.diff_match_patch_not_found = true;
  6638. throw error;
  6639. }
  6640. cachedDiffPatch = {
  6641. diff: function(txt1, txt2) {
  6642. return instance.patch_toText(instance.patch_make(txt1, txt2));
  6643. },
  6644. patch: function(txt1, patch) {
  6645. var results = instance.patch_apply(instance.patch_fromText(patch), txt1);
  6646. for (var i = 0; i < results[1].length; i++) {
  6647. if (!results[1][i]) {
  6648. var error = new Error('text patch failed');
  6649. error.textPatchFailed = true;
  6650. }
  6651. }
  6652. return results[0];
  6653. }
  6654. };
  6655. }
  6656. return cachedDiffPatch;
  6657. };
  6658. var diffFilter = function textsDiffFilter(context) {
  6659. if (context.leftType !== 'string') {
  6660. return;
  6661. }
  6662. var minLength = (context.options && context.options.textDiff &&
  6663. context.options.textDiff.minLength) || DEFAULT_MIN_LENGTH;
  6664. if (context.left.length < minLength ||
  6665. context.right.length < minLength) {
  6666. context.setResult([context.left, context.right]).exit();
  6667. return;
  6668. }
  6669. // large text, try to use a text-diff algorithm
  6670. var diffMatchPatch = getDiffMatchPatch();
  6671. if (!diffMatchPatch) {
  6672. // diff-match-patch library not available, fallback to regular string replace
  6673. context.setResult([context.left, context.right]).exit();
  6674. return;
  6675. }
  6676. var diff = diffMatchPatch.diff;
  6677. context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit();
  6678. };
  6679. diffFilter.filterName = 'texts';
  6680. var patchFilter = function textsPatchFilter(context) {
  6681. if (context.nested) {
  6682. return;
  6683. }
  6684. if (context.delta[2] !== TEXT_DIFF) {
  6685. return;
  6686. }
  6687. // text-diff, use a text-patch algorithm
  6688. var patch = getDiffMatchPatch(true).patch;
  6689. context.setResult(patch(context.left, context.delta[0])).exit();
  6690. };
  6691. patchFilter.filterName = 'texts';
  6692. var textDeltaReverse = function(delta) {
  6693. var i, l, lines, line, lineTmp, header = null,
  6694. headerRegex = /^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/,
  6695. lineHeader, lineAdd, lineRemove;
  6696. lines = delta.split('\n');
  6697. for (i = 0, l = lines.length; i < l; i++) {
  6698. line = lines[i];
  6699. var lineStart = line.slice(0, 1);
  6700. if (lineStart === '@') {
  6701. header = headerRegex.exec(line);
  6702. lineHeader = i;
  6703. lineAdd = null;
  6704. lineRemove = null;
  6705. // fix header
  6706. lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@';
  6707. } else if (lineStart === '+') {
  6708. lineAdd = i;
  6709. lines[i] = '-' + lines[i].slice(1);
  6710. if (lines[i - 1].slice(0, 1) === '+') {
  6711. // swap lines to keep default order (-+)
  6712. lineTmp = lines[i];
  6713. lines[i] = lines[i - 1];
  6714. lines[i - 1] = lineTmp;
  6715. }
  6716. } else if (lineStart === '-') {
  6717. lineRemove = i;
  6718. lines[i] = '+' + lines[i].slice(1);
  6719. }
  6720. }
  6721. return lines.join('\n');
  6722. };
  6723. var reverseFilter = function textsReverseFilter(context) {
  6724. if (context.nested) {
  6725. return;
  6726. }
  6727. if (context.delta[2] !== TEXT_DIFF) {
  6728. return;
  6729. }
  6730. // text-diff, use a text-diff algorithm
  6731. context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit();
  6732. };
  6733. reverseFilter.filterName = 'texts';
  6734. exports.diffFilter = diffFilter;
  6735. exports.patchFilter = patchFilter;
  6736. exports.reverseFilter = reverseFilter;
  6737. },{}],18:[function(require,module,exports){
  6738. var isArray = (typeof Array.isArray === 'function') ?
  6739. // use native function
  6740. Array.isArray :
  6741. // use instanceof operator
  6742. function(a) {
  6743. return a instanceof Array;
  6744. };
  6745. var diffFilter = function trivialMatchesDiffFilter(context) {
  6746. if (context.left === context.right) {
  6747. context.setResult(undefined).exit();
  6748. return;
  6749. }
  6750. if (typeof context.left === 'undefined') {
  6751. if (typeof context.right === 'function') {
  6752. throw new Error('functions are not supported');
  6753. }
  6754. context.setResult([context.right]).exit();
  6755. return;
  6756. }
  6757. if (typeof context.right === 'undefined') {
  6758. context.setResult([context.left, 0, 0]).exit();
  6759. return;
  6760. }
  6761. if (typeof context.left === 'function' || typeof context.right === 'function') {
  6762. throw new Error('functions are not supported');
  6763. }
  6764. context.leftType = context.left === null ? 'null' : typeof context.left;
  6765. context.rightType = context.right === null ? 'null' : typeof context.right;
  6766. if (context.leftType !== context.rightType) {
  6767. context.setResult([context.left, context.right]).exit();
  6768. return;
  6769. }
  6770. if (context.leftType === 'boolean' || context.leftType === 'number') {
  6771. context.setResult([context.left, context.right]).exit();
  6772. return;
  6773. }
  6774. if (context.leftType === 'object') {
  6775. context.leftIsArray = isArray(context.left);
  6776. }
  6777. if (context.rightType === 'object') {
  6778. context.rightIsArray = isArray(context.right);
  6779. }
  6780. if (context.leftIsArray !== context.rightIsArray) {
  6781. context.setResult([context.left, context.right]).exit();
  6782. return;
  6783. }
  6784. };
  6785. diffFilter.filterName = 'trivial';
  6786. var patchFilter = function trivialMatchesPatchFilter(context) {
  6787. if (typeof context.delta === 'undefined') {
  6788. context.setResult(context.left).exit();
  6789. return;
  6790. }
  6791. context.nested = !isArray(context.delta);
  6792. if (context.nested) {
  6793. return;
  6794. }
  6795. if (context.delta.length === 1) {
  6796. context.setResult(context.delta[0]).exit();
  6797. return;
  6798. }
  6799. if (context.delta.length === 2) {
  6800. context.setResult(context.delta[1]).exit();
  6801. return;
  6802. }
  6803. if (context.delta.length === 3 && context.delta[2] === 0) {
  6804. context.setResult(undefined).exit();
  6805. return;
  6806. }
  6807. };
  6808. patchFilter.filterName = 'trivial';
  6809. var reverseFilter = function trivialReferseFilter(context) {
  6810. if (typeof context.delta === 'undefined') {
  6811. context.setResult(context.delta).exit();
  6812. return;
  6813. }
  6814. context.nested = !isArray(context.delta);
  6815. if (context.nested) {
  6816. return;
  6817. }
  6818. if (context.delta.length === 1) {
  6819. context.setResult([context.delta[0], 0, 0]).exit();
  6820. return;
  6821. }
  6822. if (context.delta.length === 2) {
  6823. context.setResult([context.delta[1], context.delta[0]]).exit();
  6824. return;
  6825. }
  6826. if (context.delta.length === 3 && context.delta[2] === 0) {
  6827. context.setResult([context.delta[0]]).exit();
  6828. return;
  6829. }
  6830. };
  6831. reverseFilter.filterName = 'trivial';
  6832. exports.diffFilter = diffFilter;
  6833. exports.patchFilter = patchFilter;
  6834. exports.reverseFilter = reverseFilter;
  6835. },{}],19:[function(require,module,exports){
  6836. var environment = require('./environment');
  6837. var DiffPatcher = require('./diffpatcher').DiffPatcher;
  6838. exports.DiffPatcher = DiffPatcher;
  6839. exports.create = function(options){
  6840. return new DiffPatcher(options);
  6841. };
  6842. exports.dateReviver = require('./date-reviver');
  6843. var defaultInstance;
  6844. exports.diff = function() {
  6845. if (!defaultInstance) {
  6846. defaultInstance = new DiffPatcher();
  6847. }
  6848. return defaultInstance.diff.apply(defaultInstance, arguments);
  6849. };
  6850. exports.patch = function() {
  6851. if (!defaultInstance) {
  6852. defaultInstance = new DiffPatcher();
  6853. }
  6854. return defaultInstance.patch.apply(defaultInstance, arguments);
  6855. };
  6856. exports.unpatch = function() {
  6857. if (!defaultInstance) {
  6858. defaultInstance = new DiffPatcher();
  6859. }
  6860. return defaultInstance.unpatch.apply(defaultInstance, arguments);
  6861. };
  6862. exports.reverse = function() {
  6863. if (!defaultInstance) {
  6864. defaultInstance = new DiffPatcher();
  6865. }
  6866. return defaultInstance.reverse.apply(defaultInstance, arguments);
  6867. };
  6868. if (environment.isBrowser) {
  6869. exports.homepage = '{{package-homepage}}';
  6870. exports.version = '{{package-version}}';
  6871. } else {
  6872. var packageInfoModuleName = '../package.json';
  6873. var packageInfo = require(packageInfoModuleName);
  6874. exports.homepage = packageInfo.homepage;
  6875. exports.version = packageInfo.version;
  6876. var formatterModuleName = './formatters';
  6877. var formatters = require(formatterModuleName);
  6878. exports.formatters = formatters;
  6879. // shortcut for console
  6880. exports.console = formatters.console;
  6881. }
  6882. },{"./date-reviver":10,"./diffpatcher":11,"./environment":12}],20:[function(require,module,exports){
  6883. var Pipe = function Pipe(name) {
  6884. this.name = name;
  6885. this.filters = [];
  6886. };
  6887. Pipe.prototype.process = function(input) {
  6888. if (!this.processor) {
  6889. throw new Error('add this pipe to a processor before using it');
  6890. }
  6891. var debug = this.debug;
  6892. var length = this.filters.length;
  6893. var context = input;
  6894. for (var index = 0; index < length; index++) {
  6895. var filter = this.filters[index];
  6896. if (debug) {
  6897. this.log('filter: ' + filter.filterName);
  6898. }
  6899. filter(context);
  6900. if (typeof context === 'object' && context.exiting) {
  6901. context.exiting = false;
  6902. break;
  6903. }
  6904. }
  6905. if (!context.next && this.resultCheck) {
  6906. this.resultCheck(context);
  6907. }
  6908. };
  6909. Pipe.prototype.log = function(msg) {
  6910. console.log('[jsondiffpatch] ' + this.name + ' pipe, ' + msg);
  6911. };
  6912. Pipe.prototype.append = function() {
  6913. this.filters.push.apply(this.filters, arguments);
  6914. return this;
  6915. };
  6916. Pipe.prototype.prepend = function() {
  6917. this.filters.unshift.apply(this.filters, arguments);
  6918. return this;
  6919. };
  6920. Pipe.prototype.indexOf = function(filterName) {
  6921. if (!filterName) {
  6922. throw new Error('a filter name is required');
  6923. }
  6924. for (var index = 0; index < this.filters.length; index++) {
  6925. var filter = this.filters[index];
  6926. if (filter.filterName === filterName) {
  6927. return index;
  6928. }
  6929. }
  6930. throw new Error('filter not found: ' + filterName);
  6931. };
  6932. Pipe.prototype.list = function() {
  6933. var names = [];
  6934. for (var index = 0; index < this.filters.length; index++) {
  6935. var filter = this.filters[index];
  6936. names.push(filter.filterName);
  6937. }
  6938. return names;
  6939. };
  6940. Pipe.prototype.after = function(filterName) {
  6941. var index = this.indexOf(filterName);
  6942. var params = Array.prototype.slice.call(arguments, 1);
  6943. if (!params.length) {
  6944. throw new Error('a filter is required');
  6945. }
  6946. params.unshift(index + 1, 0);
  6947. Array.prototype.splice.apply(this.filters, params);
  6948. return this;
  6949. };
  6950. Pipe.prototype.before = function(filterName) {
  6951. var index = this.indexOf(filterName);
  6952. var params = Array.prototype.slice.call(arguments, 1);
  6953. if (!params.length) {
  6954. throw new Error('a filter is required');
  6955. }
  6956. params.unshift(index, 0);
  6957. Array.prototype.splice.apply(this.filters, params);
  6958. return this;
  6959. };
  6960. Pipe.prototype.clear = function() {
  6961. this.filters.length = 0;
  6962. return this;
  6963. };
  6964. Pipe.prototype.shouldHaveResult = function(should) {
  6965. if (should === false) {
  6966. this.resultCheck = null;
  6967. return;
  6968. }
  6969. if (this.resultCheck) {
  6970. return;
  6971. }
  6972. var pipe = this;
  6973. this.resultCheck = function(context) {
  6974. if (!context.hasResult) {
  6975. console.log(context);
  6976. var error = new Error(pipe.name + ' failed');
  6977. error.noResult = true;
  6978. throw error;
  6979. }
  6980. };
  6981. return this;
  6982. };
  6983. exports.Pipe = Pipe;
  6984. },{}],21:[function(require,module,exports){
  6985. var Processor = function Processor(options){
  6986. this.selfOptions = options || {};
  6987. this.pipes = {};
  6988. };
  6989. Processor.prototype.options = function(options) {
  6990. if (options) {
  6991. this.selfOptions = options;
  6992. }
  6993. return this.selfOptions;
  6994. };
  6995. Processor.prototype.pipe = function(name, pipe) {
  6996. if (typeof name === 'string') {
  6997. if (typeof pipe === 'undefined') {
  6998. return this.pipes[name];
  6999. } else {
  7000. this.pipes[name] = pipe;
  7001. }
  7002. }
  7003. if (name && name.name) {
  7004. pipe = name;
  7005. if (pipe.processor === this) { return pipe; }
  7006. this.pipes[pipe.name] = pipe;
  7007. }
  7008. pipe.processor = this;
  7009. return pipe;
  7010. };
  7011. Processor.prototype.process = function(input, pipe) {
  7012. var context = input;
  7013. context.options = this.options();
  7014. var nextPipe = pipe || input.pipe || 'default';
  7015. var lastPipe, lastContext;
  7016. while (nextPipe) {
  7017. if (typeof context.nextAfterChildren !== 'undefined') {
  7018. // children processed and coming back to parent
  7019. context.next = context.nextAfterChildren;
  7020. context.nextAfterChildren = null;
  7021. }
  7022. if (typeof nextPipe === 'string') {
  7023. nextPipe = this.pipe(nextPipe);
  7024. }
  7025. nextPipe.process(context);
  7026. lastContext = context;
  7027. lastPipe = nextPipe;
  7028. nextPipe = null;
  7029. if (context) {
  7030. if (context.next) {
  7031. context = context.next;
  7032. nextPipe = lastContext.nextPipe || context.pipe || lastPipe;
  7033. }
  7034. }
  7035. }
  7036. return context.hasResult ? context.result : undefined;
  7037. };
  7038. exports.Processor = Processor;
  7039. },{}],22:[function(require,module,exports){
  7040. exports.RateLimiter = require('./lib/rateLimiter');
  7041. exports.TokenBucket = require('./lib/tokenBucket');
  7042. },{"./lib/rateLimiter":24,"./lib/tokenBucket":25}],23:[function(require,module,exports){
  7043. (function (process){
  7044. var getMilliseconds = function() {
  7045. if (typeof process !== 'undefined' && process.hrtime) {
  7046. var hrtime = process.hrtime();
  7047. var seconds = hrtime[0];
  7048. var nanoseconds = hrtime[1];
  7049. return seconds * 1e3 + Math.floor(nanoseconds / 1e6);
  7050. }
  7051. return new Date().getTime();
  7052. }
  7053. module.exports = getMilliseconds;
  7054. }).call(this,require('_process'))
  7055. },{"_process":26}],24:[function(require,module,exports){
  7056. (function (process){
  7057. var TokenBucket = require('./tokenBucket');
  7058. var getMilliseconds = require('./clock');
  7059. /**
  7060. * A generic rate limiter. Underneath the hood, this uses a token bucket plus
  7061. * an additional check to limit how many tokens we can remove each interval.
  7062. * @author John Hurliman <jhurliman@jhurliman.org>
  7063. *
  7064. * @param {Number} tokensPerInterval Maximum number of tokens that can be
  7065. * removed at any given moment and over the course of one interval.
  7066. * @param {String|Number} interval The interval length in milliseconds, or as
  7067. * one of the following strings: 'second', 'minute', 'hour', day'.
  7068. * @param {Boolean} fireImmediately Optional. Whether or not the callback
  7069. * will fire immediately when rate limiting is in effect (default is false).
  7070. */
  7071. var RateLimiter = function(tokensPerInterval, interval, fireImmediately) {
  7072. this.tokenBucket = new TokenBucket(tokensPerInterval, tokensPerInterval,
  7073. interval, null);
  7074. // Fill the token bucket to start
  7075. this.tokenBucket.content = tokensPerInterval;
  7076. this.curIntervalStart = getMilliseconds();
  7077. this.tokensThisInterval = 0;
  7078. this.fireImmediately = fireImmediately;
  7079. };
  7080. RateLimiter.prototype = {
  7081. tokenBucket: null,
  7082. curIntervalStart: 0,
  7083. tokensThisInterval: 0,
  7084. fireImmediately: false,
  7085. /**
  7086. * Remove the requested number of tokens and fire the given callback. If the
  7087. * rate limiter contains enough tokens and we haven't spent too many tokens
  7088. * in this interval already, this will happen immediately. Otherwise, the
  7089. * removal and callback will happen when enough tokens become available.
  7090. * @param {Number} count The number of tokens to remove.
  7091. * @param {Function} callback(err, remainingTokens)
  7092. * @returns {Boolean} True if the callback was fired immediately, otherwise
  7093. * false.
  7094. */
  7095. removeTokens: function(count, callback) {
  7096. // Make sure the request isn't for more than we can handle
  7097. if (count > this.tokenBucket.bucketSize) {
  7098. process.nextTick(callback.bind(null, 'Requested tokens ' + count +
  7099. ' exceeds maximum tokens per interval ' + this.tokenBucket.bucketSize,
  7100. null));
  7101. return false;
  7102. }
  7103. var self = this;
  7104. var now = getMilliseconds();
  7105. // Advance the current interval and reset the current interval token count
  7106. // if needed
  7107. if (now < this.curIntervalStart
  7108. || now - this.curIntervalStart >= this.tokenBucket.interval) {
  7109. this.curIntervalStart = now;
  7110. this.tokensThisInterval = 0;
  7111. }
  7112. // If we don't have enough tokens left in this interval, wait until the
  7113. // next interval
  7114. if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {
  7115. if (this.fireImmediately) {
  7116. process.nextTick(callback.bind(null, null, -1));
  7117. } else {
  7118. var waitInterval = Math.ceil(
  7119. this.curIntervalStart + this.tokenBucket.interval - now);
  7120. setTimeout(function() {
  7121. self.tokenBucket.removeTokens(count, afterTokensRemoved);
  7122. }, waitInterval);
  7123. }
  7124. return false;
  7125. }
  7126. // Remove the requested number of tokens from the token bucket
  7127. return this.tokenBucket.removeTokens(count, afterTokensRemoved);
  7128. function afterTokensRemoved(err, tokensRemaining) {
  7129. if (err) return callback(err, null);
  7130. self.tokensThisInterval += count;
  7131. callback(null, tokensRemaining);
  7132. }
  7133. },
  7134. /**
  7135. * Attempt to remove the requested number of tokens and return immediately.
  7136. * If the bucket (and any parent buckets) contains enough tokens and we
  7137. * haven't spent too many tokens in this interval already, this will return
  7138. * true. Otherwise, false is returned.
  7139. * @param {Number} count The number of tokens to remove.
  7140. * @param {Boolean} True if the tokens were successfully removed, otherwise
  7141. * false.
  7142. */
  7143. tryRemoveTokens: function(count) {
  7144. // Make sure the request isn't for more than we can handle
  7145. if (count > this.tokenBucket.bucketSize)
  7146. return false;
  7147. var now = getMilliseconds();
  7148. // Advance the current interval and reset the current interval token count
  7149. // if needed
  7150. if (now < this.curIntervalStart
  7151. || now - this.curIntervalStart >= this.tokenBucket.interval) {
  7152. this.curIntervalStart = now;
  7153. this.tokensThisInterval = 0;
  7154. }
  7155. // If we don't have enough tokens left in this interval, return false
  7156. if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval)
  7157. return false;
  7158. // Try to remove the requested number of tokens from the token bucket
  7159. var removed = this.tokenBucket.tryRemoveTokens(count);
  7160. if (removed) {
  7161. this.tokensThisInterval += count;
  7162. }
  7163. return removed;
  7164. },
  7165. /**
  7166. * Returns the number of tokens remaining in the TokenBucket.
  7167. * @returns {Number} The number of tokens remaining.
  7168. */
  7169. getTokensRemaining: function () {
  7170. this.tokenBucket.drip();
  7171. return this.tokenBucket.content;
  7172. }
  7173. };
  7174. module.exports = RateLimiter;
  7175. }).call(this,require('_process'))
  7176. },{"./clock":23,"./tokenBucket":25,"_process":26}],25:[function(require,module,exports){
  7177. (function (process){
  7178. /**
  7179. * A hierarchical token bucket for rate limiting. See
  7180. * http://en.wikipedia.org/wiki/Token_bucket for more information.
  7181. * @author John Hurliman <jhurliman@cull.tv>
  7182. *
  7183. * @param {Number} bucketSize Maximum number of tokens to hold in the bucket.
  7184. * Also known as the burst rate.
  7185. * @param {Number} tokensPerInterval Number of tokens to drip into the bucket
  7186. * over the course of one interval.
  7187. * @param {String|Number} interval The interval length in milliseconds, or as
  7188. * one of the following strings: 'second', 'minute', 'hour', day'.
  7189. * @param {TokenBucket} parentBucket Optional. A token bucket that will act as
  7190. * the parent of this bucket.
  7191. */
  7192. var TokenBucket = function(bucketSize, tokensPerInterval, interval, parentBucket) {
  7193. this.bucketSize = bucketSize;
  7194. this.tokensPerInterval = tokensPerInterval;
  7195. if (typeof interval === 'string') {
  7196. switch (interval) {
  7197. case 'sec': case 'second':
  7198. this.interval = 1000; break;
  7199. case 'min': case 'minute':
  7200. this.interval = 1000 * 60; break;
  7201. case 'hr': case 'hour':
  7202. this.interval = 1000 * 60 * 60; break;
  7203. case 'day':
  7204. this.interval = 1000 * 60 * 60 * 24; break;
  7205. default:
  7206. throw new Error('Invaid interval ' + interval);
  7207. }
  7208. } else {
  7209. this.interval = interval;
  7210. }
  7211. this.parentBucket = parentBucket;
  7212. this.content = 0;
  7213. this.lastDrip = +new Date();
  7214. };
  7215. TokenBucket.prototype = {
  7216. bucketSize: 1,
  7217. tokensPerInterval: 1,
  7218. interval: 1000,
  7219. parentBucket: null,
  7220. content: 0,
  7221. lastDrip: 0,
  7222. /**
  7223. * Remove the requested number of tokens and fire the given callback. If the
  7224. * bucket (and any parent buckets) contains enough tokens this will happen
  7225. * immediately. Otherwise, the removal and callback will happen when enough
  7226. * tokens become available.
  7227. * @param {Number} count The number of tokens to remove.
  7228. * @param {Function} callback(err, remainingTokens)
  7229. * @returns {Boolean} True if the callback was fired immediately, otherwise
  7230. * false.
  7231. */
  7232. removeTokens: function(count, callback) {
  7233. var self = this;
  7234. // Is this an infinite size bucket?
  7235. if (!this.bucketSize) {
  7236. process.nextTick(callback.bind(null, null, count, Number.POSITIVE_INFINITY));
  7237. return true;
  7238. }
  7239. // Make sure the bucket can hold the requested number of tokens
  7240. if (count > this.bucketSize) {
  7241. process.nextTick(callback.bind(null, 'Requested tokens ' + count + ' exceeds bucket size ' +
  7242. this.bucketSize, null));
  7243. return false;
  7244. }
  7245. // Drip new tokens into this bucket
  7246. this.drip();
  7247. // If we don't have enough tokens in this bucket, come back later
  7248. if (count > this.content)
  7249. return comeBackLater();
  7250. if (this.parentBucket) {
  7251. // Remove the requested from the parent bucket first
  7252. return this.parentBucket.removeTokens(count, function(err, remainingTokens) {
  7253. if (err) return callback(err, null);
  7254. // Check that we still have enough tokens in this bucket
  7255. if (count > self.content)
  7256. return comeBackLater();
  7257. // Tokens were removed from the parent bucket, now remove them from
  7258. // this bucket and fire the callback. Note that we look at the current
  7259. // bucket and parent bucket's remaining tokens and return the smaller
  7260. // of the two values
  7261. self.content -= count;
  7262. callback(null, Math.min(remainingTokens, self.content));
  7263. });
  7264. } else {
  7265. // Remove the requested tokens from this bucket and fire the callback
  7266. this.content -= count;
  7267. process.nextTick(callback.bind(null, null, this.content));
  7268. return true;
  7269. }
  7270. function comeBackLater() {
  7271. // How long do we need to wait to make up the difference in tokens?
  7272. var waitInterval = Math.ceil(
  7273. (count - self.content) * (self.interval / self.tokensPerInterval));
  7274. setTimeout(function() { self.removeTokens(count, callback); }, waitInterval);
  7275. return false;
  7276. }
  7277. },
  7278. /**
  7279. * Attempt to remove the requested number of tokens and return immediately.
  7280. * If the bucket (and any parent buckets) contains enough tokens this will
  7281. * return true, otherwise false is returned.
  7282. * @param {Number} count The number of tokens to remove.
  7283. * @param {Boolean} True if the tokens were successfully removed, otherwise
  7284. * false.
  7285. */
  7286. tryRemoveTokens: function(count) {
  7287. // Is this an infinite size bucket?
  7288. if (!this.bucketSize)
  7289. return true;
  7290. // Make sure the bucket can hold the requested number of tokens
  7291. if (count > this.bucketSize)
  7292. return false;
  7293. // Drip new tokens into this bucket
  7294. this.drip();
  7295. // If we don't have enough tokens in this bucket, return false
  7296. if (count > this.content)
  7297. return false;
  7298. // Try to remove the requested tokens from the parent bucket
  7299. if (this.parentBucket && !this.parent.tryRemoveTokens(count))
  7300. return false;
  7301. // Remove the requested tokens from this bucket and return
  7302. this.content -= count;
  7303. return true;
  7304. },
  7305. /**
  7306. * Add any new tokens to the bucket since the last drip.
  7307. * @returns {Boolean} True if new tokens were added, otherwise false.
  7308. */
  7309. drip: function() {
  7310. if (!this.tokensPerInterval) {
  7311. this.content = this.bucketSize;
  7312. return;
  7313. }
  7314. var now = +new Date();
  7315. var deltaMS = Math.max(now - this.lastDrip, 0);
  7316. this.lastDrip = now;
  7317. var dripAmount = deltaMS * (this.tokensPerInterval / this.interval);
  7318. this.content = Math.min(this.content + dripAmount, this.bucketSize);
  7319. }
  7320. };
  7321. module.exports = TokenBucket;
  7322. }).call(this,require('_process'))
  7323. },{"_process":26}],26:[function(require,module,exports){
  7324. // shim for using process in browser
  7325. var process = module.exports = {};
  7326. // cached from whatever global is present so that test runners that stub it
  7327. // don't break things. But we need to wrap it in a try catch in case it is
  7328. // wrapped in strict mode code which doesn't define any globals. It's inside a
  7329. // function because try/catches deoptimize in certain engines.
  7330. var cachedSetTimeout;
  7331. var cachedClearTimeout;
  7332. function defaultSetTimout() {
  7333. throw new Error('setTimeout has not been defined');
  7334. }
  7335. function defaultClearTimeout () {
  7336. throw new Error('clearTimeout has not been defined');
  7337. }
  7338. (function () {
  7339. try {
  7340. if (typeof setTimeout === 'function') {
  7341. cachedSetTimeout = setTimeout;
  7342. } else {
  7343. cachedSetTimeout = defaultSetTimout;
  7344. }
  7345. } catch (e) {
  7346. cachedSetTimeout = defaultSetTimout;
  7347. }
  7348. try {
  7349. if (typeof clearTimeout === 'function') {
  7350. cachedClearTimeout = clearTimeout;
  7351. } else {
  7352. cachedClearTimeout = defaultClearTimeout;
  7353. }
  7354. } catch (e) {
  7355. cachedClearTimeout = defaultClearTimeout;
  7356. }
  7357. } ())
  7358. function runTimeout(fun) {
  7359. if (cachedSetTimeout === setTimeout) {
  7360. //normal enviroments in sane situations
  7361. return setTimeout(fun, 0);
  7362. }
  7363. // if setTimeout wasn't available but was latter defined
  7364. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  7365. cachedSetTimeout = setTimeout;
  7366. return setTimeout(fun, 0);
  7367. }
  7368. try {
  7369. // when when somebody has screwed with setTimeout but no I.E. maddness
  7370. return cachedSetTimeout(fun, 0);
  7371. } catch(e){
  7372. try {
  7373. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7374. return cachedSetTimeout.call(null, fun, 0);
  7375. } catch(e){
  7376. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  7377. return cachedSetTimeout.call(this, fun, 0);
  7378. }
  7379. }
  7380. }
  7381. function runClearTimeout(marker) {
  7382. if (cachedClearTimeout === clearTimeout) {
  7383. //normal enviroments in sane situations
  7384. return clearTimeout(marker);
  7385. }
  7386. // if clearTimeout wasn't available but was latter defined
  7387. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  7388. cachedClearTimeout = clearTimeout;
  7389. return clearTimeout(marker);
  7390. }
  7391. try {
  7392. // when when somebody has screwed with setTimeout but no I.E. maddness
  7393. return cachedClearTimeout(marker);
  7394. } catch (e){
  7395. try {
  7396. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7397. return cachedClearTimeout.call(null, marker);
  7398. } catch (e){
  7399. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  7400. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  7401. return cachedClearTimeout.call(this, marker);
  7402. }
  7403. }
  7404. }
  7405. var queue = [];
  7406. var draining = false;
  7407. var currentQueue;
  7408. var queueIndex = -1;
  7409. function cleanUpNextTick() {
  7410. if (!draining || !currentQueue) {
  7411. return;
  7412. }
  7413. draining = false;
  7414. if (currentQueue.length) {
  7415. queue = currentQueue.concat(queue);
  7416. } else {
  7417. queueIndex = -1;
  7418. }
  7419. if (queue.length) {
  7420. drainQueue();
  7421. }
  7422. }
  7423. function drainQueue() {
  7424. if (draining) {
  7425. return;
  7426. }
  7427. var timeout = runTimeout(cleanUpNextTick);
  7428. draining = true;
  7429. var len = queue.length;
  7430. while(len) {
  7431. currentQueue = queue;
  7432. queue = [];
  7433. while (++queueIndex < len) {
  7434. if (currentQueue) {
  7435. currentQueue[queueIndex].run();
  7436. }
  7437. }
  7438. queueIndex = -1;
  7439. len = queue.length;
  7440. }
  7441. currentQueue = null;
  7442. draining = false;
  7443. runClearTimeout(timeout);
  7444. }
  7445. process.nextTick = function (fun) {
  7446. var args = new Array(arguments.length - 1);
  7447. if (arguments.length > 1) {
  7448. for (var i = 1; i < arguments.length; i++) {
  7449. args[i - 1] = arguments[i];
  7450. }
  7451. }
  7452. queue.push(new Item(fun, args));
  7453. if (queue.length === 1 && !draining) {
  7454. runTimeout(drainQueue);
  7455. }
  7456. };
  7457. // v8 likes predictible objects
  7458. function Item(fun, array) {
  7459. this.fun = fun;
  7460. this.array = array;
  7461. }
  7462. Item.prototype.run = function () {
  7463. this.fun.apply(null, this.array);
  7464. };
  7465. process.title = 'browser';
  7466. process.browser = true;
  7467. process.env = {};
  7468. process.argv = [];
  7469. process.version = ''; // empty string to avoid regexp issues
  7470. process.versions = {};
  7471. function noop() {}
  7472. process.on = noop;
  7473. process.addListener = noop;
  7474. process.once = noop;
  7475. process.off = noop;
  7476. process.removeListener = noop;
  7477. process.removeAllListeners = noop;
  7478. process.emit = noop;
  7479. process.prependListener = noop;
  7480. process.prependOnceListener = noop;
  7481. process.listeners = function (name) { return [] }
  7482. process.binding = function (name) {
  7483. throw new Error('process.binding is not supported');
  7484. };
  7485. process.cwd = function () { return '/' };
  7486. process.chdir = function (dir) {
  7487. throw new Error('process.chdir is not supported');
  7488. };
  7489. process.umask = function() { return 0; };
  7490. },{}],27:[function(require,module,exports){
  7491. module.exports = OmegaPac;
  7492. },{}],28:[function(require,module,exports){
  7493. var BrowserStorage, Promise, Storage,
  7494. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  7495. hasProp = {}.hasOwnProperty;
  7496. Storage = require('./storage');
  7497. Promise = require('bluebird');
  7498. BrowserStorage = (function(superClass) {
  7499. extend(BrowserStorage, superClass);
  7500. function BrowserStorage(storage, prefix) {
  7501. this.storage = storage;
  7502. this.prefix = prefix != null ? prefix : '';
  7503. this.proto = Object.getPrototypeOf(this.storage);
  7504. }
  7505. BrowserStorage.prototype.get = function(keys) {
  7506. var i, key, len, map, value;
  7507. map = {};
  7508. if (typeof keys === 'string') {
  7509. map[keys] = void 0;
  7510. } else if (Array.isArray(keys)) {
  7511. for (i = 0, len = keys.length; i < len; i++) {
  7512. key = keys[i];
  7513. map[key] = void 0;
  7514. }
  7515. } else if (typeof keys === 'object') {
  7516. map = keys;
  7517. }
  7518. for (key in map) {
  7519. if (!hasProp.call(map, key)) continue;
  7520. try {
  7521. value = JSON.parse(this.proto.getItem.call(this.storage, this.prefix + key));
  7522. } catch (error) {}
  7523. if (value != null) {
  7524. map[key] = value;
  7525. }
  7526. if (typeof map[key] === 'undefined') {
  7527. delete map[key];
  7528. }
  7529. }
  7530. return Promise.resolve(map);
  7531. };
  7532. BrowserStorage.prototype.set = function(items) {
  7533. var key, value;
  7534. for (key in items) {
  7535. if (!hasProp.call(items, key)) continue;
  7536. value = items[key];
  7537. value = JSON.stringify(value);
  7538. this.proto.setItem.call(this.storage, this.prefix + key, value);
  7539. }
  7540. return Promise.resolve(items);
  7541. };
  7542. BrowserStorage.prototype.remove = function(keys) {
  7543. var i, index, key, len;
  7544. if (keys == null) {
  7545. if (!this.prefix) {
  7546. this.proto.clear.call(this.storage);
  7547. } else {
  7548. index = 0;
  7549. while (true) {
  7550. key = this.proto.key.call(index);
  7551. if (key === null) {
  7552. break;
  7553. }
  7554. if (this.key.substr(0, this.prefix.length) === this.prefix) {
  7555. this.proto.removeItem.call(this.storage, this.prefix + keys);
  7556. } else {
  7557. index++;
  7558. }
  7559. }
  7560. }
  7561. }
  7562. if (typeof keys === 'string') {
  7563. this.proto.removeItem.call(this.storage, this.prefix + keys);
  7564. }
  7565. for (i = 0, len = keys.length; i < len; i++) {
  7566. key = keys[i];
  7567. this.proto.removeItem.call(this.storage, this.prefix + key);
  7568. }
  7569. return Promise.resolve();
  7570. };
  7571. return BrowserStorage;
  7572. })(Storage);
  7573. module.exports = BrowserStorage;
  7574. },{"./storage":34,"bluebird":2}],29:[function(require,module,exports){
  7575. module.exports = function() {
  7576. return {
  7577. schemaVersion: 2,
  7578. "-enableQuickSwitch": false,
  7579. "-refreshOnProfileChange": true,
  7580. "-startupProfileName": "",
  7581. "-quickSwitchProfiles": [],
  7582. "-revertProxyChanges": true,
  7583. "-confirmDeletion": true,
  7584. "-showInspectMenu": true,
  7585. "-addConditionsToBottom": false,
  7586. "-showExternalProfile": true,
  7587. "-downloadInterval": 1440,
  7588. "+proxy": {
  7589. bypassList: [
  7590. {
  7591. pattern: "127.0.0.1",
  7592. conditionType: "BypassCondition"
  7593. }, {
  7594. pattern: "::1",
  7595. conditionType: "BypassCondition"
  7596. }, {
  7597. pattern: "localhost",
  7598. conditionType: "BypassCondition"
  7599. }
  7600. ],
  7601. profileType: "FixedProfile",
  7602. name: "proxy",
  7603. color: "#99ccee",
  7604. fallbackProxy: {
  7605. port: 8080,
  7606. scheme: "http",
  7607. host: "proxy.example.com"
  7608. }
  7609. },
  7610. "+auto switch": {
  7611. profileType: "SwitchProfile",
  7612. rules: [
  7613. {
  7614. condition: {
  7615. pattern: "internal.example.com",
  7616. conditionType: "HostWildcardCondition"
  7617. },
  7618. profileName: "direct"
  7619. }, {
  7620. condition: {
  7621. pattern: "*.example.com",
  7622. conditionType: "HostWildcardCondition"
  7623. },
  7624. profileName: "proxy"
  7625. }
  7626. ],
  7627. name: "auto switch",
  7628. color: "#99dd99",
  7629. defaultProfileName: "direct"
  7630. }
  7631. };
  7632. };
  7633. },{}],30:[function(require,module,exports){
  7634. var ContentTypeRejectedError, HttpError, HttpNotFoundError, HttpServerError, NetworkError,
  7635. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  7636. hasProp = {}.hasOwnProperty;
  7637. NetworkError = (function(superClass) {
  7638. extend(NetworkError, superClass);
  7639. function NetworkError(err) {
  7640. NetworkError.__super__.constructor.apply(this, arguments);
  7641. this.cause = err;
  7642. this.name = 'NetworkError';
  7643. }
  7644. return NetworkError;
  7645. })(Error);
  7646. HttpError = (function(superClass) {
  7647. extend(HttpError, superClass);
  7648. function HttpError() {
  7649. var ref;
  7650. HttpError.__super__.constructor.apply(this, arguments);
  7651. this.statusCode = (ref = this.cause) != null ? ref.statusCode : void 0;
  7652. this.name = 'HttpError';
  7653. }
  7654. return HttpError;
  7655. })(NetworkError);
  7656. HttpNotFoundError = (function(superClass) {
  7657. extend(HttpNotFoundError, superClass);
  7658. function HttpNotFoundError() {
  7659. HttpNotFoundError.__super__.constructor.apply(this, arguments);
  7660. this.name = 'HttpNotFoundError';
  7661. }
  7662. return HttpNotFoundError;
  7663. })(HttpError);
  7664. HttpServerError = (function(superClass) {
  7665. extend(HttpServerError, superClass);
  7666. function HttpServerError() {
  7667. HttpServerError.__super__.constructor.apply(this, arguments);
  7668. this.name = 'HttpServerError';
  7669. }
  7670. return HttpServerError;
  7671. })(HttpError);
  7672. ContentTypeRejectedError = (function(superClass) {
  7673. extend(ContentTypeRejectedError, superClass);
  7674. function ContentTypeRejectedError() {
  7675. ContentTypeRejectedError.__super__.constructor.apply(this, arguments);
  7676. this.name = 'ContentTypeRejectedError';
  7677. }
  7678. return ContentTypeRejectedError;
  7679. })(Error);
  7680. module.exports = {
  7681. NetworkError: NetworkError,
  7682. HttpError: HttpError,
  7683. HttpNotFoundError: HttpNotFoundError,
  7684. HttpServerError: HttpServerError,
  7685. ContentTypeRejectedError: ContentTypeRejectedError
  7686. };
  7687. },{}],31:[function(require,module,exports){
  7688. /* @module omega-target/log */
  7689. var Log, replacer;
  7690. Log = require('./log');
  7691. replacer = function(key, value) {
  7692. switch (key) {
  7693. case "username":
  7694. case "password":
  7695. case "host":
  7696. case "port":
  7697. return "<secret>";
  7698. default:
  7699. return value;
  7700. }
  7701. };
  7702. module.exports = Log = {
  7703. /**
  7704. * Pretty-print an object and return the result string.
  7705. * @param {{}} obj The object to format
  7706. * @returns {String} the formatted object in string
  7707. */
  7708. str: function(obj) {
  7709. if (typeof obj === 'object' && obj !== null) {
  7710. if (obj.debugStr != null) {
  7711. if (typeof obj.debugStr === 'function') {
  7712. return obj.debugStr();
  7713. } else {
  7714. return obj.debugStr;
  7715. }
  7716. } else if (obj instanceof Error) {
  7717. return obj.stack || obj.message;
  7718. } else {
  7719. return JSON.stringify(obj, replacer, 4);
  7720. }
  7721. } else if (typeof obj === 'function') {
  7722. if (obj.name) {
  7723. return "<f: " + obj.name + ">";
  7724. } else {
  7725. return obj.toString();
  7726. }
  7727. } else {
  7728. return '' + obj;
  7729. }
  7730. },
  7731. /**
  7732. * Print something to the log.
  7733. * @param {...{}} args The objects to log
  7734. */
  7735. log: console.log.bind(console),
  7736. /**
  7737. * Print something to the error log.
  7738. * @param {...{}} args The objects to log
  7739. */
  7740. error: console.error.bind(console),
  7741. /**
  7742. * Log a function call with target and arguments
  7743. * @param {string} name The name of the method
  7744. * @param {Array} args The arguments to the method call
  7745. */
  7746. func: function(name, args) {
  7747. return this.log(name, '(', [].slice.call(args), ')');
  7748. },
  7749. /**
  7750. * Log a method call with target and arguments
  7751. * @param {string} name The name of the method
  7752. * @param {{}} self The target of the method call
  7753. * @param {Array} args The arguments to the method call
  7754. */
  7755. method: function(name, self, args) {
  7756. return this.log(this.str(self), '<<', name, [].slice.call(args));
  7757. }
  7758. };
  7759. },{"./log":31}],32:[function(require,module,exports){
  7760. /* @module omega-target/options */
  7761. var Log, OmegaPac, Options, Promise, Storage, jsondiffpatch,
  7762. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  7763. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  7764. hasProp = {}.hasOwnProperty;
  7765. Promise = require('bluebird');
  7766. Log = require('./log');
  7767. Storage = require('./storage');
  7768. OmegaPac = require('omega-pac');
  7769. jsondiffpatch = require('jsondiffpatch');
  7770. Options = (function() {
  7771. /**
  7772. * The entire set of options including profiles and other settings.
  7773. * @typedef OmegaOptions
  7774. * @type {object}
  7775. */
  7776. /**
  7777. * All the options, in a map from key to value.
  7778. * @type OmegaOptions
  7779. */
  7780. var NoOptionsError, ProfileNotExistError;
  7781. Options.prototype._options = null;
  7782. Options.prototype._storage = null;
  7783. Options.prototype._state = null;
  7784. Options.prototype._currentProfileName = null;
  7785. Options.prototype._revertToProfileName = null;
  7786. Options.prototype._watchingProfiles = {};
  7787. Options.prototype._tempProfile = null;
  7788. Options.prototype._tempProfileActive = false;
  7789. Options.prototype.fallbackProfileName = 'system';
  7790. Options.prototype._isSystem = false;
  7791. Options.prototype.debugStr = 'Options';
  7792. Options.prototype.ready = null;
  7793. Options.ProfileNotExistError = ProfileNotExistError = (function(superClass) {
  7794. extend(ProfileNotExistError, superClass);
  7795. function ProfileNotExistError(profileName1) {
  7796. this.profileName = profileName1;
  7797. ProfileNotExistError.__super__.constructor.apply(this, arguments).constructor("Profile " + this.profileName + " does not exist!");
  7798. }
  7799. return ProfileNotExistError;
  7800. })(Error);
  7801. Options.NoOptionsError = NoOptionsError = (function(superClass) {
  7802. extend(NoOptionsError, superClass);
  7803. function NoOptionsError() {
  7804. NoOptionsError.__super__.constructor.apply(this, arguments);
  7805. }
  7806. return NoOptionsError;
  7807. })(Error);
  7808. /**
  7809. * Transform options values (especially profiles) for syncing.
  7810. * @param {{}} value The value to transform
  7811. * @param {{}} key The key of the options
  7812. * @returns {{}} The transformed value
  7813. */
  7814. Options.transformValueForSync = function(value, key) {
  7815. var k, profile, v;
  7816. if (key[0] === '+') {
  7817. if (OmegaPac.Profiles.updateUrl(value)) {
  7818. profile = {};
  7819. for (k in value) {
  7820. v = value[k];
  7821. if (k === 'lastUpdate' || k === 'ruleList' || k === 'pacScript') {
  7822. continue;
  7823. }
  7824. profile[k] = v;
  7825. }
  7826. value = profile;
  7827. }
  7828. }
  7829. return value;
  7830. };
  7831. function Options(options, _storage, _state, log, sync, proxyImpl) {
  7832. this._storage = _storage;
  7833. this._state = _state;
  7834. this.log = log;
  7835. this.sync = sync;
  7836. this.proxyImpl = proxyImpl;
  7837. this._setOptions = bind(this._setOptions, this);
  7838. this._options = {};
  7839. this._tempProfileRules = {};
  7840. this._tempProfileRulesByProfile = {};
  7841. if (this._storage == null) {
  7842. this._storage = Storage();
  7843. }
  7844. if (this._state == null) {
  7845. this._state = Storage();
  7846. }
  7847. if (this.log == null) {
  7848. this.log = Log;
  7849. }
  7850. if (options == null) {
  7851. this.init();
  7852. } else {
  7853. this.ready = this._storage.remove().then((function(_this) {
  7854. return function() {
  7855. return _this._storage.set(options);
  7856. };
  7857. })(this)).then((function(_this) {
  7858. return function() {
  7859. return _this.init();
  7860. };
  7861. })(this));
  7862. }
  7863. }
  7864. /**
  7865. * Attempt to load options from local and remote storage.
  7866. * @param {?{}} args Extra arguments
  7867. * @param {number=3} args.retry Number of retries before giving up.
  7868. * @returns {Promise<OmegaOptions>} The loaded options
  7869. */
  7870. Options.prototype.loadOptions = function(arg) {
  7871. var loadRaw, ref, retry;
  7872. retry = (arg != null ? arg : {}).retry;
  7873. if (retry == null) {
  7874. retry = 3;
  7875. }
  7876. if (typeof this._syncWatchStop === "function") {
  7877. this._syncWatchStop();
  7878. }
  7879. this._syncWatchStop = null;
  7880. if (typeof this._watchStop === "function") {
  7881. this._watchStop();
  7882. }
  7883. this._watchStop = null;
  7884. loadRaw = typeof options !== "undefined" && options !== null ? Promise.resolve(options) : !((ref = this.sync) != null ? ref.enabled : void 0) ? (this.sync == null ? this._state.set({
  7885. 'syncOptions': 'unsupported'
  7886. }) : void 0, this._storage.get(null)) : (this._state.set({
  7887. 'syncOptions': 'sync'
  7888. }), this._syncWatchStop = this.sync.watchAndPull(this._storage), this.sync.copyTo(this._storage)["catch"](Storage.StorageUnavailableError, (function(_this) {
  7889. return function() {
  7890. console.error('Warning: Sync storage is not available in this ' + 'browser! Disabling options sync.');
  7891. if (typeof _this._syncWatchStop === "function") {
  7892. _this._syncWatchStop();
  7893. }
  7894. _this._syncWatchStop = null;
  7895. _this.sync = null;
  7896. return _this._state.set({
  7897. 'syncOptions': 'unsupported'
  7898. });
  7899. };
  7900. })(this)).then((function(_this) {
  7901. return function() {
  7902. return _this._storage.get(null);
  7903. };
  7904. })(this)));
  7905. return this.optionsLoaded = loadRaw.then((function(_this) {
  7906. return function(options) {
  7907. return _this.upgrade(options);
  7908. };
  7909. })(this)).then((function(_this) {
  7910. return function(arg1) {
  7911. var changes, options;
  7912. options = arg1[0], changes = arg1[1];
  7913. return _this._storage.apply({
  7914. changes: changes
  7915. })["return"](options);
  7916. };
  7917. })(this)).tap((function(_this) {
  7918. return function(options) {
  7919. _this._options = options;
  7920. _this._watchStop = _this._watch();
  7921. return _this._state.get({
  7922. 'syncOptions': ''
  7923. }).then(function(arg1) {
  7924. var syncOptions;
  7925. syncOptions = arg1.syncOptions;
  7926. if (syncOptions) {
  7927. return;
  7928. }
  7929. _this._state.set({
  7930. 'syncOptions': 'conflict'
  7931. });
  7932. return _this.sync.storage.get('schemaVersion').then(function(arg2) {
  7933. var schemaVersion;
  7934. schemaVersion = arg2.schemaVersion;
  7935. if (!schemaVersion) {
  7936. return _this._state.set({
  7937. 'syncOptions': 'pristine'
  7938. });
  7939. }
  7940. });
  7941. });
  7942. };
  7943. })(this))["catch"]((function(_this) {
  7944. return function(e) {
  7945. var getFallbackOptions;
  7946. if (!(retry > 0)) {
  7947. return Promise.reject(e);
  7948. }
  7949. getFallbackOptions = Promise.resolve().then(function() {
  7950. if (e instanceof NoOptionsError) {
  7951. _this._state.get({
  7952. 'firstRun': 'new',
  7953. 'web.switchGuide': 'showOnFirstUse'
  7954. }).then(function(items) {
  7955. return _this._state.set(items);
  7956. });
  7957. if (_this.sync == null) {
  7958. return null;
  7959. }
  7960. return _this._state.get({
  7961. 'syncOptions': ''
  7962. }).then(function(arg1) {
  7963. var syncOptions;
  7964. syncOptions = arg1.syncOptions;
  7965. if (syncOptions === 'conflict') {
  7966. return;
  7967. }
  7968. return _this.sync.storage.get(null).then(function(options) {
  7969. if (!options['schemaVersion']) {
  7970. _this._state.set({
  7971. 'syncOptions': 'pristine'
  7972. });
  7973. return null;
  7974. } else {
  7975. _this._state.set({
  7976. 'syncOptions': 'sync'
  7977. });
  7978. _this.sync.enabled = true;
  7979. _this.log.log('Options#loadOptions::fromSync', options);
  7980. return options;
  7981. }
  7982. })["catch"](function() {
  7983. return null;
  7984. });
  7985. });
  7986. } else {
  7987. _this.log.error(e.stack);
  7988. _this._state.remove(['syncOptions']);
  7989. return null;
  7990. }
  7991. });
  7992. return getFallbackOptions.then(function(options) {
  7993. var prevEnabled;
  7994. if (options == null) {
  7995. options = _this.parseOptions(_this.getDefaultOptions());
  7996. }
  7997. if (_this.sync != null) {
  7998. prevEnabled = _this.sync.enabled;
  7999. _this.sync.enabled = false;
  8000. }
  8001. return _this._storage.remove().then(function() {
  8002. return _this._storage.set(options);
  8003. }).then(function() {
  8004. if (_this.sync != null) {
  8005. _this.sync.enabled = prevEnabled;
  8006. }
  8007. return _this.loadOptions({
  8008. retry: retry - 1
  8009. });
  8010. });
  8011. });
  8012. };
  8013. })(this));
  8014. };
  8015. /**
  8016. * Attempt to initialize (or reinitialize) options.
  8017. * @returns {Promise<OmegaOptions>} A promise that is fulfilled on ready.
  8018. */
  8019. Options.prototype.init = function() {
  8020. this.ready = this.loadOptions().then((function(_this) {
  8021. return function() {
  8022. if (_this._options['-startupProfileName']) {
  8023. return _this.applyProfile(_this._options['-startupProfileName']);
  8024. } else {
  8025. return _this._state.get({
  8026. 'currentProfileName': _this.fallbackProfileName,
  8027. 'isSystemProfile': false
  8028. }).then(function(st) {
  8029. if (st['isSystemProfile']) {
  8030. return _this.applyProfile('system');
  8031. } else {
  8032. return _this.applyProfile(st['currentProfileName'] || _this.fallbackProfileName);
  8033. }
  8034. });
  8035. }
  8036. };
  8037. })(this))["catch"]((function(_this) {
  8038. return function(err) {
  8039. if (!err instanceof ProfileNotExistError) {
  8040. _this.log.error(err);
  8041. }
  8042. return _this.applyProfile(_this.fallbackProfileName);
  8043. };
  8044. })(this))["catch"]((function(_this) {
  8045. return function(err) {
  8046. return _this.log.error(err);
  8047. };
  8048. })(this)).then((function(_this) {
  8049. return function() {
  8050. return _this.getAll();
  8051. };
  8052. })(this));
  8053. this.ready.then((function(_this) {
  8054. return function() {
  8055. var ref;
  8056. if ((ref = _this.sync) != null ? ref.enabled : void 0) {
  8057. _this.sync.requestPush(_this._options);
  8058. }
  8059. _this._state.get({
  8060. 'firstRun': ''
  8061. }).then(function(arg) {
  8062. var firstRun;
  8063. firstRun = arg.firstRun;
  8064. if (firstRun) {
  8065. return _this.onFirstRun(firstRun);
  8066. }
  8067. });
  8068. if (_this._options['-downloadInterval'] > 0) {
  8069. return _this.updateProfile();
  8070. }
  8071. };
  8072. })(this));
  8073. return this.ready;
  8074. };
  8075. Options.prototype.toString = function() {
  8076. return "<Options>";
  8077. };
  8078. /**
  8079. * Return a localized, human-readable description of the given profile.
  8080. * In base class, this method is not implemented and will always return null.
  8081. * @param {?{}} profile The profile to print
  8082. * @returns {string} Description of the profile with details
  8083. */
  8084. Options.prototype.printProfile = function(profile) {
  8085. return null;
  8086. };
  8087. /**
  8088. * Upgrade options from previous versions.
  8089. * For now, this method only supports schemaVersion 1 and 2. If so, it upgrades
  8090. * the options to version 2 (the latest version). Otherwise it rejects.
  8091. * It is recommended for the derived classes to call super() two times in the
  8092. * beginning and in the end of the implementation to check the schemaVersion
  8093. * and to apply future upgrades, respectively.
  8094. * Example: super(options).catch -> super(doCustomUpgrades(options), changes)
  8095. * @param {?OmegaOptions} options The legacy options to upgrade
  8096. * @param {{}={}} changes Previous pending changes to be applied. Default to
  8097. * an empty dictionary. Please provide this argument when calling super().
  8098. * @returns {Promise<[OmegaOptions, {}]>} The new options and the changes.
  8099. */
  8100. Options.prototype.upgrade = function(options, changes) {
  8101. var autoDetectUsed, version;
  8102. if (changes == null) {
  8103. changes = {};
  8104. }
  8105. version = options != null ? options['schemaVersion'] : void 0;
  8106. if (version === 1) {
  8107. autoDetectUsed = false;
  8108. OmegaPac.Profiles.each(options, function(key, profile) {
  8109. var refs;
  8110. if (!autoDetectUsed) {
  8111. refs = OmegaPac.Profiles.directReferenceSet(profile);
  8112. if (refs['+auto_detect']) {
  8113. return autoDetectUsed = true;
  8114. }
  8115. }
  8116. });
  8117. if (autoDetectUsed) {
  8118. options['+auto_detect'] = OmegaPac.Profiles.create({
  8119. name: 'auto_detect',
  8120. profileType: 'PacProfile',
  8121. pacUrl: 'http://wpad/wpad.dat',
  8122. color: '#00cccc'
  8123. });
  8124. }
  8125. version = changes['schemaVersion'] = options['schemaVersion'] = 2;
  8126. }
  8127. if (version === 2) {
  8128. return Promise.resolve([options, changes]);
  8129. } else {
  8130. return Promise.reject(new Error("Invalid schemaVerion " + version + "!"));
  8131. }
  8132. };
  8133. /**
  8134. * Parse options in various formats (including JSON & base64).
  8135. * @param {OmegaOptions|string} options The options to parse
  8136. * @returns {Promise<OmegaOptions>} The parsed options.
  8137. */
  8138. Options.prototype.parseOptions = function(options) {
  8139. var Buffer, _;
  8140. if (typeof options === 'string') {
  8141. if (options[0] !== '{') {
  8142. try {
  8143. Buffer = require('buffer').Buffer;
  8144. options = new Buffer(options, 'base64').toString('utf8');
  8145. } catch (error) {
  8146. _ = error;
  8147. options = null;
  8148. }
  8149. }
  8150. options = (function() {
  8151. try {
  8152. return JSON.parse(options);
  8153. } catch (error) {}
  8154. })();
  8155. }
  8156. if (!options) {
  8157. throw new Error('Invalid options!');
  8158. }
  8159. return options;
  8160. };
  8161. /**
  8162. * Reset the options to the given options or initial options.
  8163. * @param {?OmegaOptions} options The options to set. Defaults to initial.
  8164. * @returns {Promise<OmegaOptions>} The options just applied
  8165. */
  8166. Options.prototype.reset = function(options) {
  8167. this.log.method('Options#reset', this, arguments);
  8168. if (options == null) {
  8169. options = this.getDefaultOptions();
  8170. }
  8171. return this.upgrade(this.parseOptions(options)).then((function(_this) {
  8172. return function(arg) {
  8173. var opt;
  8174. opt = arg[0];
  8175. if (_this.sync != null) {
  8176. _this.sync.enabled = false;
  8177. }
  8178. _this._state.remove(['syncOptions']);
  8179. return _this._storage.remove().then(function() {
  8180. return _this._storage.set(opt);
  8181. }).then(function() {
  8182. return _this.init();
  8183. });
  8184. };
  8185. })(this));
  8186. };
  8187. /**
  8188. * Called on the first initialization of options.
  8189. * @param {reason} reason The value of 'firstRun' in state.
  8190. */
  8191. Options.prototype.onFirstRun = function(reason) {
  8192. return null;
  8193. };
  8194. /**
  8195. * Return the default options used initially and on resets.
  8196. * @returns {?OmegaOptions} The default options.
  8197. */
  8198. Options.prototype.getDefaultOptions = function() {
  8199. return require('./default_options')();
  8200. };
  8201. /**
  8202. * Return all options.
  8203. * @returns {?OmegaOptions} The options.
  8204. */
  8205. Options.prototype.getAll = function() {
  8206. return this._options;
  8207. };
  8208. /**
  8209. * Get profile by name.
  8210. * @returns {?{}} The profile, or undefined if no such profile.
  8211. */
  8212. Options.prototype.profile = function(name) {
  8213. return OmegaPac.Profiles.byName(name, this._options);
  8214. };
  8215. /**
  8216. * Apply the patch to the current options.
  8217. * @param {jsondiffpatch} patch The patch to apply
  8218. * @returns {Promise<OmegaOptions>} The updated options
  8219. */
  8220. Options.prototype.patch = function(patch) {
  8221. var changes, delta, key;
  8222. if (!patch) {
  8223. return;
  8224. }
  8225. this.log.method('Options#patch', this, arguments);
  8226. this._options = jsondiffpatch.patch(this._options, patch);
  8227. changes = {};
  8228. for (key in patch) {
  8229. if (!hasProp.call(patch, key)) continue;
  8230. delta = patch[key];
  8231. if (delta.length === 3 && delta[1] === 0 && delta[2] === 0) {
  8232. changes[key] = void 0;
  8233. } else {
  8234. changes[key] = this._options[key];
  8235. }
  8236. }
  8237. return this._setOptions(changes);
  8238. };
  8239. Options.prototype._setOptions = function(changes, args) {
  8240. var checkRev, currentProfileAffected, j, key, len, profilesChanged, ref, ref1, ref2, ref3, removed, result, value;
  8241. removed = [];
  8242. checkRev = (ref = args != null ? args.checkRevision : void 0) != null ? ref : false;
  8243. profilesChanged = false;
  8244. currentProfileAffected = false;
  8245. for (key in changes) {
  8246. if (!hasProp.call(changes, key)) continue;
  8247. value = changes[key];
  8248. if (typeof value === 'undefined') {
  8249. delete this._options[key];
  8250. removed.push(key);
  8251. if (key[0] === '+') {
  8252. profilesChanged = true;
  8253. if (key === '+' + this._currentProfileName) {
  8254. currentProfileAffected = 'removed';
  8255. }
  8256. }
  8257. } else {
  8258. if (key[0] === '+') {
  8259. if (checkRev && this._options[key]) {
  8260. result = OmegaPac.Revision.compare(this._options[key].revision, value.revision);
  8261. if (result >= 0) {
  8262. continue;
  8263. }
  8264. }
  8265. profilesChanged = true;
  8266. }
  8267. this._options[key] = value;
  8268. }
  8269. if (!currentProfileAffected && this._watchingProfiles[key]) {
  8270. currentProfileAffected = 'changed';
  8271. }
  8272. }
  8273. switch (currentProfileAffected) {
  8274. case 'removed':
  8275. this.applyProfile(this.fallbackProfileName);
  8276. break;
  8277. case 'changed':
  8278. this.applyProfile(this._currentProfileName, {
  8279. update: false
  8280. });
  8281. break;
  8282. default:
  8283. if (profilesChanged) {
  8284. this._setAvailableProfiles();
  8285. }
  8286. }
  8287. if ((ref1 = args != null ? args.persist : void 0) != null ? ref1 : true) {
  8288. if ((ref2 = this.sync) != null ? ref2.enabled : void 0) {
  8289. if ((ref3 = this.sync) != null) {
  8290. ref3.requestPush(changes);
  8291. }
  8292. }
  8293. for (j = 0, len = removed.length; j < len; j++) {
  8294. key = removed[j];
  8295. delete changes[key];
  8296. }
  8297. return this._storage.set(changes).then((function(_this) {
  8298. return function() {
  8299. _this._storage.remove(removed);
  8300. return _this._options;
  8301. };
  8302. })(this));
  8303. }
  8304. };
  8305. Options.prototype._watch = function() {
  8306. var handler;
  8307. handler = (function(_this) {
  8308. return function(changes) {
  8309. var monitorWebRequests, quickSwitchProfiles, refresh, showExternal, showMenu;
  8310. if (changes) {
  8311. _this._setOptions(changes, {
  8312. checkRevision: true,
  8313. persist: false
  8314. });
  8315. } else {
  8316. changes = _this._options;
  8317. }
  8318. refresh = changes['-refreshOnProfileChange'];
  8319. if (refresh != null) {
  8320. _this._state.set({
  8321. 'refreshOnProfileChange': refresh
  8322. });
  8323. }
  8324. if (Object.prototype.hasOwnProperty.call(changes, '-showExternalProfile')) {
  8325. showExternal = changes['-showExternalProfile'];
  8326. if (showExternal == null) {
  8327. showExternal = true;
  8328. _this._setOptions({
  8329. '-showExternalProfile': true
  8330. }, {
  8331. persist: true
  8332. });
  8333. }
  8334. _this._state.set({
  8335. 'showExternalProfile': showExternal
  8336. });
  8337. }
  8338. quickSwitchProfiles = changes['-quickSwitchProfiles'];
  8339. quickSwitchProfiles = _this._cleanUpQuickSwitchProfiles(quickSwitchProfiles);
  8340. if ((changes['-enableQuickSwitch'] != null) || (quickSwitchProfiles != null)) {
  8341. _this.reloadQuickSwitch();
  8342. }
  8343. if (changes['-downloadInterval'] != null) {
  8344. _this.schedule('updateProfile', _this._options['-downloadInterval'], function() {
  8345. return _this.updateProfile();
  8346. });
  8347. }
  8348. if ((changes['-showInspectMenu'] != null) || changes === _this._options) {
  8349. showMenu = _this._options['-showInspectMenu'];
  8350. if (showMenu == null) {
  8351. showMenu = true;
  8352. _this._setOptions({
  8353. '-showInspectMenu': true
  8354. }, {
  8355. persist: true
  8356. });
  8357. }
  8358. _this.setInspect({
  8359. showMenu: showMenu
  8360. });
  8361. }
  8362. if ((changes['-monitorWebRequests'] != null) || changes === _this._options) {
  8363. monitorWebRequests = _this._options['-monitorWebRequests'];
  8364. if (monitorWebRequests == null) {
  8365. monitorWebRequests = true;
  8366. _this._setOptions({
  8367. '-monitorWebRequests': true
  8368. }, {
  8369. persist: true
  8370. });
  8371. }
  8372. return _this.setMonitorWebRequests(monitorWebRequests);
  8373. }
  8374. };
  8375. })(this);
  8376. handler();
  8377. return this._storage.watch(null, handler);
  8378. };
  8379. Options.prototype._cleanUpQuickSwitchProfiles = function(quickSwitchProfiles) {
  8380. var seenQuickSwitchProfile, validQuickSwitchProfiles;
  8381. if (quickSwitchProfiles == null) {
  8382. return;
  8383. }
  8384. seenQuickSwitchProfile = {};
  8385. validQuickSwitchProfiles = quickSwitchProfiles.filter((function(_this) {
  8386. return function(name) {
  8387. var key;
  8388. if (!name) {
  8389. return false;
  8390. }
  8391. key = OmegaPac.Profiles.nameAsKey(name);
  8392. if (seenQuickSwitchProfile[key]) {
  8393. return false;
  8394. }
  8395. if (!OmegaPac.Profiles.byName(name, _this._options)) {
  8396. return false;
  8397. }
  8398. seenQuickSwitchProfile[key] = true;
  8399. return true;
  8400. };
  8401. })(this));
  8402. if (validQuickSwitchProfiles.length !== quickSwitchProfiles.length) {
  8403. this._setOptions({
  8404. '-quickSwitchProfiles': validQuickSwitchProfiles
  8405. }, {
  8406. persist: true
  8407. });
  8408. }
  8409. return validQuickSwitchProfiles;
  8410. };
  8411. /**
  8412. * Reload the quick switch according to settings.
  8413. * @returns {Promise} A promise which is fulfilled when the quick switch is set
  8414. */
  8415. Options.prototype.reloadQuickSwitch = function() {
  8416. var profiles;
  8417. profiles = this._options['-quickSwitchProfiles'];
  8418. if (profiles.length < 2) {
  8419. profiles = null;
  8420. }
  8421. if (this._options['-enableQuickSwitch']) {
  8422. return this.setQuickSwitch(profiles, !!profiles);
  8423. } else {
  8424. return this.setQuickSwitch(null, !!profiles);
  8425. }
  8426. };
  8427. /**
  8428. * Apply the settings related to element proxy inspection.
  8429. * In base class, this method is not implemented and will not do anything.
  8430. * @param {{}} settings
  8431. * @param {boolean} settings.showMenu Whether to show the menu or not
  8432. * @returns {Promise} A promise which is fulfilled when the settings apply
  8433. */
  8434. Options.prototype.setInspect = function() {
  8435. return Promise.resolve();
  8436. };
  8437. /**
  8438. * Apply the settings related to web request monitoring.
  8439. * In base class, this method is not implemented and will not do anything.
  8440. * @param {boolean} enabled Whether network shall be monitored or not
  8441. * @returns {Promise} A promise which is fulfilled when the settings apply
  8442. */
  8443. Options.prototype.setMonitorWebRequests = function() {
  8444. return Promise.resolve();
  8445. };
  8446. /**
  8447. * @callback watchCallback
  8448. * @param {Object.<string, {}>} changes A map from keys to values.
  8449. */
  8450. /**
  8451. * Watch for any changes to the options
  8452. * @param {watchCallback} callback Called everytime the value of a key changes
  8453. * @returns {function} Calling the returned function will stop watching.
  8454. */
  8455. Options.prototype.watch = function(callback) {
  8456. return this._storage.watch(null, callback);
  8457. };
  8458. Options.prototype._profileNotFound = function(name) {
  8459. this.log.error("Profile " + name + " not found! Things may go very, very wrong.");
  8460. return OmegaPac.Profiles.create({
  8461. name: name,
  8462. profileType: 'VirtualProfile',
  8463. defaultProfileName: 'direct'
  8464. });
  8465. };
  8466. /**
  8467. * Get PAC script for profile.
  8468. * @param {?string|Object} profile The name of the profile, or the profile.
  8469. * @param {bool=false} compress Compress the script if true.
  8470. * @returns {string} The compiled
  8471. */
  8472. Options.prototype.pacForProfile = function(profile, compress) {
  8473. var ast;
  8474. if (compress == null) {
  8475. compress = false;
  8476. }
  8477. ast = OmegaPac.PacGenerator.script(this._options, profile, {
  8478. profileNotFound: this._profileNotFound.bind(this)
  8479. });
  8480. if (compress) {
  8481. ast = OmegaPac.PacGenerator.compress(ast);
  8482. }
  8483. return Promise.resolve(OmegaPac.PacGenerator.ascii(ast.print_to_string()));
  8484. };
  8485. Options.prototype._setAvailableProfiles = function() {
  8486. var allReferenceSet, currentIncludable, profile, profiles, results;
  8487. profile = this._currentProfileName ? this.currentProfile() : null;
  8488. profiles = {};
  8489. currentIncludable = profile && OmegaPac.Profiles.isIncludable(profile);
  8490. allReferenceSet = null;
  8491. if (!profile || !OmegaPac.Profiles.isInclusive(profile)) {
  8492. results = [];
  8493. }
  8494. OmegaPac.Profiles.each(this._options, (function(_this) {
  8495. return function(key, p) {
  8496. profiles[key] = {
  8497. name: p.name,
  8498. profileType: p.profileType,
  8499. color: p.color,
  8500. desc: _this.printProfile(p),
  8501. builtin: p.builtin ? true : void 0
  8502. };
  8503. if (p.profileType === 'VirtualProfile') {
  8504. profiles[key].defaultProfileName = p.defaultProfileName;
  8505. if (allReferenceSet == null) {
  8506. allReferenceSet = profile ? OmegaPac.Profiles.allReferenceSet(profile, _this._options, {
  8507. profileNotFound: _this._profileNotFound.bind(_this)
  8508. }) : {};
  8509. }
  8510. if (allReferenceSet[key]) {
  8511. profiles[key].validResultProfiles = OmegaPac.Profiles.validResultProfilesFor(p, _this._options).map(function(result) {
  8512. return result.name;
  8513. });
  8514. }
  8515. }
  8516. if (currentIncludable && OmegaPac.Profiles.isIncludable(p)) {
  8517. return results != null ? results.push(p.name) : void 0;
  8518. }
  8519. };
  8520. })(this));
  8521. if (profile && OmegaPac.Profiles.isInclusive(profile)) {
  8522. results = OmegaPac.Profiles.validResultProfilesFor(profile, this._options);
  8523. results = results.map(function(profile) {
  8524. return profile.name;
  8525. });
  8526. }
  8527. return this._state.set({
  8528. 'availableProfiles': profiles,
  8529. 'validResultProfiles': results
  8530. });
  8531. };
  8532. /**
  8533. * Apply the profile by name.
  8534. * @param {?string} name The name of the profile, or null for default.
  8535. * @param {?{}} options Some options
  8536. * @param {bool=true} options.proxy Set proxy for the applied profile if true
  8537. * @param {bool=true} options.update Try to update this profile and referenced
  8538. * profiles after the proxy is set.
  8539. * @param {bool=false} options.system Whether options is in system mode.
  8540. * @param {{}=undefined} options.reason will be passed to currentProfileChanged
  8541. * @returns {Promise} A promise which is fulfilled when the profile is applied.
  8542. */
  8543. Options.prototype.applyProfile = function(name, options) {
  8544. var applyProxy, j, key, l, len, len1, list, profile, ref, removedKeys, rule;
  8545. this.log.method('Options#applyProfile', this, arguments);
  8546. profile = OmegaPac.Profiles.byName(name, this._options);
  8547. if (!profile) {
  8548. return Promise.reject(new ProfileNotExistError(name));
  8549. }
  8550. this._currentProfileName = profile.name;
  8551. this._isSystem = (options != null ? options.system : void 0) || (profile.profileType === 'SystemProfile');
  8552. this._watchingProfiles = OmegaPac.Profiles.allReferenceSet(profile, this._options, {
  8553. profileNotFound: this._profileNotFound.bind(this)
  8554. });
  8555. this._state.set({
  8556. 'currentProfileName': this._currentProfileName,
  8557. 'isSystemProfile': this._isSystem,
  8558. 'currentProfileCanAddRule': (profile.rules != null) && profile.profileType !== 'VirtualProfile'
  8559. });
  8560. this._setAvailableProfiles();
  8561. this.currentProfileChanged(options != null ? options.reason : void 0);
  8562. if ((options != null) && options.proxy === false) {
  8563. return Promise.resolve();
  8564. }
  8565. this._tempProfileActive = false;
  8566. if ((this._tempProfile != null) && OmegaPac.Profiles.isIncludable(profile)) {
  8567. this._tempProfileActive = true;
  8568. if (this._tempProfile.defaultProfileName !== profile.name) {
  8569. this._tempProfile.defaultProfileName = profile.name;
  8570. this._tempProfile.color = profile.color;
  8571. OmegaPac.Profiles.updateRevision(this._tempProfile);
  8572. }
  8573. removedKeys = [];
  8574. ref = this._tempProfileRulesByProfile;
  8575. for (key in ref) {
  8576. if (!hasProp.call(ref, key)) continue;
  8577. list = ref[key];
  8578. if (!OmegaPac.Profiles.byKey(key, this._options)) {
  8579. removedKeys.push(key);
  8580. for (j = 0, len = list.length; j < len; j++) {
  8581. rule = list[j];
  8582. rule.profileName = null;
  8583. this._tempProfile.rules.splice(this._tempProfile.rules.indexOf(rule), 1);
  8584. }
  8585. }
  8586. }
  8587. if (removedKeys.length > 0) {
  8588. for (l = 0, len1 = removedKeys.length; l < len1; l++) {
  8589. key = removedKeys[l];
  8590. delete this._tempProfileRulesByProfile[key];
  8591. }
  8592. OmegaPac.Profiles.updateRevision(this._tempProfile);
  8593. }
  8594. this._watchingProfiles = OmegaPac.Profiles.allReferenceSet(this._tempProfile, this._options, {
  8595. profileNotFound: this._profileNotFound.bind(this)
  8596. });
  8597. applyProxy = this.proxyImpl.applyProfile(this._tempProfile, profile, this._options);
  8598. } else {
  8599. applyProxy = this.proxyImpl.applyProfile(profile, profile, this._options);
  8600. }
  8601. if ((options != null) && options.update === false) {
  8602. return applyProxy;
  8603. }
  8604. applyProxy.then((function(_this) {
  8605. return function() {
  8606. var ref1, updateProfiles;
  8607. if (!(_this._options['-downloadInterval'] > 0)) {
  8608. return;
  8609. }
  8610. if (_this._currentProfileName !== profile.name) {
  8611. return;
  8612. }
  8613. updateProfiles = [];
  8614. ref1 = _this._watchingProfiles;
  8615. for (key in ref1) {
  8616. name = ref1[key];
  8617. updateProfiles.push(name);
  8618. }
  8619. if (updateProfiles.length > 0) {
  8620. return _this.updateProfile(updateProfiles);
  8621. }
  8622. };
  8623. })(this));
  8624. return applyProxy;
  8625. };
  8626. /**
  8627. * Get the current applied profile.
  8628. * @returns {{}} The current profile
  8629. */
  8630. Options.prototype.currentProfile = function() {
  8631. if (this._currentProfileName) {
  8632. return OmegaPac.Profiles.byName(this._currentProfileName, this._options);
  8633. } else {
  8634. return this._externalProfile;
  8635. }
  8636. };
  8637. /**
  8638. * Return true if in system mode.
  8639. * @returns {boolean} True if system mode is activated
  8640. */
  8641. Options.prototype.isSystem = function() {
  8642. return this._isSystem;
  8643. };
  8644. /**
  8645. * Called when current profile has changed.
  8646. * In base class, this method is not implemented and will not do anything.
  8647. */
  8648. Options.prototype.currentProfileChanged = function() {
  8649. return null;
  8650. };
  8651. /**
  8652. * Set or disable the quick switch profiles.
  8653. * In base class, this method is not implemented and will not do anything.
  8654. * @param {string[]|null} quickSwitch The profile names, or null to disable
  8655. * @param {boolean} canEnable Whether user can enable quick switch or not.
  8656. * @returns {Promise} A promise which is fulfilled when the quick switch is set
  8657. */
  8658. Options.prototype.setQuickSwitch = function(quickSwitch, canEnable) {
  8659. return Promise.resolve();
  8660. };
  8661. /**
  8662. * Schedule a task that runs every periodInMinutes.
  8663. * In base class, this method is not implemented and will not do anything.
  8664. * @param {string} name The name of the schedule. If there is a previous
  8665. * schedule with the same name, it will be replaced by the new one.
  8666. * @param {number} periodInMinutes The interval of the schedule
  8667. * @param {function} callback The callback to call when the task runs
  8668. * @returns {Promise} A promise which is fulfilled when the schedule is set
  8669. */
  8670. Options.prototype.schedule = function(name, periodInMinutes, callback) {
  8671. return Promise.resolve();
  8672. };
  8673. /**
  8674. * Return true if the match result of current profile does not change with URLs
  8675. * @returns {bool} Whether @match always return the same result for requests
  8676. */
  8677. Options.prototype.isCurrentProfileStatic = function() {
  8678. var currentProfile;
  8679. if (!this._currentProfileName) {
  8680. return true;
  8681. }
  8682. if (this._tempProfileActive) {
  8683. return false;
  8684. }
  8685. currentProfile = this.currentProfile();
  8686. if (OmegaPac.Profiles.isInclusive(currentProfile)) {
  8687. return false;
  8688. }
  8689. return true;
  8690. };
  8691. /**
  8692. * Update the profile by name.
  8693. * @param {(string|string[]|null)} name The name of the profiles,
  8694. * or null for all.
  8695. * @param {?bool} opt_bypass_cache Do not read from the cache if true
  8696. * @returns {Promise<Object.<string,({}|Error)>>} A map from keys to updated
  8697. * profiles or errors.
  8698. * A value is an error if `value instanceof Error`. Otherwise the value is an
  8699. * updated profile.
  8700. */
  8701. Options.prototype.updateProfile = function(name, opt_bypass_cache) {
  8702. var results;
  8703. this.log.method('Options#updateProfile', this, arguments);
  8704. results = {};
  8705. OmegaPac.Profiles.each(this._options, (function(_this) {
  8706. return function(key, profile) {
  8707. var fetchResult, type_hints, url;
  8708. if (name != null) {
  8709. if (Array.isArray(name)) {
  8710. if (!(name.indexOf(profile.name) >= 0)) {
  8711. return;
  8712. }
  8713. } else {
  8714. if (profile.name !== name) {
  8715. return;
  8716. }
  8717. }
  8718. }
  8719. url = OmegaPac.Profiles.updateUrl(profile);
  8720. if (url) {
  8721. type_hints = OmegaPac.Profiles.updateContentTypeHints(profile);
  8722. fetchResult = _this.fetchUrl(url, opt_bypass_cache, type_hints);
  8723. return results[key] = fetchResult.then(function(data) {
  8724. var changes;
  8725. if (!data) {
  8726. return profile;
  8727. }
  8728. profile = OmegaPac.Profiles.byKey(key, _this._options);
  8729. profile.lastUpdate = new Date().toISOString();
  8730. if (OmegaPac.Profiles.update(profile, data)) {
  8731. OmegaPac.Profiles.dropCache(profile);
  8732. changes = {};
  8733. changes[key] = profile;
  8734. return _this._setOptions(changes)["return"](profile);
  8735. } else {
  8736. return profile;
  8737. }
  8738. })["catch"](function(reason) {
  8739. if (reason instanceof Error) {
  8740. return reason;
  8741. } else {
  8742. return new Error(reason);
  8743. }
  8744. });
  8745. }
  8746. };
  8747. })(this));
  8748. return Promise.props(results);
  8749. };
  8750. /**
  8751. * Make an HTTP GET request to fetch the content of the url.
  8752. * In base class, this method is not implemented and will always reject.
  8753. * @param {string} url The name of the profiles,
  8754. * @param {?bool} opt_bypass_cache Do not read from the cache if true
  8755. * @param {?string} opt_type_hints MIME type hints for downloaded content.
  8756. * @returns {Promise<String>} The text content fetched from the url
  8757. */
  8758. Options.prototype.fetchUrl = function(url, opt_bypass_cache, opt_type_hints) {
  8759. return Promise.reject(new Error('not implemented'));
  8760. };
  8761. Options.prototype._replaceRefChanges = function(fromName, toName, changes) {
  8762. var i, j, quickSwitch, ref;
  8763. if (changes == null) {
  8764. changes = {};
  8765. }
  8766. OmegaPac.Profiles.each(this._options, function(key, p) {
  8767. if (p.name === fromName || p.name === toName) {
  8768. return;
  8769. }
  8770. if (OmegaPac.Profiles.replaceRef(p, fromName, toName)) {
  8771. OmegaPac.Profiles.updateRevision(p);
  8772. return changes[OmegaPac.Profiles.nameAsKey(p)] = p;
  8773. }
  8774. });
  8775. if (this._options['-startupProfileName'] === fromName) {
  8776. changes['-startupProfileName'] = toName;
  8777. }
  8778. quickSwitch = this._options['-quickSwitchProfiles'];
  8779. if (quickSwitch.indexOf(toName) < 0) {
  8780. for (i = j = 0, ref = quickSwitch.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
  8781. if (quickSwitch[i] === fromName) {
  8782. quickSwitch[i] = toName;
  8783. changes['-quickSwitchProfiles'] = quickSwitch;
  8784. }
  8785. }
  8786. }
  8787. return changes;
  8788. };
  8789. /**
  8790. * Replace all references of profile fromName to toName.
  8791. * @param {String} fromName The original profile name
  8792. * @param {String} toname The target profile name
  8793. * @returns {Promise<OmegaOptions>} The updated options
  8794. */
  8795. Options.prototype.replaceRef = function(fromName, toName) {
  8796. var changes, fromKey, key, profile, value;
  8797. this.log.method('Options#replaceRef', this, arguments);
  8798. profile = OmegaPac.Profiles.byName(fromName, this._options);
  8799. if (!profile) {
  8800. return Promise.reject(new ProfileNotExistError(fromName));
  8801. }
  8802. changes = this._replaceRefChanges(fromName, toName);
  8803. for (key in changes) {
  8804. if (!hasProp.call(changes, key)) continue;
  8805. value = changes[key];
  8806. this._options[key] = value;
  8807. }
  8808. fromKey = OmegaPac.Profiles.nameAsKey(fromName);
  8809. if (this._watchingProfiles[fromKey]) {
  8810. if (this._currentProfileName === fromName) {
  8811. this._currentProfileName = toName;
  8812. }
  8813. this.applyProfile(this._currentProfileName);
  8814. }
  8815. return this._setOptions(changes);
  8816. };
  8817. /**
  8818. * Rename a profile and update references and options
  8819. * @param {String} fromName The original profile name
  8820. * @param {String} toname The target profile name
  8821. * @returns {Promise<OmegaOptions>} The updated options
  8822. */
  8823. Options.prototype.renameProfile = function(fromName, toName) {
  8824. var changes, fromKey, key, profile, value;
  8825. this.log.method('Options#renameProfile', this, arguments);
  8826. if (OmegaPac.Profiles.byName(toName, this._options)) {
  8827. return Promise.reject(new Error("Target name " + name + " already taken!"));
  8828. }
  8829. profile = OmegaPac.Profiles.byName(fromName, this._options);
  8830. if (!profile) {
  8831. return Promise.reject(new ProfileNotExistError(fromName));
  8832. }
  8833. profile.name = toName;
  8834. changes = {};
  8835. changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
  8836. this._replaceRefChanges(fromName, toName, changes);
  8837. for (key in changes) {
  8838. if (!hasProp.call(changes, key)) continue;
  8839. value = changes[key];
  8840. this._options[key] = value;
  8841. }
  8842. fromKey = OmegaPac.Profiles.nameAsKey(fromName);
  8843. changes[fromKey] = void 0;
  8844. delete this._options[fromKey];
  8845. if (this._watchingProfiles[fromKey]) {
  8846. if (this._currentProfileName === fromName) {
  8847. this._currentProfileName = toName;
  8848. }
  8849. this.applyProfile(this._currentProfileName);
  8850. }
  8851. return this._setOptions(changes);
  8852. };
  8853. /**
  8854. * Add a temp rule.
  8855. * @param {String} domain The domain for the temp rule.
  8856. * @param {String} profileName The profile to apply for the domain.
  8857. * @returns {Promise} A promise which is fulfilled when the rule is applied.
  8858. */
  8859. Options.prototype.addTempRule = function(domain, profileName) {
  8860. var changed, currentProfile, key, list, profile, rule, rulesByProfile;
  8861. this.log.method('Options#addTempRule', this, arguments);
  8862. if (!this._currentProfileName) {
  8863. return Promise.resolve();
  8864. }
  8865. profile = OmegaPac.Profiles.byName(profileName, this._options);
  8866. if (!profile) {
  8867. return Promise.reject(new ProfileNotExistError(profileName));
  8868. }
  8869. if (this._tempProfile == null) {
  8870. this._tempProfile = OmegaPac.Profiles.create('', 'SwitchProfile');
  8871. currentProfile = this.currentProfile();
  8872. this._tempProfile.color = currentProfile.color;
  8873. this._tempProfile.defaultProfileName = currentProfile.name;
  8874. }
  8875. changed = false;
  8876. rule = this._tempProfileRules[domain];
  8877. if (rule && rule.profileName) {
  8878. if (rule.profileName !== profileName) {
  8879. key = OmegaPac.Profiles.nameAsKey(rule.profileName);
  8880. list = this._tempProfileRulesByProfile[key];
  8881. list.splice(list.indexOf(rule), 1);
  8882. rule.profileName = profileName;
  8883. changed = true;
  8884. }
  8885. } else {
  8886. rule = {
  8887. condition: {
  8888. conditionType: 'HostWildcardCondition',
  8889. pattern: '*.' + domain
  8890. },
  8891. profileName: profileName,
  8892. isTempRule: true
  8893. };
  8894. this._tempProfile.rules.push(rule);
  8895. this._tempProfileRules[domain] = rule;
  8896. changed = true;
  8897. }
  8898. key = OmegaPac.Profiles.nameAsKey(profileName);
  8899. rulesByProfile = this._tempProfileRulesByProfile[key];
  8900. if (rulesByProfile == null) {
  8901. rulesByProfile = this._tempProfileRulesByProfile[key] = [];
  8902. }
  8903. rulesByProfile.push(rule);
  8904. if (changed) {
  8905. OmegaPac.Profiles.updateRevision(this._tempProfile);
  8906. return this.applyProfile(this._currentProfileName);
  8907. } else {
  8908. return Promise.resolve();
  8909. }
  8910. };
  8911. /**
  8912. * Find a temp rule by domain.
  8913. * @param {String} domain The domain of the temp rule.
  8914. * @returns {Promise<?String>} The profile name for the domain, or null if such
  8915. * rule does not exist.
  8916. */
  8917. Options.prototype.queryTempRule = function(domain) {
  8918. var rule;
  8919. rule = this._tempProfileRules[domain];
  8920. if (rule) {
  8921. if (rule.profileName) {
  8922. return rule.profileName;
  8923. } else {
  8924. delete this._tempProfileRules[domain];
  8925. }
  8926. }
  8927. return null;
  8928. };
  8929. /**
  8930. * Add a condition to the current active switch profile.
  8931. * @param {Object.<String,{}>} cond The condition to add
  8932. * @param {string>} profileName The name of the result profile of the rule.
  8933. * @returns {Promise} A promise which is fulfilled when the condition is saved.
  8934. */
  8935. Options.prototype.addCondition = function(condition, profileName) {
  8936. var changes, cond, i, j, l, len, profile, ref, tag, target;
  8937. this.log.method('Options#addCondition', this, arguments);
  8938. if (!this._currentProfileName) {
  8939. return Promise.resolve();
  8940. }
  8941. profile = OmegaPac.Profiles.byName(this._currentProfileName, this._options);
  8942. if ((profile != null ? profile.rules : void 0) == null) {
  8943. return Promise.reject(new Error("Cannot add condition to Profile " + this.profile.name + " (" + profile.type + ")"));
  8944. }
  8945. target = OmegaPac.Profiles.byName(profileName, this._options);
  8946. if (target == null) {
  8947. return Promise.reject(new ProfileNotExistError(profileName));
  8948. }
  8949. if (!Array.isArray(condition)) {
  8950. condition = [condition];
  8951. }
  8952. for (j = 0, len = condition.length; j < len; j++) {
  8953. cond = condition[j];
  8954. tag = OmegaPac.Conditions.tag(cond);
  8955. for (i = l = 0, ref = profile.rules.length; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
  8956. if (OmegaPac.Conditions.tag(profile.rules[i].condition) === tag) {
  8957. profile.rules.splice(i, 1);
  8958. break;
  8959. }
  8960. }
  8961. if (this._options['-addConditionsToBottom']) {
  8962. profile.rules.push({
  8963. condition: cond,
  8964. profileName: profileName
  8965. });
  8966. } else {
  8967. profile.rules.unshift({
  8968. condition: cond,
  8969. profileName: profileName
  8970. });
  8971. }
  8972. }
  8973. OmegaPac.Profiles.updateRevision(profile);
  8974. changes = {};
  8975. changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
  8976. return this._setOptions(changes);
  8977. };
  8978. /**
  8979. * Set the defaultProfileName of the profile.
  8980. * @param {string>} profileName The name of the profile to modify.
  8981. * @param {string>} defaultProfileName The defaultProfileName to set.
  8982. * @returns {Promise} A promise which is fulfilled when the profile is saved.
  8983. */
  8984. Options.prototype.setDefaultProfile = function(profileName, defaultProfileName) {
  8985. var changes, profile, target;
  8986. this.log.method('Options#setDefaultProfile', this, arguments);
  8987. profile = OmegaPac.Profiles.byName(profileName, this._options);
  8988. if (profile == null) {
  8989. return Promise.reject(new ProfileNotExistError(profileName));
  8990. } else if (profile.defaultProfileName == null) {
  8991. return Promise.reject(new Error(("Profile " + this.profile.name + " ") + "(@{profile.type}) does not have defaultProfileName!"));
  8992. }
  8993. target = OmegaPac.Profiles.byName(defaultProfileName, this._options);
  8994. if (target == null) {
  8995. return Promise.reject(new ProfileNotExistError(defaultProfileName));
  8996. }
  8997. profile.defaultProfileName = defaultProfileName;
  8998. OmegaPac.Profiles.updateRevision(profile);
  8999. changes = {};
  9000. changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
  9001. return this._setOptions(changes);
  9002. };
  9003. /**
  9004. * Add a profile to the options
  9005. * @param {{}} profile The profile to create
  9006. * @returns {Promise<{}>} The saved profile
  9007. */
  9008. Options.prototype.addProfile = function(profile) {
  9009. var changes;
  9010. this.log.method('Options#addProfile', this, arguments);
  9011. if (OmegaPac.Profiles.byName(profile.name, this._options)) {
  9012. return Promise.reject(new Error("Target name " + profile.name + " already taken!"));
  9013. } else {
  9014. changes = {};
  9015. changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
  9016. return this._setOptions(changes);
  9017. }
  9018. };
  9019. /**
  9020. * Get the matching results of a request
  9021. * @param {{}} request The request to test
  9022. * @returns {Promise<{profile: {}, results: {}[]}>} The last matched profile
  9023. * and the matching details
  9024. */
  9025. Options.prototype.matchProfile = function(request) {
  9026. var lastProfile, next, profile, result, results;
  9027. if (!this._currentProfileName) {
  9028. return Promise.resolve({
  9029. profile: this._externalProfile,
  9030. results: []
  9031. });
  9032. }
  9033. results = [];
  9034. profile = this._tempProfileActive ? this._tempProfile : OmegaPac.Profiles.byName(this._currentProfileName, this._options);
  9035. while (profile) {
  9036. lastProfile = profile;
  9037. result = OmegaPac.Profiles.match(profile, request);
  9038. if (result == null) {
  9039. break;
  9040. }
  9041. results.push(result);
  9042. if (Array.isArray(result)) {
  9043. next = result[0];
  9044. } else if (result.profileName) {
  9045. next = OmegaPac.Profiles.nameAsKey(result.profileName);
  9046. } else {
  9047. break;
  9048. }
  9049. profile = OmegaPac.Profiles.byKey(next, this._options);
  9050. }
  9051. return Promise.resolve({
  9052. profile: lastProfile,
  9053. results: results
  9054. });
  9055. };
  9056. /**
  9057. * Notify Options that the proxy settings are set externally.
  9058. * @param {{}} profile The external profile
  9059. * @param {?{}} args Extra arguments
  9060. * @param {boolean=false} args.noRevert If true, do not revert changes.
  9061. * @param {boolean=false} args.internal If true, treat the profile change as
  9062. * caused by the options itself instead of external reasons.
  9063. * @returns {Promise} A promise which is fulfilled when the profile is set
  9064. */
  9065. Options.prototype.setExternalProfile = function(profile, args) {
  9066. var p;
  9067. if (this._options['-revertProxyChanges'] && !this._isSystem) {
  9068. if (profile.name !== this._currentProfileName && this._currentProfileName) {
  9069. if (!(args != null ? args.noRevert : void 0)) {
  9070. this.applyProfile(this._revertToProfileName);
  9071. this._revertToProfileName = null;
  9072. return;
  9073. } else {
  9074. if (this._revertToProfileName == null) {
  9075. this._revertToProfileName = this._currentProfileName;
  9076. }
  9077. }
  9078. }
  9079. }
  9080. p = OmegaPac.Profiles.byName(profile.name, this._options);
  9081. if (p) {
  9082. if (args != null ? args.internal : void 0) {
  9083. return this.applyProfile(p.name, {
  9084. proxy: false
  9085. });
  9086. } else {
  9087. return this.applyProfile(p.name, {
  9088. proxy: false,
  9089. system: this._isSystem,
  9090. reason: 'external'
  9091. });
  9092. }
  9093. } else {
  9094. this._currentProfileName = null;
  9095. this._externalProfile = profile;
  9096. if (profile.color == null) {
  9097. profile.color = '#49afcd';
  9098. }
  9099. this._state.set({
  9100. 'currentProfileName': '',
  9101. 'externalProfile': profile,
  9102. 'validResultProfiles': [],
  9103. 'currentProfileCanAddRule': false
  9104. });
  9105. this.currentProfileChanged('external');
  9106. }
  9107. };
  9108. /**
  9109. * Switch options syncing on and off.
  9110. * @param {boolean} enabled Whether to enable syncing
  9111. * @param {?{}} args Extra arguments
  9112. * @param {boolean=false} args.force If true, overwrite options when conflict
  9113. * @returns {Promise} A promise which is fulfilled when the syncing is switched
  9114. */
  9115. Options.prototype.setOptionsSync = function(enabled, args) {
  9116. this.log.method('Options#setOptionsSync', this, arguments);
  9117. if (this.sync == null) {
  9118. return Promise.reject(new Error('Options syncing is unsupported.'));
  9119. }
  9120. return this._state.get({
  9121. 'syncOptions': ''
  9122. }).then((function(_this) {
  9123. return function(arg) {
  9124. var syncOptions;
  9125. syncOptions = arg.syncOptions;
  9126. if (!enabled) {
  9127. if (syncOptions === 'sync') {
  9128. _this._state.set({
  9129. 'syncOptions': 'conflict'
  9130. });
  9131. }
  9132. _this.sync.enabled = false;
  9133. if (typeof _this._syncWatchStop === "function") {
  9134. _this._syncWatchStop();
  9135. }
  9136. _this._syncWatchStop = null;
  9137. return;
  9138. }
  9139. if (syncOptions === 'conflict') {
  9140. if (!(args != null ? args.force : void 0)) {
  9141. return Promise.reject(new Error('Syncing not enabled due to conflict. Retry with force to overwrite local options and enable syncing.'));
  9142. }
  9143. }
  9144. if (syncOptions === 'sync') {
  9145. return;
  9146. }
  9147. return _this._state.set({
  9148. 'syncOptions': 'sync'
  9149. }).then(function() {
  9150. if (syncOptions === 'conflict') {
  9151. _this.sync.enabled = false;
  9152. return _this._storage.remove().then(function() {
  9153. _this.sync.enabled = true;
  9154. return _this.init();
  9155. });
  9156. } else {
  9157. _this.sync.enabled = true;
  9158. if (typeof _this._syncWatchStop === "function") {
  9159. _this._syncWatchStop();
  9160. }
  9161. _this.sync.requestPush(_this._options);
  9162. _this._syncWatchStop = _this.sync.watchAndPull(_this._storage);
  9163. }
  9164. });
  9165. };
  9166. })(this));
  9167. };
  9168. /**
  9169. * Clear the sync storage, resetting syncing state to pristine.
  9170. * @returns {Promise} A promise which is fulfilled when the syncing is reset.
  9171. */
  9172. Options.prototype.resetOptionsSync = function() {
  9173. this.log.method('Options#resetOptionsSync', this, arguments);
  9174. if (this.sync == null) {
  9175. return Promise.reject(new Error('Options syncing is unsupported.'));
  9176. }
  9177. this.sync.enabled = false;
  9178. if (typeof this._syncWatchStop === "function") {
  9179. this._syncWatchStop();
  9180. }
  9181. this._syncWatchStop = null;
  9182. this._state.set({
  9183. 'syncOptions': 'conflict'
  9184. });
  9185. return this.sync.storage.remove().then((function(_this) {
  9186. return function() {
  9187. return _this._state.set({
  9188. 'syncOptions': 'pristine'
  9189. });
  9190. };
  9191. })(this));
  9192. };
  9193. return Options;
  9194. })();
  9195. module.exports = Options;
  9196. },{"./default_options":29,"./log":31,"./storage":34,"bluebird":2,"buffer":3,"jsondiffpatch":19,"omega-pac":27}],33:[function(require,module,exports){
  9197. /* @module omega-target/options_sync */
  9198. var Log, OptionsSync, Promise, Revision, Storage, TokenBucket, jsondiffpatch,
  9199. hasProp = {}.hasOwnProperty;
  9200. Promise = require('bluebird');
  9201. Storage = require('./storage');
  9202. Log = require('./log');
  9203. Revision = require('omega-pac').Revision;
  9204. jsondiffpatch = require('jsondiffpatch');
  9205. TokenBucket = require('limiter').TokenBucket;
  9206. OptionsSync = (function() {
  9207. OptionsSync.TokenBucket = TokenBucket;
  9208. OptionsSync.prototype._timeout = null;
  9209. OptionsSync.prototype._bucket = null;
  9210. OptionsSync.prototype._waiting = false;
  9211. /**
  9212. * The debounce timeout (ms) for requestPush scheduling. See requestPush.
  9213. * @type number
  9214. */
  9215. OptionsSync.prototype.debounce = 1000;
  9216. /**
  9217. * The throttling timeout (ms) for watchAndPull. See watchAndPull.
  9218. * @type number
  9219. */
  9220. OptionsSync.prototype.pullThrottle = 1000;
  9221. /**
  9222. * The remote storage of syncing.
  9223. * @type Storage
  9224. */
  9225. OptionsSync.prototype.storage = null;
  9226. function OptionsSync(storage, _bucket) {
  9227. var base1;
  9228. this.storage = storage;
  9229. this._bucket = _bucket;
  9230. this._pending = {};
  9231. if (this._bucket == null) {
  9232. this._bucket = new TokenBucket(10, 10, 'minute', null);
  9233. }
  9234. if ((base1 = this._bucket).clear == null) {
  9235. base1.clear = (function(_this) {
  9236. return function() {
  9237. return _this._bucket.tryRemoveTokens(_this._bucket.content);
  9238. };
  9239. })(this);
  9240. }
  9241. }
  9242. /**
  9243. * Transform storage values for syncing. The default implementation applies no
  9244. * transformation, but the behavior can be altered by assigning to this field.
  9245. * Note: Transformation is applied before merging.
  9246. * @param {{}} value The value to transform
  9247. * @param {{}} key The key of the item
  9248. * @returns {{}} The transformed value
  9249. */
  9250. OptionsSync.prototype.transformValue = function(v) {
  9251. return v;
  9252. };
  9253. /**
  9254. * Merge newVal and oldVal of a given key. The default implementation choose
  9255. * between newVal and oldVal based on the following rules:
  9256. * 1. Choose oldVal if syncOptions is 'disabled' in either oldVal or newVal.
  9257. * 2. Choose oldVal if it has a revision newer than or equal to that of newVal.
  9258. * 3. Choose oldVal if it deeply equals newVal.
  9259. * 4. Otherwise, choose newVal.
  9260. *
  9261. * @param {string} key The key of the item
  9262. * @param {} newVal The new value
  9263. * @param {} oldVal The old value
  9264. * @returns {} The merged result
  9265. */
  9266. OptionsSync.prototype.merge = (function() {
  9267. var diff;
  9268. diff = jsondiffpatch.create({
  9269. objectHash: function(obj) {
  9270. return JSON.stringify(obj);
  9271. },
  9272. textDiff: {
  9273. minLength: 1 / 0
  9274. }
  9275. });
  9276. return function(key, newVal, oldVal) {
  9277. var result;
  9278. if (newVal === oldVal) {
  9279. return oldVal;
  9280. }
  9281. if ((oldVal != null ? oldVal.syncOptions : void 0) === 'disabled' || (newVal != null ? newVal.syncOptions : void 0) === 'disabled') {
  9282. return oldVal;
  9283. }
  9284. if (((oldVal != null ? oldVal.revision : void 0) != null) && ((newVal != null ? newVal.revision : void 0) != null)) {
  9285. result = Revision.compare(oldVal.revision, newVal.revision);
  9286. if (result >= 0) {
  9287. return oldVal;
  9288. }
  9289. }
  9290. if (diff.diff(oldVal, newVal) == null) {
  9291. return oldVal;
  9292. }
  9293. return newVal;
  9294. };
  9295. })();
  9296. /**
  9297. * Whether syncing is enabled or not. See requestPush for the effect.
  9298. * @type boolean
  9299. */
  9300. OptionsSync.prototype.enabled = true;
  9301. /**
  9302. * Request pushing the changes to remote storage. The changes are cached first,
  9303. * and then the actual write operations are scheduled if enabled is true.
  9304. * The actual operation is delayed and debounced, combining continuous writes
  9305. * in a short period into a single write operation.
  9306. * @param {Object.<string, {}>} changes A map from keys to values.
  9307. */
  9308. OptionsSync.prototype.requestPush = function(changes) {
  9309. var key, value;
  9310. if (this._timeout != null) {
  9311. clearTimeout(this._timeout);
  9312. }
  9313. for (key in changes) {
  9314. if (!hasProp.call(changes, key)) continue;
  9315. value = changes[key];
  9316. if (typeof value !== 'undefined') {
  9317. value = this.transformValue(value, key);
  9318. if (typeof value === 'undefined') {
  9319. continue;
  9320. }
  9321. }
  9322. this._pending[key] = value;
  9323. }
  9324. if (!this.enabled) {
  9325. return;
  9326. }
  9327. return this._timeout = setTimeout(this._doPush.bind(this), this.debounce);
  9328. };
  9329. /**
  9330. * Returning the pending changes not written to the remote storage.
  9331. * @returns {Object.<string, {}>} The pending changes.
  9332. */
  9333. OptionsSync.prototype.pendingChanges = function() {
  9334. return this._pending;
  9335. };
  9336. OptionsSync.prototype._doPush = function() {
  9337. this._timeout = null;
  9338. if (this._waiting) {
  9339. return;
  9340. }
  9341. this._waiting = true;
  9342. return this._bucket.removeTokens(1, (function(_this) {
  9343. return function() {
  9344. return _this.storage.get(null).then(function(base) {
  9345. var changes;
  9346. changes = _this._pending;
  9347. _this._pending = {};
  9348. _this._waiting = false;
  9349. return Storage.operationsForChanges(changes, {
  9350. base: base,
  9351. merge: _this.merge
  9352. });
  9353. }).then(function(arg) {
  9354. var doSet, remove, set;
  9355. set = arg.set, remove = arg.remove;
  9356. doSet = Object.keys(set).length === 0 ? Promise.resolve(0) : (Log.log('OptionsSync::set', set), _this.storage.set(set)["return"](1));
  9357. return doSet.then(function(cost) {
  9358. set = {};
  9359. if (remove.length > 0) {
  9360. if (_this._bucket.tryRemoveTokens(cost)) {
  9361. Log.log('OptionsSync::remove', remove);
  9362. return _this.storage.remove(remove);
  9363. } else {
  9364. return Promise.reject('bucket');
  9365. }
  9366. }
  9367. })["catch"](function(e) {
  9368. var i, key, len, value, valuesAffected;
  9369. for (key in set) {
  9370. if (!hasProp.call(set, key)) continue;
  9371. value = set[key];
  9372. if (!(key in _this._pending)) {
  9373. _this._pending[key] = value;
  9374. }
  9375. }
  9376. for (i = 0, len = remove.length; i < len; i++) {
  9377. key = remove[i];
  9378. if (!(key in _this._pending)) {
  9379. _this._pending[key] = void 0;
  9380. }
  9381. }
  9382. if (e === 'bucket') {
  9383. return _this._doPush();
  9384. } else if (e instanceof Storage.RateLimitExceededError) {
  9385. Log.log('OptionsSync::rateLimitExceeded');
  9386. _this._bucket.clear();
  9387. _this.requestPush({});
  9388. } else if (e instanceof Storage.QuotaExceededError) {
  9389. valuesAffected = 0;
  9390. for (key in set) {
  9391. if (!hasProp.call(set, key)) continue;
  9392. value = set[key];
  9393. if (key[0] === '+' && value.syncOptions !== 'disabled') {
  9394. value.syncOptions = 'disabled';
  9395. value.syncError = {
  9396. reason: 'quotaPerItem'
  9397. };
  9398. valuesAffected++;
  9399. }
  9400. }
  9401. if (valuesAffected > 0) {
  9402. _this.requestPush({});
  9403. } else {
  9404. _this._pending = {};
  9405. }
  9406. } else {
  9407. return Promise.reject(e);
  9408. }
  9409. });
  9410. });
  9411. };
  9412. })(this));
  9413. };
  9414. OptionsSync.prototype._logOperations = function(text, operations) {
  9415. if (Object.keys(operations.set).length) {
  9416. Log.log(text + '::set', operations.set);
  9417. }
  9418. if (operations.remove.length) {
  9419. return Log.log(text + '::remove', operations.remove);
  9420. }
  9421. };
  9422. /**
  9423. * Pull the remote storage for changes, and write them to local.
  9424. * @param {Storage} local The local storage to be written to
  9425. * @returns {function} Calling the returned function will stop watching.
  9426. */
  9427. OptionsSync.prototype.copyTo = function(local) {
  9428. return Promise.join(local.get(null), this.storage.get(null), (function(_this) {
  9429. return function(base, changes) {
  9430. var key, ref;
  9431. for (key in base) {
  9432. if (!hasProp.call(base, key)) continue;
  9433. if (!(key in changes)) {
  9434. if (key[0] === '+' && !((ref = base[key]) != null ? ref.syncOptions : void 0) === 'disabled') {
  9435. changes[key] = void 0;
  9436. }
  9437. }
  9438. }
  9439. return local.apply({
  9440. changes: changes,
  9441. base: base,
  9442. merge: _this.merge
  9443. }).then(function(operations) {
  9444. return _this._logOperations('OptionsSync::copyTo', operations);
  9445. });
  9446. };
  9447. })(this));
  9448. };
  9449. /**
  9450. * Watch the remote storage for changes, and write them to local.
  9451. * The actual writing is throttled by pullThrottle with initial delay.
  9452. * @param {Storage} local The local storage to be written to
  9453. * @returns {function} Calling the returned function will stop watching.
  9454. */
  9455. OptionsSync.prototype.watchAndPull = function(local) {
  9456. var doPull, pull, pullScheduled;
  9457. pullScheduled = null;
  9458. pull = {};
  9459. doPull = (function(_this) {
  9460. return function() {
  9461. return local.get(null).then(function(base) {
  9462. var changes;
  9463. changes = pull;
  9464. pull = {};
  9465. pullScheduled = null;
  9466. return Storage.operationsForChanges(changes, {
  9467. base: base,
  9468. merge: _this.merge
  9469. });
  9470. }).then(function(operations) {
  9471. _this._logOperations('OptionsSync::pull', operations);
  9472. return local.apply(operations);
  9473. });
  9474. };
  9475. })(this);
  9476. return this.storage.watch(null, (function(_this) {
  9477. return function(changes) {
  9478. var key, value;
  9479. for (key in changes) {
  9480. if (!hasProp.call(changes, key)) continue;
  9481. value = changes[key];
  9482. pull[key] = value;
  9483. }
  9484. if (pullScheduled != null) {
  9485. return;
  9486. }
  9487. return pullScheduled = setTimeout(doPull, _this.pullThrottle);
  9488. };
  9489. })(this));
  9490. };
  9491. return OptionsSync;
  9492. })();
  9493. module.exports = OptionsSync;
  9494. },{"./log":31,"./storage":34,"bluebird":2,"jsondiffpatch":19,"limiter":22,"omega-pac":27}],34:[function(require,module,exports){
  9495. /* @module omega-target/storage */
  9496. var Log, Promise, Storage,
  9497. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  9498. hasProp = {}.hasOwnProperty;
  9499. Promise = require('bluebird');
  9500. Log = require('./log');
  9501. Storage = (function() {
  9502. var QuotaExceededError, RateLimitExceededError, StorageUnavailableError;
  9503. function Storage() {}
  9504. /**
  9505. * Any operation that fails due to rate limiting should reject with an instance
  9506. * of RateLimitExceededError, when implemented in derived classes of Storage.
  9507. */
  9508. Storage.RateLimitExceededError = RateLimitExceededError = (function(superClass) {
  9509. extend(RateLimitExceededError, superClass);
  9510. function RateLimitExceededError() {
  9511. RateLimitExceededError.__super__.constructor.apply(this, arguments);
  9512. }
  9513. return RateLimitExceededError;
  9514. })(Error);
  9515. /**
  9516. * Any operation that fails due to storage quota should reject with an instance
  9517. * of QuotaExceededError, when implemented in derived classes of Storage.
  9518. */
  9519. Storage.QuotaExceededError = QuotaExceededError = (function(superClass) {
  9520. extend(QuotaExceededError, superClass);
  9521. function QuotaExceededError() {
  9522. QuotaExceededError.__super__.constructor.apply(this, arguments);
  9523. }
  9524. return QuotaExceededError;
  9525. })(Error);
  9526. /**
  9527. * If this storage is not available for some reason, all operations should
  9528. * reject with an instance of StorageUnavailableError, when implemented in
  9529. * derived classes of Storage.
  9530. * This error is considered fatal and unrecoverable in the current environment.
  9531. * Further access to this storage should be avoided until restart.
  9532. */
  9533. Storage.StorageUnavailableError = StorageUnavailableError = (function(superClass) {
  9534. extend(StorageUnavailableError, superClass);
  9535. function StorageUnavailableError() {
  9536. StorageUnavailableError.__super__.constructor.apply(this, arguments);
  9537. }
  9538. return StorageUnavailableError;
  9539. })(Error);
  9540. /**
  9541. * A set of operations to be performed on a Storage.
  9542. * @typedef WriteOperations
  9543. * @type {object}
  9544. * @property {Object.<string, {}>} set - A map from keys to new values of the
  9545. * items to set
  9546. * @property {{}[]} remove - An array of keys to remove
  9547. */
  9548. /**
  9549. * Calculate the actual operations against storage that should be performed to
  9550. * replay the changes on a storage.
  9551. * @param {Object.<string, {}>} changes The changes to apply
  9552. * @param {?{}} args Extra arguments
  9553. * @param {Object.<string, {}>?} args.base The original items in the storage.
  9554. * @param {function(key, newVal, oldVal)} args.merge A function that merges
  9555. * the newVal and oldVal. oldVal is provided only if args.base is present.
  9556. * Otherwise it will be equal to newVal (i.e. merge(key, newVal, newVal)).
  9557. * @returns {WriteOperations} The operations that should be performed.
  9558. */
  9559. Storage.operationsForChanges = function(changes, arg) {
  9560. var base, key, merge, newVal, oldVal, ref, remove, set;
  9561. ref = arg != null ? arg : {}, base = ref.base, merge = ref.merge;
  9562. set = {};
  9563. remove = [];
  9564. for (key in changes) {
  9565. newVal = changes[key];
  9566. oldVal = base != null ? base[key] : newVal;
  9567. if (merge) {
  9568. newVal = merge(key, newVal, oldVal);
  9569. }
  9570. if ((base != null) && newVal === oldVal) {
  9571. continue;
  9572. }
  9573. if (typeof newVal === 'undefined') {
  9574. if (typeof oldVal !== 'undefined' || (base == null)) {
  9575. remove.push(key);
  9576. }
  9577. } else {
  9578. set[key] = newVal;
  9579. }
  9580. }
  9581. return {
  9582. set: set,
  9583. remove: remove
  9584. };
  9585. };
  9586. /**
  9587. * Get the requested values by keys from the storage.
  9588. * @param {(string|string[]|null|Object.<string,{}>)} keys The keys to retrive,
  9589. * or null for all.
  9590. * @returns {Promise<(Object.<string, {}>)>} A map from keys to values
  9591. */
  9592. Storage.prototype.get = function(keys) {
  9593. var i, key, len, map, ref, value;
  9594. Log.method('Storage#get', this, arguments);
  9595. if (!this._items) {
  9596. return Promise.resolve({});
  9597. }
  9598. if (keys == null) {
  9599. keys = this._items;
  9600. }
  9601. map = {};
  9602. if (typeof keys === 'string') {
  9603. map[keys] = this._items[keys];
  9604. } else if (Array.isArray(keys)) {
  9605. for (i = 0, len = keys.length; i < len; i++) {
  9606. key = keys[i];
  9607. map[key] = this._items[key];
  9608. }
  9609. } else if (typeof keys === 'object') {
  9610. for (key in keys) {
  9611. value = keys[key];
  9612. map[key] = (ref = this._items[key]) != null ? ref : value;
  9613. }
  9614. }
  9615. return Promise.resolve(map);
  9616. };
  9617. /**
  9618. * Set multiple values by keys in the storage.
  9619. * @param {(string|Object.<string,{}>)} items A map from key to value to set.
  9620. * @returns {Promise<(Object.<string, {}>)>} A map of key-value pairs just set.
  9621. */
  9622. Storage.prototype.set = function(items) {
  9623. var key, value;
  9624. Log.method('Storage#set', this, arguments);
  9625. if (this._items == null) {
  9626. this._items = {};
  9627. }
  9628. for (key in items) {
  9629. value = items[key];
  9630. this._items[key] = value;
  9631. }
  9632. return Promise.resolve(items);
  9633. };
  9634. /**
  9635. * Remove items by keys from the storage.
  9636. * @param {(string|string[]|null)} keys The keys to remove, or null for all.
  9637. * @returns {Promise} A promise that fulfills on successful removal.
  9638. */
  9639. Storage.prototype.remove = function(keys) {
  9640. var i, key, len;
  9641. Log.method('Storage#remove', this, arguments);
  9642. if (this._items != null) {
  9643. if (keys == null) {
  9644. this._items = {};
  9645. } else if (Array.isArray(keys)) {
  9646. for (i = 0, len = keys.length; i < len; i++) {
  9647. key = keys[i];
  9648. delete this._items[key];
  9649. }
  9650. } else {
  9651. delete this._items[keys];
  9652. }
  9653. }
  9654. return Promise.resolve();
  9655. };
  9656. /**
  9657. * @callback watchCallback
  9658. * @param {Object.<string, {}>} map A map of key-value pairs just changed.
  9659. */
  9660. /**
  9661. * Watch for any changes to the storage.
  9662. * @param {(string|string[]|null)} keys The keys to watch, or null for all.
  9663. * @param {watchCallback} callback Called everytime something changes.
  9664. * @returns {function} Calling the returned function will stop watching.
  9665. */
  9666. Storage.prototype.watch = function(keys, callback) {
  9667. Log.method('Storage#watch', this, arguments);
  9668. return (function() {
  9669. return null;
  9670. });
  9671. };
  9672. /**
  9673. * Apply WriteOperations to the storage.
  9674. * @param {WriteOperations|{changes: Object.<string,{}>}} operations The
  9675. * operations to apply, or the changes to be applied. If changes is provided,
  9676. * the operations are calculated by Storage.operationsForChanges, with extra
  9677. * fields passed through as the second argument.
  9678. * @returns {Promise} A promise that fulfills on operation success.
  9679. */
  9680. Storage.prototype.apply = function(operations) {
  9681. if ('changes' in operations) {
  9682. operations = Storage.operationsForChanges(operations.changes, operations);
  9683. }
  9684. return this.set(operations.set).then((function(_this) {
  9685. return function() {
  9686. return _this.remove(operations.remove);
  9687. };
  9688. })(this))["return"](operations);
  9689. };
  9690. return Storage;
  9691. })();
  9692. module.exports = Storage;
  9693. },{"./log":31,"bluebird":2}],35:[function(require,module,exports){
  9694. exports.Promise = require('bluebird');
  9695. },{"bluebird":2}],"OmegaTarget":[function(require,module,exports){
  9696. var name, ref, ref1, value;
  9697. module.exports = {
  9698. Log: require('./src/log'),
  9699. Storage: require('./src/storage'),
  9700. BrowserStorage: require('./src/browser_storage'),
  9701. Options: require('./src/options'),
  9702. OptionsSync: require('./src/options_sync'),
  9703. OmegaPac: require('omega-pac')
  9704. };
  9705. ref = require('./src/utils.coffee');
  9706. for (name in ref) {
  9707. value = ref[name];
  9708. module.exports[name] = value;
  9709. }
  9710. ref1 = require('./src/errors.coffee');
  9711. for (name in ref1) {
  9712. value = ref1[name];
  9713. module.exports[name] = value;
  9714. }
  9715. },{"./src/browser_storage":28,"./src/errors.coffee":30,"./src/log":31,"./src/options":32,"./src/options_sync":33,"./src/storage":34,"./src/utils.coffee":35,"omega-pac":27}]},{},["OmegaTarget"])("OmegaTarget")
  9716. });