| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066 |
- (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){
- var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- ;(function (exports) {
- 'use strict';
- var Arr = (typeof Uint8Array !== 'undefined')
- ? Uint8Array
- : Array
- var PLUS = '+'.charCodeAt(0)
- var SLASH = '/'.charCodeAt(0)
- var NUMBER = '0'.charCodeAt(0)
- var LOWER = 'a'.charCodeAt(0)
- var UPPER = 'A'.charCodeAt(0)
- var PLUS_URL_SAFE = '-'.charCodeAt(0)
- var SLASH_URL_SAFE = '_'.charCodeAt(0)
- function decode (elt) {
- var code = elt.charCodeAt(0)
- if (code === PLUS ||
- code === PLUS_URL_SAFE)
- return 62 // '+'
- if (code === SLASH ||
- code === SLASH_URL_SAFE)
- return 63 // '/'
- if (code < NUMBER)
- return -1 //no match
- if (code < NUMBER + 10)
- return code - NUMBER + 26 + 26
- if (code < UPPER + 26)
- return code - UPPER
- if (code < LOWER + 26)
- return code - LOWER + 26
- }
- function b64ToByteArray (b64) {
- var i, j, l, tmp, placeHolders, arr
- if (b64.length % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
- // the number of equal signs (place holders)
- // if there are two placeholders, than the two characters before it
- // represent one byte
- // if there is only one, then the three characters before it represent 2 bytes
- // this is just a cheap hack to not do indexOf twice
- var len = b64.length
- placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
- // base64 is 4/3 + up to two characters of the original data
- arr = new Arr(b64.length * 3 / 4 - placeHolders)
- // if there are placeholders, only get up to the last complete 4 chars
- l = placeHolders > 0 ? b64.length - 4 : b64.length
- var L = 0
- function push (v) {
- arr[L++] = v
- }
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
- tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
- push((tmp & 0xFF0000) >> 16)
- push((tmp & 0xFF00) >> 8)
- push(tmp & 0xFF)
- }
- if (placeHolders === 2) {
- tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
- push(tmp & 0xFF)
- } else if (placeHolders === 1) {
- tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
- push((tmp >> 8) & 0xFF)
- push(tmp & 0xFF)
- }
- return arr
- }
- function uint8ToBase64 (uint8) {
- var i,
- extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
- output = "",
- temp, length
- function encode (num) {
- return lookup.charAt(num)
- }
- function tripletToBase64 (num) {
- return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
- }
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
- temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
- output += tripletToBase64(temp)
- }
- // pad the end with zeros, but make sure to not forget the extra bytes
- switch (extraBytes) {
- case 1:
- temp = uint8[uint8.length - 1]
- output += encode(temp >> 2)
- output += encode((temp << 4) & 0x3F)
- output += '=='
- break
- case 2:
- temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
- output += encode(temp >> 10)
- output += encode((temp >> 4) & 0x3F)
- output += encode((temp << 2) & 0x3F)
- output += '='
- break
- }
- return output
- }
- exports.toByteArray = b64ToByteArray
- exports.fromByteArray = uint8ToBase64
- }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
- },{}],2:[function(require,module,exports){
- (function (process,global){
- /* @preserve
- * The MIT License (MIT)
- *
- * Copyright (c) 2013-2015 Petka Antonov
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- */
- /**
- * bluebird build version 2.11.0
- * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
- */
- !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){
- "use strict";
- module.exports = function(Promise) {
- var SomePromiseArray = Promise._SomePromiseArray;
- function any(promises) {
- var ret = new SomePromiseArray(promises);
- var promise = ret.promise();
- ret.setHowMany(1);
- ret.setUnwrap();
- ret.init();
- return promise;
- }
- Promise.any = function (promises) {
- return any(promises);
- };
- Promise.prototype.any = function () {
- return any(this);
- };
- };
- },{}],2:[function(_dereq_,module,exports){
- "use strict";
- var firstLineError;
- try {throw new Error(); } catch (e) {firstLineError = e;}
- var schedule = _dereq_("./schedule.js");
- var Queue = _dereq_("./queue.js");
- var util = _dereq_("./util.js");
- function Async() {
- this._isTickUsed = false;
- this._lateQueue = new Queue(16);
- this._normalQueue = new Queue(16);
- this._trampolineEnabled = true;
- var self = this;
- this.drainQueues = function () {
- self._drainQueues();
- };
- this._schedule =
- schedule.isStatic ? schedule(this.drainQueues) : schedule;
- }
- Async.prototype.disableTrampolineIfNecessary = function() {
- if (util.hasDevTools) {
- this._trampolineEnabled = false;
- }
- };
- Async.prototype.enableTrampoline = function() {
- if (!this._trampolineEnabled) {
- this._trampolineEnabled = true;
- this._schedule = function(fn) {
- setTimeout(fn, 0);
- };
- }
- };
- Async.prototype.haveItemsQueued = function () {
- return this._normalQueue.length() > 0;
- };
- Async.prototype.throwLater = function(fn, arg) {
- if (arguments.length === 1) {
- arg = fn;
- fn = function () { throw arg; };
- }
- if (typeof setTimeout !== "undefined") {
- setTimeout(function() {
- fn(arg);
- }, 0);
- } else try {
- this._schedule(function() {
- fn(arg);
- });
- } catch (e) {
- throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
- }
- };
- function AsyncInvokeLater(fn, receiver, arg) {
- this._lateQueue.push(fn, receiver, arg);
- this._queueTick();
- }
- function AsyncInvoke(fn, receiver, arg) {
- this._normalQueue.push(fn, receiver, arg);
- this._queueTick();
- }
- function AsyncSettlePromises(promise) {
- this._normalQueue._pushOne(promise);
- this._queueTick();
- }
- if (!util.hasDevTools) {
- Async.prototype.invokeLater = AsyncInvokeLater;
- Async.prototype.invoke = AsyncInvoke;
- Async.prototype.settlePromises = AsyncSettlePromises;
- } else {
- if (schedule.isStatic) {
- schedule = function(fn) { setTimeout(fn, 0); };
- }
- Async.prototype.invokeLater = function (fn, receiver, arg) {
- if (this._trampolineEnabled) {
- AsyncInvokeLater.call(this, fn, receiver, arg);
- } else {
- this._schedule(function() {
- setTimeout(function() {
- fn.call(receiver, arg);
- }, 100);
- });
- }
- };
- Async.prototype.invoke = function (fn, receiver, arg) {
- if (this._trampolineEnabled) {
- AsyncInvoke.call(this, fn, receiver, arg);
- } else {
- this._schedule(function() {
- fn.call(receiver, arg);
- });
- }
- };
- Async.prototype.settlePromises = function(promise) {
- if (this._trampolineEnabled) {
- AsyncSettlePromises.call(this, promise);
- } else {
- this._schedule(function() {
- promise._settlePromises();
- });
- }
- };
- }
- Async.prototype.invokeFirst = function (fn, receiver, arg) {
- this._normalQueue.unshift(fn, receiver, arg);
- this._queueTick();
- };
- Async.prototype._drainQueue = function(queue) {
- while (queue.length() > 0) {
- var fn = queue.shift();
- if (typeof fn !== "function") {
- fn._settlePromises();
- continue;
- }
- var receiver = queue.shift();
- var arg = queue.shift();
- fn.call(receiver, arg);
- }
- };
- Async.prototype._drainQueues = function () {
- this._drainQueue(this._normalQueue);
- this._reset();
- this._drainQueue(this._lateQueue);
- };
- Async.prototype._queueTick = function () {
- if (!this._isTickUsed) {
- this._isTickUsed = true;
- this._schedule(this.drainQueues);
- }
- };
- Async.prototype._reset = function () {
- this._isTickUsed = false;
- };
- module.exports = new Async();
- module.exports.firstLineError = firstLineError;
- },{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
- var rejectThis = function(_, e) {
- this._reject(e);
- };
- var targetRejected = function(e, context) {
- context.promiseRejectionQueued = true;
- context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
- };
- var bindingResolved = function(thisArg, context) {
- if (this._isPending()) {
- this._resolveCallback(context.target);
- }
- };
- var bindingRejected = function(e, context) {
- if (!context.promiseRejectionQueued) this._reject(e);
- };
- Promise.prototype.bind = function (thisArg) {
- var maybePromise = tryConvertToPromise(thisArg);
- var ret = new Promise(INTERNAL);
- ret._propagateFrom(this, 1);
- var target = this._target();
- ret._setBoundTo(maybePromise);
- if (maybePromise instanceof Promise) {
- var context = {
- promiseRejectionQueued: false,
- promise: ret,
- target: target,
- bindingPromise: maybePromise
- };
- target._then(INTERNAL, targetRejected, ret._progress, ret, context);
- maybePromise._then(
- bindingResolved, bindingRejected, ret._progress, ret, context);
- } else {
- ret._resolveCallback(target);
- }
- return ret;
- };
- Promise.prototype._setBoundTo = function (obj) {
- if (obj !== undefined) {
- this._bitField = this._bitField | 131072;
- this._boundTo = obj;
- } else {
- this._bitField = this._bitField & (~131072);
- }
- };
- Promise.prototype._isBound = function () {
- return (this._bitField & 131072) === 131072;
- };
- Promise.bind = function (thisArg, value) {
- var maybePromise = tryConvertToPromise(thisArg);
- var ret = new Promise(INTERNAL);
- ret._setBoundTo(maybePromise);
- if (maybePromise instanceof Promise) {
- maybePromise._then(function() {
- ret._resolveCallback(value);
- }, ret._reject, ret._progress, ret, null);
- } else {
- ret._resolveCallback(value);
- }
- return ret;
- };
- };
- },{}],4:[function(_dereq_,module,exports){
- "use strict";
- var old;
- if (typeof Promise !== "undefined") old = Promise;
- function noConflict() {
- try { if (Promise === bluebird) Promise = old; }
- catch (e) {}
- return bluebird;
- }
- var bluebird = _dereq_("./promise.js")();
- bluebird.noConflict = noConflict;
- module.exports = bluebird;
- },{"./promise.js":23}],5:[function(_dereq_,module,exports){
- "use strict";
- var cr = Object.create;
- if (cr) {
- var callerCache = cr(null);
- var getterCache = cr(null);
- callerCache[" size"] = getterCache[" size"] = 0;
- }
- module.exports = function(Promise) {
- var util = _dereq_("./util.js");
- var canEvaluate = util.canEvaluate;
- var isIdentifier = util.isIdentifier;
- var getMethodCaller;
- var getGetter;
- if (!true) {
- var makeMethodCaller = function (methodName) {
- return new Function("ensureMethod", " \n\
- return function(obj) { \n\
- 'use strict' \n\
- var len = this.length; \n\
- ensureMethod(obj, 'methodName'); \n\
- switch(len) { \n\
- case 1: return obj.methodName(this[0]); \n\
- case 2: return obj.methodName(this[0], this[1]); \n\
- case 3: return obj.methodName(this[0], this[1], this[2]); \n\
- case 0: return obj.methodName(); \n\
- default: \n\
- return obj.methodName.apply(obj, this); \n\
- } \n\
- }; \n\
- ".replace(/methodName/g, methodName))(ensureMethod);
- };
- var makeGetter = function (propertyName) {
- return new Function("obj", " \n\
- 'use strict'; \n\
- return obj.propertyName; \n\
- ".replace("propertyName", propertyName));
- };
- var getCompiled = function(name, compiler, cache) {
- var ret = cache[name];
- if (typeof ret !== "function") {
- if (!isIdentifier(name)) {
- return null;
- }
- ret = compiler(name);
- cache[name] = ret;
- cache[" size"]++;
- if (cache[" size"] > 512) {
- var keys = Object.keys(cache);
- for (var i = 0; i < 256; ++i) delete cache[keys[i]];
- cache[" size"] = keys.length - 256;
- }
- }
- return ret;
- };
- getMethodCaller = function(name) {
- return getCompiled(name, makeMethodCaller, callerCache);
- };
- getGetter = function(name) {
- return getCompiled(name, makeGetter, getterCache);
- };
- }
- function ensureMethod(obj, methodName) {
- var fn;
- if (obj != null) fn = obj[methodName];
- if (typeof fn !== "function") {
- var message = "Object " + util.classString(obj) + " has no method '" +
- util.toString(methodName) + "'";
- throw new Promise.TypeError(message);
- }
- return fn;
- }
- function caller(obj) {
- var methodName = this.pop();
- var fn = ensureMethod(obj, methodName);
- return fn.apply(obj, this);
- }
- Promise.prototype.call = function (methodName) {
- var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
- if (!true) {
- if (canEvaluate) {
- var maybeCaller = getMethodCaller(methodName);
- if (maybeCaller !== null) {
- return this._then(
- maybeCaller, undefined, undefined, args, undefined);
- }
- }
- }
- args.push(methodName);
- return this._then(caller, undefined, undefined, args, undefined);
- };
- function namedGetter(obj) {
- return obj[this];
- }
- function indexedGetter(obj) {
- var index = +this;
- if (index < 0) index = Math.max(0, index + obj.length);
- return obj[index];
- }
- Promise.prototype.get = function (propertyName) {
- var isIndex = (typeof propertyName === "number");
- var getter;
- if (!isIndex) {
- if (canEvaluate) {
- var maybeGetter = getGetter(propertyName);
- getter = maybeGetter !== null ? maybeGetter : namedGetter;
- } else {
- getter = namedGetter;
- }
- } else {
- getter = indexedGetter;
- }
- return this._then(getter, undefined, undefined, propertyName, undefined);
- };
- };
- },{"./util.js":38}],6:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var errors = _dereq_("./errors.js");
- var async = _dereq_("./async.js");
- var CancellationError = errors.CancellationError;
- Promise.prototype._cancel = function (reason) {
- if (!this.isCancellable()) return this;
- var parent;
- var promiseToReject = this;
- while ((parent = promiseToReject._cancellationParent) !== undefined &&
- parent.isCancellable()) {
- promiseToReject = parent;
- }
- this._unsetCancellable();
- promiseToReject._target()._rejectCallback(reason, false, true);
- };
- Promise.prototype.cancel = function (reason) {
- if (!this.isCancellable()) return this;
- if (reason === undefined) reason = new CancellationError();
- async.invokeLater(this._cancel, this, reason);
- return this;
- };
- Promise.prototype.cancellable = function () {
- if (this._cancellable()) return this;
- async.enableTrampoline();
- this._setCancellable();
- this._cancellationParent = undefined;
- return this;
- };
- Promise.prototype.uncancellable = function () {
- var ret = this.then();
- ret._unsetCancellable();
- return ret;
- };
- Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
- var ret = this._then(didFulfill, didReject, didProgress,
- undefined, undefined);
- ret._setCancellable();
- ret._cancellationParent = undefined;
- return ret;
- };
- };
- },{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function() {
- var async = _dereq_("./async.js");
- var util = _dereq_("./util.js");
- var bluebirdFramePattern =
- /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
- var stackFramePattern = null;
- var formatStack = null;
- var indentStackFrames = false;
- var warn;
- function CapturedTrace(parent) {
- this._parent = parent;
- var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
- captureStackTrace(this, CapturedTrace);
- if (length > 32) this.uncycle();
- }
- util.inherits(CapturedTrace, Error);
- CapturedTrace.prototype.uncycle = function() {
- var length = this._length;
- if (length < 2) return;
- var nodes = [];
- var stackToIndex = {};
- for (var i = 0, node = this; node !== undefined; ++i) {
- nodes.push(node);
- node = node._parent;
- }
- length = this._length = i;
- for (var i = length - 1; i >= 0; --i) {
- var stack = nodes[i].stack;
- if (stackToIndex[stack] === undefined) {
- stackToIndex[stack] = i;
- }
- }
- for (var i = 0; i < length; ++i) {
- var currentStack = nodes[i].stack;
- var index = stackToIndex[currentStack];
- if (index !== undefined && index !== i) {
- if (index > 0) {
- nodes[index - 1]._parent = undefined;
- nodes[index - 1]._length = 1;
- }
- nodes[i]._parent = undefined;
- nodes[i]._length = 1;
- var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
- if (index < length - 1) {
- cycleEdgeNode._parent = nodes[index + 1];
- cycleEdgeNode._parent.uncycle();
- cycleEdgeNode._length =
- cycleEdgeNode._parent._length + 1;
- } else {
- cycleEdgeNode._parent = undefined;
- cycleEdgeNode._length = 1;
- }
- var currentChildLength = cycleEdgeNode._length + 1;
- for (var j = i - 2; j >= 0; --j) {
- nodes[j]._length = currentChildLength;
- currentChildLength++;
- }
- return;
- }
- }
- };
- CapturedTrace.prototype.parent = function() {
- return this._parent;
- };
- CapturedTrace.prototype.hasParent = function() {
- return this._parent !== undefined;
- };
- CapturedTrace.prototype.attachExtraTrace = function(error) {
- if (error.__stackCleaned__) return;
- this.uncycle();
- var parsed = CapturedTrace.parseStackAndMessage(error);
- var message = parsed.message;
- var stacks = [parsed.stack];
- var trace = this;
- while (trace !== undefined) {
- stacks.push(cleanStack(trace.stack.split("\n")));
- trace = trace._parent;
- }
- removeCommonRoots(stacks);
- removeDuplicateOrEmptyJumps(stacks);
- util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
- util.notEnumerableProp(error, "__stackCleaned__", true);
- };
- function reconstructStack(message, stacks) {
- for (var i = 0; i < stacks.length - 1; ++i) {
- stacks[i].push("From previous event:");
- stacks[i] = stacks[i].join("\n");
- }
- if (i < stacks.length) {
- stacks[i] = stacks[i].join("\n");
- }
- return message + "\n" + stacks.join("\n");
- }
- function removeDuplicateOrEmptyJumps(stacks) {
- for (var i = 0; i < stacks.length; ++i) {
- if (stacks[i].length === 0 ||
- ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
- stacks.splice(i, 1);
- i--;
- }
- }
- }
- function removeCommonRoots(stacks) {
- var current = stacks[0];
- for (var i = 1; i < stacks.length; ++i) {
- var prev = stacks[i];
- var currentLastIndex = current.length - 1;
- var currentLastLine = current[currentLastIndex];
- var commonRootMeetPoint = -1;
- for (var j = prev.length - 1; j >= 0; --j) {
- if (prev[j] === currentLastLine) {
- commonRootMeetPoint = j;
- break;
- }
- }
- for (var j = commonRootMeetPoint; j >= 0; --j) {
- var line = prev[j];
- if (current[currentLastIndex] === line) {
- current.pop();
- currentLastIndex--;
- } else {
- break;
- }
- }
- current = prev;
- }
- }
- function cleanStack(stack) {
- var ret = [];
- for (var i = 0; i < stack.length; ++i) {
- var line = stack[i];
- var isTraceLine = stackFramePattern.test(line) ||
- " (No stack trace)" === line;
- var isInternalFrame = isTraceLine && shouldIgnore(line);
- if (isTraceLine && !isInternalFrame) {
- if (indentStackFrames && line.charAt(0) !== " ") {
- line = " " + line;
- }
- ret.push(line);
- }
- }
- return ret;
- }
- function stackFramesAsArray(error) {
- var stack = error.stack.replace(/\s+$/g, "").split("\n");
- for (var i = 0; i < stack.length; ++i) {
- var line = stack[i];
- if (" (No stack trace)" === line || stackFramePattern.test(line)) {
- break;
- }
- }
- if (i > 0) {
- stack = stack.slice(i);
- }
- return stack;
- }
- CapturedTrace.parseStackAndMessage = function(error) {
- var stack = error.stack;
- var message = error.toString();
- stack = typeof stack === "string" && stack.length > 0
- ? stackFramesAsArray(error) : [" (No stack trace)"];
- return {
- message: message,
- stack: cleanStack(stack)
- };
- };
- CapturedTrace.formatAndLogError = function(error, title) {
- if (typeof console !== "undefined") {
- var message;
- if (typeof error === "object" || typeof error === "function") {
- var stack = error.stack;
- message = title + formatStack(stack, error);
- } else {
- message = title + String(error);
- }
- if (typeof warn === "function") {
- warn(message);
- } else if (typeof console.log === "function" ||
- typeof console.log === "object") {
- console.log(message);
- }
- }
- };
- CapturedTrace.unhandledRejection = function (reason) {
- CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
- };
- CapturedTrace.isSupported = function () {
- return typeof captureStackTrace === "function";
- };
- CapturedTrace.fireRejectionEvent =
- function(name, localHandler, reason, promise) {
- var localEventFired = false;
- try {
- if (typeof localHandler === "function") {
- localEventFired = true;
- if (name === "rejectionHandled") {
- localHandler(promise);
- } else {
- localHandler(reason, promise);
- }
- }
- } catch (e) {
- async.throwLater(e);
- }
- var globalEventFired = false;
- try {
- globalEventFired = fireGlobalEvent(name, reason, promise);
- } catch (e) {
- globalEventFired = true;
- async.throwLater(e);
- }
- var domEventFired = false;
- if (fireDomEvent) {
- try {
- domEventFired = fireDomEvent(name.toLowerCase(), {
- reason: reason,
- promise: promise
- });
- } catch (e) {
- domEventFired = true;
- async.throwLater(e);
- }
- }
- if (!globalEventFired && !localEventFired && !domEventFired &&
- name === "unhandledRejection") {
- CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
- }
- };
- function formatNonError(obj) {
- var str;
- if (typeof obj === "function") {
- str = "[function " +
- (obj.name || "anonymous") +
- "]";
- } else {
- str = obj.toString();
- var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
- if (ruselessToString.test(str)) {
- try {
- var newStr = JSON.stringify(obj);
- str = newStr;
- }
- catch(e) {
- }
- }
- if (str.length === 0) {
- str = "(empty array)";
- }
- }
- return ("(<" + snip(str) + ">, no stack trace)");
- }
- function snip(str) {
- var maxChars = 41;
- if (str.length < maxChars) {
- return str;
- }
- return str.substr(0, maxChars - 3) + "...";
- }
- var shouldIgnore = function() { return false; };
- var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
- function parseLineInfo(line) {
- var matches = line.match(parseLineInfoRegex);
- if (matches) {
- return {
- fileName: matches[1],
- line: parseInt(matches[2], 10)
- };
- }
- }
- CapturedTrace.setBounds = function(firstLineError, lastLineError) {
- if (!CapturedTrace.isSupported()) return;
- var firstStackLines = firstLineError.stack.split("\n");
- var lastStackLines = lastLineError.stack.split("\n");
- var firstIndex = -1;
- var lastIndex = -1;
- var firstFileName;
- var lastFileName;
- for (var i = 0; i < firstStackLines.length; ++i) {
- var result = parseLineInfo(firstStackLines[i]);
- if (result) {
- firstFileName = result.fileName;
- firstIndex = result.line;
- break;
- }
- }
- for (var i = 0; i < lastStackLines.length; ++i) {
- var result = parseLineInfo(lastStackLines[i]);
- if (result) {
- lastFileName = result.fileName;
- lastIndex = result.line;
- break;
- }
- }
- if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
- firstFileName !== lastFileName || firstIndex >= lastIndex) {
- return;
- }
- shouldIgnore = function(line) {
- if (bluebirdFramePattern.test(line)) return true;
- var info = parseLineInfo(line);
- if (info) {
- if (info.fileName === firstFileName &&
- (firstIndex <= info.line && info.line <= lastIndex)) {
- return true;
- }
- }
- return false;
- };
- };
- var captureStackTrace = (function stackDetection() {
- var v8stackFramePattern = /^\s*at\s*/;
- var v8stackFormatter = function(stack, error) {
- if (typeof stack === "string") return stack;
- if (error.name !== undefined &&
- error.message !== undefined) {
- return error.toString();
- }
- return formatNonError(error);
- };
- if (typeof Error.stackTraceLimit === "number" &&
- typeof Error.captureStackTrace === "function") {
- Error.stackTraceLimit = Error.stackTraceLimit + 6;
- stackFramePattern = v8stackFramePattern;
- formatStack = v8stackFormatter;
- var captureStackTrace = Error.captureStackTrace;
- shouldIgnore = function(line) {
- return bluebirdFramePattern.test(line);
- };
- return function(receiver, ignoreUntil) {
- Error.stackTraceLimit = Error.stackTraceLimit + 6;
- captureStackTrace(receiver, ignoreUntil);
- Error.stackTraceLimit = Error.stackTraceLimit - 6;
- };
- }
- var err = new Error();
- if (typeof err.stack === "string" &&
- err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
- stackFramePattern = /@/;
- formatStack = v8stackFormatter;
- indentStackFrames = true;
- return function captureStackTrace(o) {
- o.stack = new Error().stack;
- };
- }
- var hasStackAfterThrow;
- try { throw new Error(); }
- catch(e) {
- hasStackAfterThrow = ("stack" in e);
- }
- if (!("stack" in err) && hasStackAfterThrow &&
- typeof Error.stackTraceLimit === "number") {
- stackFramePattern = v8stackFramePattern;
- formatStack = v8stackFormatter;
- return function captureStackTrace(o) {
- Error.stackTraceLimit = Error.stackTraceLimit + 6;
- try { throw new Error(); }
- catch(e) { o.stack = e.stack; }
- Error.stackTraceLimit = Error.stackTraceLimit - 6;
- };
- }
- formatStack = function(stack, error) {
- if (typeof stack === "string") return stack;
- if ((typeof error === "object" ||
- typeof error === "function") &&
- error.name !== undefined &&
- error.message !== undefined) {
- return error.toString();
- }
- return formatNonError(error);
- };
- return null;
- })([]);
- var fireDomEvent;
- var fireGlobalEvent = (function() {
- if (util.isNode) {
- return function(name, reason, promise) {
- if (name === "rejectionHandled") {
- return process.emit(name, promise);
- } else {
- return process.emit(name, reason, promise);
- }
- };
- } else {
- var customEventWorks = false;
- var anyEventWorks = true;
- try {
- var ev = new self.CustomEvent("test");
- customEventWorks = ev instanceof CustomEvent;
- } catch (e) {}
- if (!customEventWorks) {
- try {
- var event = document.createEvent("CustomEvent");
- event.initCustomEvent("testingtheevent", false, true, {});
- self.dispatchEvent(event);
- } catch (e) {
- anyEventWorks = false;
- }
- }
- if (anyEventWorks) {
- fireDomEvent = function(type, detail) {
- var event;
- if (customEventWorks) {
- event = new self.CustomEvent(type, {
- detail: detail,
- bubbles: false,
- cancelable: true
- });
- } else if (self.dispatchEvent) {
- event = document.createEvent("CustomEvent");
- event.initCustomEvent(type, false, true, detail);
- }
- return event ? !self.dispatchEvent(event) : false;
- };
- }
- var toWindowMethodNameMap = {};
- toWindowMethodNameMap["unhandledRejection"] = ("on" +
- "unhandledRejection").toLowerCase();
- toWindowMethodNameMap["rejectionHandled"] = ("on" +
- "rejectionHandled").toLowerCase();
- return function(name, reason, promise) {
- var methodName = toWindowMethodNameMap[name];
- var method = self[methodName];
- if (!method) return false;
- if (name === "rejectionHandled") {
- method.call(self, promise);
- } else {
- method.call(self, reason, promise);
- }
- return true;
- };
- }
- })();
- if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
- warn = function (message) {
- console.warn(message);
- };
- if (util.isNode && process.stderr.isTTY) {
- warn = function(message) {
- process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
- };
- } else if (!util.isNode && typeof (new Error().stack) === "string") {
- warn = function(message) {
- console.warn("%c" + message, "color: red");
- };
- }
- }
- return CapturedTrace;
- };
- },{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(NEXT_FILTER) {
- var util = _dereq_("./util.js");
- var errors = _dereq_("./errors.js");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var keys = _dereq_("./es5.js").keys;
- var TypeError = errors.TypeError;
- function CatchFilter(instances, callback, promise) {
- this._instances = instances;
- this._callback = callback;
- this._promise = promise;
- }
- function safePredicate(predicate, e) {
- var safeObject = {};
- var retfilter = tryCatch(predicate).call(safeObject, e);
- if (retfilter === errorObj) return retfilter;
- var safeKeys = keys(safeObject);
- if (safeKeys.length) {
- errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a");
- return errorObj;
- }
- return retfilter;
- }
- CatchFilter.prototype.doFilter = function (e) {
- var cb = this._callback;
- var promise = this._promise;
- var boundTo = promise._boundValue();
- for (var i = 0, len = this._instances.length; i < len; ++i) {
- var item = this._instances[i];
- var itemIsErrorType = item === Error ||
- (item != null && item.prototype instanceof Error);
- if (itemIsErrorType && e instanceof item) {
- var ret = tryCatch(cb).call(boundTo, e);
- if (ret === errorObj) {
- NEXT_FILTER.e = ret.e;
- return NEXT_FILTER;
- }
- return ret;
- } else if (typeof item === "function" && !itemIsErrorType) {
- var shouldHandle = safePredicate(item, e);
- if (shouldHandle === errorObj) {
- e = errorObj.e;
- break;
- } else if (shouldHandle) {
- var ret = tryCatch(cb).call(boundTo, e);
- if (ret === errorObj) {
- NEXT_FILTER.e = ret.e;
- return NEXT_FILTER;
- }
- return ret;
- }
- }
- }
- NEXT_FILTER.e = e;
- return NEXT_FILTER;
- };
- return CatchFilter;
- };
- },{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, CapturedTrace, isDebugging) {
- var contextStack = [];
- function Context() {
- this._trace = new CapturedTrace(peekContext());
- }
- Context.prototype._pushContext = function () {
- if (!isDebugging()) return;
- if (this._trace !== undefined) {
- contextStack.push(this._trace);
- }
- };
- Context.prototype._popContext = function () {
- if (!isDebugging()) return;
- if (this._trace !== undefined) {
- contextStack.pop();
- }
- };
- function createContext() {
- if (isDebugging()) return new Context();
- }
- function peekContext() {
- var lastIndex = contextStack.length - 1;
- if (lastIndex >= 0) {
- return contextStack[lastIndex];
- }
- return undefined;
- }
- Promise.prototype._peekContext = peekContext;
- Promise.prototype._pushContext = Context.prototype._pushContext;
- Promise.prototype._popContext = Context.prototype._popContext;
- return createContext;
- };
- },{}],10:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, CapturedTrace) {
- var getDomain = Promise._getDomain;
- var async = _dereq_("./async.js");
- var Warning = _dereq_("./errors.js").Warning;
- var util = _dereq_("./util.js");
- var canAttachTrace = util.canAttachTrace;
- var unhandledRejectionHandled;
- var possiblyUnhandledRejection;
- var debugging = false || (util.isNode &&
- (!!process.env["BLUEBIRD_DEBUG"] ||
- process.env["NODE_ENV"] === "development"));
- if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false;
- if (debugging) {
- async.disableTrampolineIfNecessary();
- }
- Promise.prototype._ignoreRejections = function() {
- this._unsetRejectionIsUnhandled();
- this._bitField = this._bitField | 16777216;
- };
- Promise.prototype._ensurePossibleRejectionHandled = function () {
- if ((this._bitField & 16777216) !== 0) return;
- this._setRejectionIsUnhandled();
- async.invokeLater(this._notifyUnhandledRejection, this, undefined);
- };
- Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
- CapturedTrace.fireRejectionEvent("rejectionHandled",
- unhandledRejectionHandled, undefined, this);
- };
- Promise.prototype._notifyUnhandledRejection = function () {
- if (this._isRejectionUnhandled()) {
- var reason = this._getCarriedStackTrace() || this._settledValue;
- this._setUnhandledRejectionIsNotified();
- CapturedTrace.fireRejectionEvent("unhandledRejection",
- possiblyUnhandledRejection, reason, this);
- }
- };
- Promise.prototype._setUnhandledRejectionIsNotified = function () {
- this._bitField = this._bitField | 524288;
- };
- Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
- this._bitField = this._bitField & (~524288);
- };
- Promise.prototype._isUnhandledRejectionNotified = function () {
- return (this._bitField & 524288) > 0;
- };
- Promise.prototype._setRejectionIsUnhandled = function () {
- this._bitField = this._bitField | 2097152;
- };
- Promise.prototype._unsetRejectionIsUnhandled = function () {
- this._bitField = this._bitField & (~2097152);
- if (this._isUnhandledRejectionNotified()) {
- this._unsetUnhandledRejectionIsNotified();
- this._notifyUnhandledRejectionIsHandled();
- }
- };
- Promise.prototype._isRejectionUnhandled = function () {
- return (this._bitField & 2097152) > 0;
- };
- Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
- this._bitField = this._bitField | 1048576;
- this._fulfillmentHandler0 = capturedTrace;
- };
- Promise.prototype._isCarryingStackTrace = function () {
- return (this._bitField & 1048576) > 0;
- };
- Promise.prototype._getCarriedStackTrace = function () {
- return this._isCarryingStackTrace()
- ? this._fulfillmentHandler0
- : undefined;
- };
- Promise.prototype._captureStackTrace = function () {
- if (debugging) {
- this._trace = new CapturedTrace(this._peekContext());
- }
- return this;
- };
- Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
- if (debugging && canAttachTrace(error)) {
- var trace = this._trace;
- if (trace !== undefined) {
- if (ignoreSelf) trace = trace._parent;
- }
- if (trace !== undefined) {
- trace.attachExtraTrace(error);
- } else if (!error.__stackCleaned__) {
- var parsed = CapturedTrace.parseStackAndMessage(error);
- util.notEnumerableProp(error, "stack",
- parsed.message + "\n" + parsed.stack.join("\n"));
- util.notEnumerableProp(error, "__stackCleaned__", true);
- }
- }
- };
- Promise.prototype._warn = function(message) {
- var warning = new Warning(message);
- var ctx = this._peekContext();
- if (ctx) {
- ctx.attachExtraTrace(warning);
- } else {
- var parsed = CapturedTrace.parseStackAndMessage(warning);
- warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
- }
- CapturedTrace.formatAndLogError(warning, "");
- };
- Promise.onPossiblyUnhandledRejection = function (fn) {
- var domain = getDomain();
- possiblyUnhandledRejection =
- typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
- : undefined;
- };
- Promise.onUnhandledRejectionHandled = function (fn) {
- var domain = getDomain();
- unhandledRejectionHandled =
- typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
- : undefined;
- };
- Promise.longStackTraces = function () {
- if (async.haveItemsQueued() &&
- debugging === false
- ) {
- throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a");
- }
- debugging = CapturedTrace.isSupported();
- if (debugging) {
- async.disableTrampolineIfNecessary();
- }
- };
- Promise.hasLongStackTraces = function () {
- return debugging && CapturedTrace.isSupported();
- };
- if (!CapturedTrace.isSupported()) {
- Promise.longStackTraces = function(){};
- debugging = false;
- }
- return function() {
- return debugging;
- };
- };
- },{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
- "use strict";
- var util = _dereq_("./util.js");
- var isPrimitive = util.isPrimitive;
- module.exports = function(Promise) {
- var returner = function () {
- return this;
- };
- var thrower = function () {
- throw this;
- };
- var returnUndefined = function() {};
- var throwUndefined = function() {
- throw undefined;
- };
- var wrapper = function (value, action) {
- if (action === 1) {
- return function () {
- throw value;
- };
- } else if (action === 2) {
- return function () {
- return value;
- };
- }
- };
- Promise.prototype["return"] =
- Promise.prototype.thenReturn = function (value) {
- if (value === undefined) return this.then(returnUndefined);
- if (isPrimitive(value)) {
- return this._then(
- wrapper(value, 2),
- undefined,
- undefined,
- undefined,
- undefined
- );
- } else if (value instanceof Promise) {
- value._ignoreRejections();
- }
- return this._then(returner, undefined, undefined, value, undefined);
- };
- Promise.prototype["throw"] =
- Promise.prototype.thenThrow = function (reason) {
- if (reason === undefined) return this.then(throwUndefined);
- if (isPrimitive(reason)) {
- return this._then(
- wrapper(reason, 1),
- undefined,
- undefined,
- undefined,
- undefined
- );
- }
- return this._then(thrower, undefined, undefined, reason, undefined);
- };
- };
- },{"./util.js":38}],12:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var PromiseReduce = Promise.reduce;
- Promise.prototype.each = function (fn) {
- return PromiseReduce(this, fn, null, INTERNAL);
- };
- Promise.each = function (promises, fn) {
- return PromiseReduce(promises, fn, null, INTERNAL);
- };
- };
- },{}],13:[function(_dereq_,module,exports){
- "use strict";
- var es5 = _dereq_("./es5.js");
- var Objectfreeze = es5.freeze;
- var util = _dereq_("./util.js");
- var inherits = util.inherits;
- var notEnumerableProp = util.notEnumerableProp;
- function subError(nameProperty, defaultMessage) {
- function SubError(message) {
- if (!(this instanceof SubError)) return new SubError(message);
- notEnumerableProp(this, "message",
- typeof message === "string" ? message : defaultMessage);
- notEnumerableProp(this, "name", nameProperty);
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- } else {
- Error.call(this);
- }
- }
- inherits(SubError, Error);
- return SubError;
- }
- var _TypeError, _RangeError;
- var Warning = subError("Warning", "warning");
- var CancellationError = subError("CancellationError", "cancellation error");
- var TimeoutError = subError("TimeoutError", "timeout error");
- var AggregateError = subError("AggregateError", "aggregate error");
- try {
- _TypeError = TypeError;
- _RangeError = RangeError;
- } catch(e) {
- _TypeError = subError("TypeError", "type error");
- _RangeError = subError("RangeError", "range error");
- }
- var methods = ("join pop push shift unshift slice filter forEach some " +
- "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
- for (var i = 0; i < methods.length; ++i) {
- if (typeof Array.prototype[methods[i]] === "function") {
- AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
- }
- }
- es5.defineProperty(AggregateError.prototype, "length", {
- value: 0,
- configurable: false,
- writable: true,
- enumerable: true
- });
- AggregateError.prototype["isOperational"] = true;
- var level = 0;
- AggregateError.prototype.toString = function() {
- var indent = Array(level * 4 + 1).join(" ");
- var ret = "\n" + indent + "AggregateError of:" + "\n";
- level++;
- indent = Array(level * 4 + 1).join(" ");
- for (var i = 0; i < this.length; ++i) {
- var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
- var lines = str.split("\n");
- for (var j = 0; j < lines.length; ++j) {
- lines[j] = indent + lines[j];
- }
- str = lines.join("\n");
- ret += str + "\n";
- }
- level--;
- return ret;
- };
- function OperationalError(message) {
- if (!(this instanceof OperationalError))
- return new OperationalError(message);
- notEnumerableProp(this, "name", "OperationalError");
- notEnumerableProp(this, "message", message);
- this.cause = message;
- this["isOperational"] = true;
- if (message instanceof Error) {
- notEnumerableProp(this, "message", message.message);
- notEnumerableProp(this, "stack", message.stack);
- } else if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
- }
- inherits(OperationalError, Error);
- var errorTypes = Error["__BluebirdErrorTypes__"];
- if (!errorTypes) {
- errorTypes = Objectfreeze({
- CancellationError: CancellationError,
- TimeoutError: TimeoutError,
- OperationalError: OperationalError,
- RejectionError: OperationalError,
- AggregateError: AggregateError
- });
- notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
- }
- module.exports = {
- Error: Error,
- TypeError: _TypeError,
- RangeError: _RangeError,
- CancellationError: errorTypes.CancellationError,
- OperationalError: errorTypes.OperationalError,
- TimeoutError: errorTypes.TimeoutError,
- AggregateError: errorTypes.AggregateError,
- Warning: Warning
- };
- },{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
- var isES5 = (function(){
- "use strict";
- return this === undefined;
- })();
- if (isES5) {
- module.exports = {
- freeze: Object.freeze,
- defineProperty: Object.defineProperty,
- getDescriptor: Object.getOwnPropertyDescriptor,
- keys: Object.keys,
- names: Object.getOwnPropertyNames,
- getPrototypeOf: Object.getPrototypeOf,
- isArray: Array.isArray,
- isES5: isES5,
- propertyIsWritable: function(obj, prop) {
- var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- return !!(!descriptor || descriptor.writable || descriptor.set);
- }
- };
- } else {
- var has = {}.hasOwnProperty;
- var str = {}.toString;
- var proto = {}.constructor.prototype;
- var ObjectKeys = function (o) {
- var ret = [];
- for (var key in o) {
- if (has.call(o, key)) {
- ret.push(key);
- }
- }
- return ret;
- };
- var ObjectGetDescriptor = function(o, key) {
- return {value: o[key]};
- };
- var ObjectDefineProperty = function (o, key, desc) {
- o[key] = desc.value;
- return o;
- };
- var ObjectFreeze = function (obj) {
- return obj;
- };
- var ObjectGetPrototypeOf = function (obj) {
- try {
- return Object(obj).constructor.prototype;
- }
- catch (e) {
- return proto;
- }
- };
- var ArrayIsArray = function (obj) {
- try {
- return str.call(obj) === "[object Array]";
- }
- catch(e) {
- return false;
- }
- };
- module.exports = {
- isArray: ArrayIsArray,
- keys: ObjectKeys,
- names: ObjectKeys,
- defineProperty: ObjectDefineProperty,
- getDescriptor: ObjectGetDescriptor,
- freeze: ObjectFreeze,
- getPrototypeOf: ObjectGetPrototypeOf,
- isES5: isES5,
- propertyIsWritable: function() {
- return true;
- }
- };
- }
- },{}],15:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var PromiseMap = Promise.map;
- Promise.prototype.filter = function (fn, options) {
- return PromiseMap(this, fn, options, INTERNAL);
- };
- Promise.filter = function (promises, fn, options) {
- return PromiseMap(promises, fn, options, INTERNAL);
- };
- };
- },{}],16:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
- var util = _dereq_("./util.js");
- var isPrimitive = util.isPrimitive;
- var thrower = util.thrower;
- function returnThis() {
- return this;
- }
- function throwThis() {
- throw this;
- }
- function return$(r) {
- return function() {
- return r;
- };
- }
- function throw$(r) {
- return function() {
- throw r;
- };
- }
- function promisedFinally(ret, reasonOrValue, isFulfilled) {
- var then;
- if (isPrimitive(reasonOrValue)) {
- then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
- } else {
- then = isFulfilled ? returnThis : throwThis;
- }
- return ret._then(then, thrower, undefined, reasonOrValue, undefined);
- }
- function finallyHandler(reasonOrValue) {
- var promise = this.promise;
- var handler = this.handler;
- var ret = promise._isBound()
- ? handler.call(promise._boundValue())
- : handler();
- if (ret !== undefined) {
- var maybePromise = tryConvertToPromise(ret, promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- return promisedFinally(maybePromise, reasonOrValue,
- promise.isFulfilled());
- }
- }
- if (promise.isRejected()) {
- NEXT_FILTER.e = reasonOrValue;
- return NEXT_FILTER;
- } else {
- return reasonOrValue;
- }
- }
- function tapHandler(value) {
- var promise = this.promise;
- var handler = this.handler;
- var ret = promise._isBound()
- ? handler.call(promise._boundValue(), value)
- : handler(value);
- if (ret !== undefined) {
- var maybePromise = tryConvertToPromise(ret, promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- return promisedFinally(maybePromise, value, true);
- }
- }
- return value;
- }
- Promise.prototype._passThroughHandler = function (handler, isFinally) {
- if (typeof handler !== "function") return this.then();
- var promiseAndHandler = {
- promise: this,
- handler: handler
- };
- return this._then(
- isFinally ? finallyHandler : tapHandler,
- isFinally ? finallyHandler : undefined, undefined,
- promiseAndHandler, undefined);
- };
- Promise.prototype.lastly =
- Promise.prototype["finally"] = function (handler) {
- return this._passThroughHandler(handler, true);
- };
- Promise.prototype.tap = function (handler) {
- return this._passThroughHandler(handler, false);
- };
- };
- },{"./util.js":38}],17:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise,
- apiRejection,
- INTERNAL,
- tryConvertToPromise) {
- var errors = _dereq_("./errors.js");
- var TypeError = errors.TypeError;
- var util = _dereq_("./util.js");
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- var yieldHandlers = [];
- function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
- for (var i = 0; i < yieldHandlers.length; ++i) {
- traceParent._pushContext();
- var result = tryCatch(yieldHandlers[i])(value);
- traceParent._popContext();
- if (result === errorObj) {
- traceParent._pushContext();
- var ret = Promise.reject(errorObj.e);
- traceParent._popContext();
- return ret;
- }
- var maybePromise = tryConvertToPromise(result, traceParent);
- if (maybePromise instanceof Promise) return maybePromise;
- }
- return null;
- }
- function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
- var promise = this._promise = new Promise(INTERNAL);
- promise._captureStackTrace();
- this._stack = stack;
- this._generatorFunction = generatorFunction;
- this._receiver = receiver;
- this._generator = undefined;
- this._yieldHandlers = typeof yieldHandler === "function"
- ? [yieldHandler].concat(yieldHandlers)
- : yieldHandlers;
- }
- PromiseSpawn.prototype.promise = function () {
- return this._promise;
- };
- PromiseSpawn.prototype._run = function () {
- this._generator = this._generatorFunction.call(this._receiver);
- this._receiver =
- this._generatorFunction = undefined;
- this._next(undefined);
- };
- PromiseSpawn.prototype._continue = function (result) {
- if (result === errorObj) {
- return this._promise._rejectCallback(result.e, false, true);
- }
- var value = result.value;
- if (result.done === true) {
- this._promise._resolveCallback(value);
- } else {
- var maybePromise = tryConvertToPromise(value, this._promise);
- if (!(maybePromise instanceof Promise)) {
- maybePromise =
- promiseFromYieldHandler(maybePromise,
- this._yieldHandlers,
- this._promise);
- if (maybePromise === null) {
- this._throw(
- new TypeError(
- "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) +
- "From coroutine:\u000a" +
- this._stack.split("\n").slice(1, -7).join("\n")
- )
- );
- return;
- }
- }
- maybePromise._then(
- this._next,
- this._throw,
- undefined,
- this,
- null
- );
- }
- };
- PromiseSpawn.prototype._throw = function (reason) {
- this._promise._attachExtraTrace(reason);
- this._promise._pushContext();
- var result = tryCatch(this._generator["throw"])
- .call(this._generator, reason);
- this._promise._popContext();
- this._continue(result);
- };
- PromiseSpawn.prototype._next = function (value) {
- this._promise._pushContext();
- var result = tryCatch(this._generator.next).call(this._generator, value);
- this._promise._popContext();
- this._continue(result);
- };
- Promise.coroutine = function (generatorFunction, options) {
- if (typeof generatorFunction !== "function") {
- throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
- }
- var yieldHandler = Object(options).yieldHandler;
- var PromiseSpawn$ = PromiseSpawn;
- var stack = new Error().stack;
- return function () {
- var generator = generatorFunction.apply(this, arguments);
- var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
- stack);
- spawn._generator = generator;
- spawn._next(undefined);
- return spawn.promise();
- };
- };
- Promise.coroutine.addYieldHandler = function(fn) {
- if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- yieldHandlers.push(fn);
- };
- Promise.spawn = function (generatorFunction) {
- if (typeof generatorFunction !== "function") {
- return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
- }
- var spawn = new PromiseSpawn(generatorFunction, this);
- var ret = spawn.promise();
- spawn._run(Promise.spawn);
- return ret;
- };
- };
- },{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
- var util = _dereq_("./util.js");
- var canEvaluate = util.canEvaluate;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var reject;
- if (!true) {
- if (canEvaluate) {
- var thenCallback = function(i) {
- return new Function("value", "holder", " \n\
- 'use strict'; \n\
- holder.pIndex = value; \n\
- holder.checkFulfillment(this); \n\
- ".replace(/Index/g, i));
- };
- var caller = function(count) {
- var values = [];
- for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
- return new Function("holder", " \n\
- 'use strict'; \n\
- var callback = holder.fn; \n\
- return callback(values); \n\
- ".replace(/values/g, values.join(", ")));
- };
- var thenCallbacks = [];
- var callers = [undefined];
- for (var i = 1; i <= 5; ++i) {
- thenCallbacks.push(thenCallback(i));
- callers.push(caller(i));
- }
- var Holder = function(total, fn) {
- this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
- this.fn = fn;
- this.total = total;
- this.now = 0;
- };
- Holder.prototype.callers = callers;
- Holder.prototype.checkFulfillment = function(promise) {
- var now = this.now;
- now++;
- var total = this.total;
- if (now >= total) {
- var handler = this.callers[total];
- promise._pushContext();
- var ret = tryCatch(handler)(this);
- promise._popContext();
- if (ret === errorObj) {
- promise._rejectCallback(ret.e, false, true);
- } else {
- promise._resolveCallback(ret);
- }
- } else {
- this.now = now;
- }
- };
- var reject = function (reason) {
- this._reject(reason);
- };
- }
- }
- Promise.join = function () {
- var last = arguments.length - 1;
- var fn;
- if (last > 0 && typeof arguments[last] === "function") {
- fn = arguments[last];
- if (!true) {
- if (last < 6 && canEvaluate) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- var holder = new Holder(last, fn);
- var callbacks = thenCallbacks;
- for (var i = 0; i < last; ++i) {
- var maybePromise = tryConvertToPromise(arguments[i], ret);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- if (maybePromise._isPending()) {
- maybePromise._then(callbacks[i], reject,
- undefined, ret, holder);
- } else if (maybePromise._isFulfilled()) {
- callbacks[i].call(ret,
- maybePromise._value(), holder);
- } else {
- ret._reject(maybePromise._reason());
- }
- } else {
- callbacks[i].call(ret, maybePromise, holder);
- }
- }
- return ret;
- }
- }
- }
- var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
- if (fn) args.pop();
- var ret = new PromiseArray(args).promise();
- return fn !== undefined ? ret.spread(fn) : ret;
- };
- };
- },{"./util.js":38}],19:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise,
- PromiseArray,
- apiRejection,
- tryConvertToPromise,
- INTERNAL) {
- var getDomain = Promise._getDomain;
- var async = _dereq_("./async.js");
- var util = _dereq_("./util.js");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var PENDING = {};
- var EMPTY_ARRAY = [];
- function MappingPromiseArray(promises, fn, limit, _filter) {
- this.constructor$(promises);
- this._promise._captureStackTrace();
- var domain = getDomain();
- this._callback = domain === null ? fn : domain.bind(fn);
- this._preservedValues = _filter === INTERNAL
- ? new Array(this.length())
- : null;
- this._limit = limit;
- this._inFlight = 0;
- this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
- async.invoke(init, this, undefined);
- }
- util.inherits(MappingPromiseArray, PromiseArray);
- function init() {this._init$(undefined, -2);}
- MappingPromiseArray.prototype._init = function () {};
- MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var values = this._values;
- var length = this.length();
- var preservedValues = this._preservedValues;
- var limit = this._limit;
- if (values[index] === PENDING) {
- values[index] = value;
- if (limit >= 1) {
- this._inFlight--;
- this._drainQueue();
- if (this._isResolved()) return;
- }
- } else {
- if (limit >= 1 && this._inFlight >= limit) {
- values[index] = value;
- this._queue.push(index);
- return;
- }
- if (preservedValues !== null) preservedValues[index] = value;
- var callback = this._callback;
- var receiver = this._promise._boundValue();
- this._promise._pushContext();
- var ret = tryCatch(callback).call(receiver, value, index, length);
- this._promise._popContext();
- if (ret === errorObj) return this._reject(ret.e);
- var maybePromise = tryConvertToPromise(ret, this._promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- if (maybePromise._isPending()) {
- if (limit >= 1) this._inFlight++;
- values[index] = PENDING;
- return maybePromise._proxyPromiseArray(this, index);
- } else if (maybePromise._isFulfilled()) {
- ret = maybePromise._value();
- } else {
- return this._reject(maybePromise._reason());
- }
- }
- values[index] = ret;
- }
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= length) {
- if (preservedValues !== null) {
- this._filter(values, preservedValues);
- } else {
- this._resolve(values);
- }
- }
- };
- MappingPromiseArray.prototype._drainQueue = function () {
- var queue = this._queue;
- var limit = this._limit;
- var values = this._values;
- while (queue.length > 0 && this._inFlight < limit) {
- if (this._isResolved()) return;
- var index = queue.pop();
- this._promiseFulfilled(values[index], index);
- }
- };
- MappingPromiseArray.prototype._filter = function (booleans, values) {
- var len = values.length;
- var ret = new Array(len);
- var j = 0;
- for (var i = 0; i < len; ++i) {
- if (booleans[i]) ret[j++] = values[i];
- }
- ret.length = j;
- this._resolve(ret);
- };
- MappingPromiseArray.prototype.preservedValues = function () {
- return this._preservedValues;
- };
- function map(promises, fn, options, _filter) {
- var limit = typeof options === "object" && options !== null
- ? options.concurrency
- : 0;
- limit = typeof limit === "number" &&
- isFinite(limit) && limit >= 1 ? limit : 0;
- return new MappingPromiseArray(promises, fn, limit, _filter);
- }
- Promise.prototype.map = function (fn, options) {
- if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- return map(this, fn, options, null).promise();
- };
- Promise.map = function (promises, fn, options, _filter) {
- if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- return map(promises, fn, options, _filter).promise();
- };
- };
- },{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
- var util = _dereq_("./util.js");
- var tryCatch = util.tryCatch;
- Promise.method = function (fn) {
- if (typeof fn !== "function") {
- throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- }
- return function () {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._pushContext();
- var value = tryCatch(fn).apply(this, arguments);
- ret._popContext();
- ret._resolveFromSyncValue(value);
- return ret;
- };
- };
- Promise.attempt = Promise["try"] = function (fn, args, ctx) {
- if (typeof fn !== "function") {
- return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- }
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._pushContext();
- var value = util.isArray(args)
- ? tryCatch(fn).apply(ctx, args)
- : tryCatch(fn).call(ctx, args);
- ret._popContext();
- ret._resolveFromSyncValue(value);
- return ret;
- };
- Promise.prototype._resolveFromSyncValue = function (value) {
- if (value === util.errorObj) {
- this._rejectCallback(value.e, false, true);
- } else {
- this._resolveCallback(value, true);
- }
- };
- };
- },{"./util.js":38}],21:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var util = _dereq_("./util.js");
- var async = _dereq_("./async.js");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- function spreadAdapter(val, nodeback) {
- var promise = this;
- if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
- var ret =
- tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- function successAdapter(val, nodeback) {
- var promise = this;
- var receiver = promise._boundValue();
- var ret = val === undefined
- ? tryCatch(nodeback).call(receiver, null)
- : tryCatch(nodeback).call(receiver, null, val);
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- function errorAdapter(reason, nodeback) {
- var promise = this;
- if (!reason) {
- var target = promise._target();
- var newReason = target._getCarriedStackTrace();
- newReason.cause = reason;
- reason = newReason;
- }
- var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- Promise.prototype.asCallback =
- Promise.prototype.nodeify = function (nodeback, options) {
- if (typeof nodeback == "function") {
- var adapter = successAdapter;
- if (options !== undefined && Object(options).spread) {
- adapter = spreadAdapter;
- }
- this._then(
- adapter,
- errorAdapter,
- undefined,
- this,
- nodeback
- );
- }
- return this;
- };
- };
- },{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, PromiseArray) {
- var util = _dereq_("./util.js");
- var async = _dereq_("./async.js");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- Promise.prototype.progressed = function (handler) {
- return this._then(undefined, undefined, handler, undefined, undefined);
- };
- Promise.prototype._progress = function (progressValue) {
- if (this._isFollowingOrFulfilledOrRejected()) return;
- this._target()._progressUnchecked(progressValue);
- };
- Promise.prototype._progressHandlerAt = function (index) {
- return index === 0
- ? this._progressHandler0
- : this[(index << 2) + index - 5 + 2];
- };
- Promise.prototype._doProgressWith = function (progression) {
- var progressValue = progression.value;
- var handler = progression.handler;
- var promise = progression.promise;
- var receiver = progression.receiver;
- var ret = tryCatch(handler).call(receiver, progressValue);
- if (ret === errorObj) {
- if (ret.e != null &&
- ret.e.name !== "StopProgressPropagation") {
- var trace = util.canAttachTrace(ret.e)
- ? ret.e : new Error(util.toString(ret.e));
- promise._attachExtraTrace(trace);
- promise._progress(ret.e);
- }
- } else if (ret instanceof Promise) {
- ret._then(promise._progress, null, null, promise, undefined);
- } else {
- promise._progress(ret);
- }
- };
- Promise.prototype._progressUnchecked = function (progressValue) {
- var len = this._length();
- var progress = this._progress;
- for (var i = 0; i < len; i++) {
- var handler = this._progressHandlerAt(i);
- var promise = this._promiseAt(i);
- if (!(promise instanceof Promise)) {
- var receiver = this._receiverAt(i);
- if (typeof handler === "function") {
- handler.call(receiver, progressValue, promise);
- } else if (receiver instanceof PromiseArray &&
- !receiver._isResolved()) {
- receiver._promiseProgressed(progressValue, promise);
- }
- continue;
- }
- if (typeof handler === "function") {
- async.invoke(this._doProgressWith, this, {
- handler: handler,
- promise: promise,
- receiver: this._receiverAt(i),
- value: progressValue
- });
- } else {
- async.invoke(progress, promise, progressValue);
- }
- }
- };
- };
- },{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function() {
- var makeSelfResolutionError = function () {
- return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a");
- };
- var reflect = function() {
- return new Promise.PromiseInspection(this._target());
- };
- var apiRejection = function(msg) {
- return Promise.reject(new TypeError(msg));
- };
- var util = _dereq_("./util.js");
- var getDomain;
- if (util.isNode) {
- getDomain = function() {
- var ret = process.domain;
- if (ret === undefined) ret = null;
- return ret;
- };
- } else {
- getDomain = function() {
- return null;
- };
- }
- util.notEnumerableProp(Promise, "_getDomain", getDomain);
- var UNDEFINED_BINDING = {};
- var async = _dereq_("./async.js");
- var errors = _dereq_("./errors.js");
- var TypeError = Promise.TypeError = errors.TypeError;
- Promise.RangeError = errors.RangeError;
- Promise.CancellationError = errors.CancellationError;
- Promise.TimeoutError = errors.TimeoutError;
- Promise.OperationalError = errors.OperationalError;
- Promise.RejectionError = errors.OperationalError;
- Promise.AggregateError = errors.AggregateError;
- var INTERNAL = function(){};
- var APPLY = {};
- var NEXT_FILTER = {e: null};
- var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
- var PromiseArray =
- _dereq_("./promise_array.js")(Promise, INTERNAL,
- tryConvertToPromise, apiRejection);
- var CapturedTrace = _dereq_("./captured_trace.js")();
- var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
- /*jshint unused:false*/
- var createContext =
- _dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
- var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
- var PromiseResolver = _dereq_("./promise_resolver.js");
- var nodebackForPromise = PromiseResolver._nodebackForPromise;
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- function Promise(resolver) {
- if (typeof resolver !== "function") {
- throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a");
- }
- if (this.constructor !== Promise) {
- throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a");
- }
- this._bitField = 0;
- this._fulfillmentHandler0 = undefined;
- this._rejectionHandler0 = undefined;
- this._progressHandler0 = undefined;
- this._promise0 = undefined;
- this._receiver0 = undefined;
- this._settledValue = undefined;
- if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
- }
- Promise.prototype.toString = function () {
- return "[object Promise]";
- };
- Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
- var len = arguments.length;
- if (len > 1) {
- var catchInstances = new Array(len - 1),
- j = 0, i;
- for (i = 0; i < len - 1; ++i) {
- var item = arguments[i];
- if (typeof item === "function") {
- catchInstances[j++] = item;
- } else {
- return Promise.reject(
- new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"));
- }
- }
- catchInstances.length = j;
- fn = arguments[i];
- var catchFilter = new CatchFilter(catchInstances, fn, this);
- return this._then(undefined, catchFilter.doFilter, undefined,
- catchFilter, undefined);
- }
- return this._then(undefined, fn, undefined, undefined, undefined);
- };
- Promise.prototype.reflect = function () {
- return this._then(reflect, reflect, undefined, this, undefined);
- };
- Promise.prototype.then = function (didFulfill, didReject, didProgress) {
- if (isDebugging() && arguments.length > 0 &&
- typeof didFulfill !== "function" &&
- typeof didReject !== "function") {
- var msg = ".then() only accepts functions but was passed: " +
- util.classString(didFulfill);
- if (arguments.length > 1) {
- msg += ", " + util.classString(didReject);
- }
- this._warn(msg);
- }
- return this._then(didFulfill, didReject, didProgress,
- undefined, undefined);
- };
- Promise.prototype.done = function (didFulfill, didReject, didProgress) {
- var promise = this._then(didFulfill, didReject, didProgress,
- undefined, undefined);
- promise._setIsFinal();
- };
- Promise.prototype.spread = function (didFulfill, didReject) {
- return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
- };
- Promise.prototype.isCancellable = function () {
- return !this.isResolved() &&
- this._cancellable();
- };
- Promise.prototype.toJSON = function () {
- var ret = {
- isFulfilled: false,
- isRejected: false,
- fulfillmentValue: undefined,
- rejectionReason: undefined
- };
- if (this.isFulfilled()) {
- ret.fulfillmentValue = this.value();
- ret.isFulfilled = true;
- } else if (this.isRejected()) {
- ret.rejectionReason = this.reason();
- ret.isRejected = true;
- }
- return ret;
- };
- Promise.prototype.all = function () {
- return new PromiseArray(this).promise();
- };
- Promise.prototype.error = function (fn) {
- return this.caught(util.originatesFromRejection, fn);
- };
- Promise.getNewLibraryCopy = module.exports;
- Promise.is = function (val) {
- return val instanceof Promise;
- };
- Promise.fromNode = function(fn) {
- var ret = new Promise(INTERNAL);
- var result = tryCatch(fn)(nodebackForPromise(ret));
- if (result === errorObj) {
- ret._rejectCallback(result.e, true, true);
- }
- return ret;
- };
- Promise.all = function (promises) {
- return new PromiseArray(promises).promise();
- };
- Promise.defer = Promise.pending = function () {
- var promise = new Promise(INTERNAL);
- return new PromiseResolver(promise);
- };
- Promise.cast = function (obj) {
- var ret = tryConvertToPromise(obj);
- if (!(ret instanceof Promise)) {
- var val = ret;
- ret = new Promise(INTERNAL);
- ret._fulfillUnchecked(val);
- }
- return ret;
- };
- Promise.resolve = Promise.fulfilled = Promise.cast;
- Promise.reject = Promise.rejected = function (reason) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._rejectCallback(reason, true);
- return ret;
- };
- Promise.setScheduler = function(fn) {
- if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- var prev = async._schedule;
- async._schedule = fn;
- return prev;
- };
- Promise.prototype._then = function (
- didFulfill,
- didReject,
- didProgress,
- receiver,
- internalData
- ) {
- var haveInternalData = internalData !== undefined;
- var ret = haveInternalData ? internalData : new Promise(INTERNAL);
- if (!haveInternalData) {
- ret._propagateFrom(this, 4 | 1);
- ret._captureStackTrace();
- }
- var target = this._target();
- if (target !== this) {
- if (receiver === undefined) receiver = this._boundTo;
- if (!haveInternalData) ret._setIsMigrated();
- }
- var callbackIndex = target._addCallbacks(didFulfill,
- didReject,
- didProgress,
- ret,
- receiver,
- getDomain());
- if (target._isResolved() && !target._isSettlePromisesQueued()) {
- async.invoke(
- target._settlePromiseAtPostResolution, target, callbackIndex);
- }
- return ret;
- };
- Promise.prototype._settlePromiseAtPostResolution = function (index) {
- if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
- this._settlePromiseAt(index);
- };
- Promise.prototype._length = function () {
- return this._bitField & 131071;
- };
- Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
- return (this._bitField & 939524096) > 0;
- };
- Promise.prototype._isFollowing = function () {
- return (this._bitField & 536870912) === 536870912;
- };
- Promise.prototype._setLength = function (len) {
- this._bitField = (this._bitField & -131072) |
- (len & 131071);
- };
- Promise.prototype._setFulfilled = function () {
- this._bitField = this._bitField | 268435456;
- };
- Promise.prototype._setRejected = function () {
- this._bitField = this._bitField | 134217728;
- };
- Promise.prototype._setFollowing = function () {
- this._bitField = this._bitField | 536870912;
- };
- Promise.prototype._setIsFinal = function () {
- this._bitField = this._bitField | 33554432;
- };
- Promise.prototype._isFinal = function () {
- return (this._bitField & 33554432) > 0;
- };
- Promise.prototype._cancellable = function () {
- return (this._bitField & 67108864) > 0;
- };
- Promise.prototype._setCancellable = function () {
- this._bitField = this._bitField | 67108864;
- };
- Promise.prototype._unsetCancellable = function () {
- this._bitField = this._bitField & (~67108864);
- };
- Promise.prototype._setIsMigrated = function () {
- this._bitField = this._bitField | 4194304;
- };
- Promise.prototype._unsetIsMigrated = function () {
- this._bitField = this._bitField & (~4194304);
- };
- Promise.prototype._isMigrated = function () {
- return (this._bitField & 4194304) > 0;
- };
- Promise.prototype._receiverAt = function (index) {
- var ret = index === 0
- ? this._receiver0
- : this[
- index * 5 - 5 + 4];
- if (ret === UNDEFINED_BINDING) {
- return undefined;
- } else if (ret === undefined && this._isBound()) {
- return this._boundValue();
- }
- return ret;
- };
- Promise.prototype._promiseAt = function (index) {
- return index === 0
- ? this._promise0
- : this[index * 5 - 5 + 3];
- };
- Promise.prototype._fulfillmentHandlerAt = function (index) {
- return index === 0
- ? this._fulfillmentHandler0
- : this[index * 5 - 5 + 0];
- };
- Promise.prototype._rejectionHandlerAt = function (index) {
- return index === 0
- ? this._rejectionHandler0
- : this[index * 5 - 5 + 1];
- };
- Promise.prototype._boundValue = function() {
- var ret = this._boundTo;
- if (ret !== undefined) {
- if (ret instanceof Promise) {
- if (ret.isFulfilled()) {
- return ret.value();
- } else {
- return undefined;
- }
- }
- }
- return ret;
- };
- Promise.prototype._migrateCallbacks = function (follower, index) {
- var fulfill = follower._fulfillmentHandlerAt(index);
- var reject = follower._rejectionHandlerAt(index);
- var progress = follower._progressHandlerAt(index);
- var promise = follower._promiseAt(index);
- var receiver = follower._receiverAt(index);
- if (promise instanceof Promise) promise._setIsMigrated();
- if (receiver === undefined) receiver = UNDEFINED_BINDING;
- this._addCallbacks(fulfill, reject, progress, promise, receiver, null);
- };
- Promise.prototype._addCallbacks = function (
- fulfill,
- reject,
- progress,
- promise,
- receiver,
- domain
- ) {
- var index = this._length();
- if (index >= 131071 - 5) {
- index = 0;
- this._setLength(0);
- }
- if (index === 0) {
- this._promise0 = promise;
- if (receiver !== undefined) this._receiver0 = receiver;
- if (typeof fulfill === "function" && !this._isCarryingStackTrace()) {
- this._fulfillmentHandler0 =
- domain === null ? fulfill : domain.bind(fulfill);
- }
- if (typeof reject === "function") {
- this._rejectionHandler0 =
- domain === null ? reject : domain.bind(reject);
- }
- if (typeof progress === "function") {
- this._progressHandler0 =
- domain === null ? progress : domain.bind(progress);
- }
- } else {
- var base = index * 5 - 5;
- this[base + 3] = promise;
- this[base + 4] = receiver;
- if (typeof fulfill === "function") {
- this[base + 0] =
- domain === null ? fulfill : domain.bind(fulfill);
- }
- if (typeof reject === "function") {
- this[base + 1] =
- domain === null ? reject : domain.bind(reject);
- }
- if (typeof progress === "function") {
- this[base + 2] =
- domain === null ? progress : domain.bind(progress);
- }
- }
- this._setLength(index + 1);
- return index;
- };
- Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
- var index = this._length();
- if (index >= 131071 - 5) {
- index = 0;
- this._setLength(0);
- }
- if (index === 0) {
- this._promise0 = promiseSlotValue;
- this._receiver0 = receiver;
- } else {
- var base = index * 5 - 5;
- this[base + 3] = promiseSlotValue;
- this[base + 4] = receiver;
- }
- this._setLength(index + 1);
- };
- Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
- this._setProxyHandlers(promiseArray, index);
- };
- Promise.prototype._resolveCallback = function(value, shouldBind) {
- if (this._isFollowingOrFulfilledOrRejected()) return;
- if (value === this)
- return this._rejectCallback(makeSelfResolutionError(), false, true);
- var maybePromise = tryConvertToPromise(value, this);
- if (!(maybePromise instanceof Promise)) return this._fulfill(value);
- var propagationFlags = 1 | (shouldBind ? 4 : 0);
- this._propagateFrom(maybePromise, propagationFlags);
- var promise = maybePromise._target();
- if (promise._isPending()) {
- var len = this._length();
- for (var i = 0; i < len; ++i) {
- promise._migrateCallbacks(this, i);
- }
- this._setFollowing();
- this._setLength(0);
- this._setFollowee(promise);
- } else if (promise._isFulfilled()) {
- this._fulfillUnchecked(promise._value());
- } else {
- this._rejectUnchecked(promise._reason(),
- promise._getCarriedStackTrace());
- }
- };
- Promise.prototype._rejectCallback =
- function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
- if (!shouldNotMarkOriginatingFromRejection) {
- util.markAsOriginatingFromRejection(reason);
- }
- var trace = util.ensureErrorObject(reason);
- var hasStack = trace === reason;
- this._attachExtraTrace(trace, synchronous ? hasStack : false);
- this._reject(reason, hasStack ? undefined : trace);
- };
- Promise.prototype._resolveFromResolver = function (resolver) {
- var promise = this;
- this._captureStackTrace();
- this._pushContext();
- var synchronous = true;
- var r = tryCatch(resolver)(function(value) {
- if (promise === null) return;
- promise._resolveCallback(value);
- promise = null;
- }, function (reason) {
- if (promise === null) return;
- promise._rejectCallback(reason, synchronous);
- promise = null;
- });
- synchronous = false;
- this._popContext();
- if (r !== undefined && r === errorObj && promise !== null) {
- promise._rejectCallback(r.e, true, true);
- promise = null;
- }
- };
- Promise.prototype._settlePromiseFromHandler = function (
- handler, receiver, value, promise
- ) {
- if (promise._isRejected()) return;
- promise._pushContext();
- var x;
- if (receiver === APPLY && !this._isRejected()) {
- x = tryCatch(handler).apply(this._boundValue(), value);
- } else {
- x = tryCatch(handler).call(receiver, value);
- }
- promise._popContext();
- if (x === errorObj || x === promise || x === NEXT_FILTER) {
- var err = x === promise ? makeSelfResolutionError() : x.e;
- promise._rejectCallback(err, false, true);
- } else {
- promise._resolveCallback(x);
- }
- };
- Promise.prototype._target = function() {
- var ret = this;
- while (ret._isFollowing()) ret = ret._followee();
- return ret;
- };
- Promise.prototype._followee = function() {
- return this._rejectionHandler0;
- };
- Promise.prototype._setFollowee = function(promise) {
- this._rejectionHandler0 = promise;
- };
- Promise.prototype._cleanValues = function () {
- if (this._cancellable()) {
- this._cancellationParent = undefined;
- }
- };
- Promise.prototype._propagateFrom = function (parent, flags) {
- if ((flags & 1) > 0 && parent._cancellable()) {
- this._setCancellable();
- this._cancellationParent = parent;
- }
- if ((flags & 4) > 0 && parent._isBound()) {
- this._setBoundTo(parent._boundTo);
- }
- };
- Promise.prototype._fulfill = function (value) {
- if (this._isFollowingOrFulfilledOrRejected()) return;
- this._fulfillUnchecked(value);
- };
- Promise.prototype._reject = function (reason, carriedStackTrace) {
- if (this._isFollowingOrFulfilledOrRejected()) return;
- this._rejectUnchecked(reason, carriedStackTrace);
- };
- Promise.prototype._settlePromiseAt = function (index) {
- var promise = this._promiseAt(index);
- var isPromise = promise instanceof Promise;
- if (isPromise && promise._isMigrated()) {
- promise._unsetIsMigrated();
- return async.invoke(this._settlePromiseAt, this, index);
- }
- var handler = this._isFulfilled()
- ? this._fulfillmentHandlerAt(index)
- : this._rejectionHandlerAt(index);
- var carriedStackTrace =
- this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
- var value = this._settledValue;
- var receiver = this._receiverAt(index);
- this._clearCallbackDataAtIndex(index);
- if (typeof handler === "function") {
- if (!isPromise) {
- handler.call(receiver, value, promise);
- } else {
- this._settlePromiseFromHandler(handler, receiver, value, promise);
- }
- } else if (receiver instanceof PromiseArray) {
- if (!receiver._isResolved()) {
- if (this._isFulfilled()) {
- receiver._promiseFulfilled(value, promise);
- }
- else {
- receiver._promiseRejected(value, promise);
- }
- }
- } else if (isPromise) {
- if (this._isFulfilled()) {
- promise._fulfill(value);
- } else {
- promise._reject(value, carriedStackTrace);
- }
- }
- if (index >= 4 && (index & 31) === 4)
- async.invokeLater(this._setLength, this, 0);
- };
- Promise.prototype._clearCallbackDataAtIndex = function(index) {
- if (index === 0) {
- if (!this._isCarryingStackTrace()) {
- this._fulfillmentHandler0 = undefined;
- }
- this._rejectionHandler0 =
- this._progressHandler0 =
- this._receiver0 =
- this._promise0 = undefined;
- } else {
- var base = index * 5 - 5;
- this[base + 3] =
- this[base + 4] =
- this[base + 0] =
- this[base + 1] =
- this[base + 2] = undefined;
- }
- };
- Promise.prototype._isSettlePromisesQueued = function () {
- return (this._bitField &
- -1073741824) === -1073741824;
- };
- Promise.prototype._setSettlePromisesQueued = function () {
- this._bitField = this._bitField | -1073741824;
- };
- Promise.prototype._unsetSettlePromisesQueued = function () {
- this._bitField = this._bitField & (~-1073741824);
- };
- Promise.prototype._queueSettlePromises = function() {
- async.settlePromises(this);
- this._setSettlePromisesQueued();
- };
- Promise.prototype._fulfillUnchecked = function (value) {
- if (value === this) {
- var err = makeSelfResolutionError();
- this._attachExtraTrace(err);
- return this._rejectUnchecked(err, undefined);
- }
- this._setFulfilled();
- this._settledValue = value;
- this._cleanValues();
- if (this._length() > 0) {
- this._queueSettlePromises();
- }
- };
- Promise.prototype._rejectUncheckedCheckError = function (reason) {
- var trace = util.ensureErrorObject(reason);
- this._rejectUnchecked(reason, trace === reason ? undefined : trace);
- };
- Promise.prototype._rejectUnchecked = function (reason, trace) {
- if (reason === this) {
- var err = makeSelfResolutionError();
- this._attachExtraTrace(err);
- return this._rejectUnchecked(err);
- }
- this._setRejected();
- this._settledValue = reason;
- this._cleanValues();
- if (this._isFinal()) {
- async.throwLater(function(e) {
- if ("stack" in e) {
- async.invokeFirst(
- CapturedTrace.unhandledRejection, undefined, e);
- }
- throw e;
- }, trace === undefined ? reason : trace);
- return;
- }
- if (trace !== undefined && trace !== reason) {
- this._setCarriedStackTrace(trace);
- }
- if (this._length() > 0) {
- this._queueSettlePromises();
- } else {
- this._ensurePossibleRejectionHandled();
- }
- };
- Promise.prototype._settlePromises = function () {
- this._unsetSettlePromisesQueued();
- var len = this._length();
- for (var i = 0; i < len; i++) {
- this._settlePromiseAt(i);
- }
- };
- util.notEnumerableProp(Promise,
- "_makeSelfResolutionError",
- makeSelfResolutionError);
- _dereq_("./progress.js")(Promise, PromiseArray);
- _dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
- _dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
- _dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
- _dereq_("./direct_resolve.js")(Promise);
- _dereq_("./synchronous_inspection.js")(Promise);
- _dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
- Promise.version = "2.11.0";
- Promise.Promise = Promise;
- _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
- _dereq_('./cancel.js')(Promise);
- _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
- _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
- _dereq_('./nodeify.js')(Promise);
- _dereq_('./call_get.js')(Promise);
- _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
- _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
- _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
- _dereq_('./settle.js')(Promise, PromiseArray);
- _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
- _dereq_('./promisify.js')(Promise, INTERNAL);
- _dereq_('./any.js')(Promise);
- _dereq_('./each.js')(Promise, INTERNAL);
- _dereq_('./timers.js')(Promise, INTERNAL);
- _dereq_('./filter.js')(Promise, INTERNAL);
-
- util.toFastProperties(Promise);
- util.toFastProperties(Promise.prototype);
- function fillTypes(value) {
- var p = new Promise(INTERNAL);
- p._fulfillmentHandler0 = value;
- p._rejectionHandler0 = value;
- p._progressHandler0 = value;
- p._promise0 = value;
- p._receiver0 = value;
- p._settledValue = value;
- }
- // Complete slack tracking, opt out of field-type tracking and
- // stabilize map
- fillTypes({a: 1});
- fillTypes({b: 2});
- fillTypes({c: 3});
- fillTypes(1);
- fillTypes(function(){});
- fillTypes(undefined);
- fillTypes(false);
- fillTypes(new Promise(INTERNAL));
- CapturedTrace.setBounds(async.firstLineError, util.lastLineError);
- return Promise;
- };
- },{"./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){
- "use strict";
- module.exports = function(Promise, INTERNAL, tryConvertToPromise,
- apiRejection) {
- var util = _dereq_("./util.js");
- var isArray = util.isArray;
- function toResolutionValue(val) {
- switch(val) {
- case -2: return [];
- case -3: return {};
- }
- }
- function PromiseArray(values) {
- var promise = this._promise = new Promise(INTERNAL);
- var parent;
- if (values instanceof Promise) {
- parent = values;
- promise._propagateFrom(parent, 1 | 4);
- }
- this._values = values;
- this._length = 0;
- this._totalResolved = 0;
- this._init(undefined, -2);
- }
- PromiseArray.prototype.length = function () {
- return this._length;
- };
- PromiseArray.prototype.promise = function () {
- return this._promise;
- };
- PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
- var values = tryConvertToPromise(this._values, this._promise);
- if (values instanceof Promise) {
- values = values._target();
- this._values = values;
- if (values._isFulfilled()) {
- values = values._value();
- if (!isArray(values)) {
- var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
- this.__hardReject__(err);
- return;
- }
- } else if (values._isPending()) {
- values._then(
- init,
- this._reject,
- undefined,
- this,
- resolveValueIfEmpty
- );
- return;
- } else {
- this._reject(values._reason());
- return;
- }
- } else if (!isArray(values)) {
- this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason());
- return;
- }
- if (values.length === 0) {
- if (resolveValueIfEmpty === -5) {
- this._resolveEmptyArray();
- }
- else {
- this._resolve(toResolutionValue(resolveValueIfEmpty));
- }
- return;
- }
- var len = this.getActualLength(values.length);
- this._length = len;
- this._values = this.shouldCopyValues() ? new Array(len) : this._values;
- var promise = this._promise;
- for (var i = 0; i < len; ++i) {
- var isResolved = this._isResolved();
- var maybePromise = tryConvertToPromise(values[i], promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- if (isResolved) {
- maybePromise._ignoreRejections();
- } else if (maybePromise._isPending()) {
- maybePromise._proxyPromiseArray(this, i);
- } else if (maybePromise._isFulfilled()) {
- this._promiseFulfilled(maybePromise._value(), i);
- } else {
- this._promiseRejected(maybePromise._reason(), i);
- }
- } else if (!isResolved) {
- this._promiseFulfilled(maybePromise, i);
- }
- }
- };
- PromiseArray.prototype._isResolved = function () {
- return this._values === null;
- };
- PromiseArray.prototype._resolve = function (value) {
- this._values = null;
- this._promise._fulfill(value);
- };
- PromiseArray.prototype.__hardReject__ =
- PromiseArray.prototype._reject = function (reason) {
- this._values = null;
- this._promise._rejectCallback(reason, false, true);
- };
- PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
- this._promise._progress({
- index: index,
- value: progressValue
- });
- };
- PromiseArray.prototype._promiseFulfilled = function (value, index) {
- this._values[index] = value;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- this._resolve(this._values);
- }
- };
- PromiseArray.prototype._promiseRejected = function (reason, index) {
- this._totalResolved++;
- this._reject(reason);
- };
- PromiseArray.prototype.shouldCopyValues = function () {
- return true;
- };
- PromiseArray.prototype.getActualLength = function (len) {
- return len;
- };
- return PromiseArray;
- };
- },{"./util.js":38}],25:[function(_dereq_,module,exports){
- "use strict";
- var util = _dereq_("./util.js");
- var maybeWrapAsError = util.maybeWrapAsError;
- var errors = _dereq_("./errors.js");
- var TimeoutError = errors.TimeoutError;
- var OperationalError = errors.OperationalError;
- var haveGetters = util.haveGetters;
- var es5 = _dereq_("./es5.js");
- function isUntypedError(obj) {
- return obj instanceof Error &&
- es5.getPrototypeOf(obj) === Error.prototype;
- }
- var rErrorKey = /^(?:name|message|stack|cause)$/;
- function wrapAsOperationalError(obj) {
- var ret;
- if (isUntypedError(obj)) {
- ret = new OperationalError(obj);
- ret.name = obj.name;
- ret.message = obj.message;
- ret.stack = obj.stack;
- var keys = es5.keys(obj);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (!rErrorKey.test(key)) {
- ret[key] = obj[key];
- }
- }
- return ret;
- }
- util.markAsOriginatingFromRejection(obj);
- return obj;
- }
- function nodebackForPromise(promise) {
- return function(err, value) {
- if (promise === null) return;
- if (err) {
- var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
- promise._attachExtraTrace(wrapped);
- promise._reject(wrapped);
- } else if (arguments.length > 2) {
- var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
- promise._fulfill(args);
- } else {
- promise._fulfill(value);
- }
- promise = null;
- };
- }
- var PromiseResolver;
- if (!haveGetters) {
- PromiseResolver = function (promise) {
- this.promise = promise;
- this.asCallback = nodebackForPromise(promise);
- this.callback = this.asCallback;
- };
- }
- else {
- PromiseResolver = function (promise) {
- this.promise = promise;
- };
- }
- if (haveGetters) {
- var prop = {
- get: function() {
- return nodebackForPromise(this.promise);
- }
- };
- es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
- es5.defineProperty(PromiseResolver.prototype, "callback", prop);
- }
- PromiseResolver._nodebackForPromise = nodebackForPromise;
- PromiseResolver.prototype.toString = function () {
- return "[object PromiseResolver]";
- };
- PromiseResolver.prototype.resolve =
- PromiseResolver.prototype.fulfill = function (value) {
- if (!(this instanceof PromiseResolver)) {
- 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");
- }
- this.promise._resolveCallback(value);
- };
- PromiseResolver.prototype.reject = function (reason) {
- if (!(this instanceof PromiseResolver)) {
- 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");
- }
- this.promise._rejectCallback(reason);
- };
- PromiseResolver.prototype.progress = function (value) {
- if (!(this instanceof PromiseResolver)) {
- 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");
- }
- this.promise._progress(value);
- };
- PromiseResolver.prototype.cancel = function (err) {
- this.promise.cancel(err);
- };
- PromiseResolver.prototype.timeout = function () {
- this.reject(new TimeoutError("timeout"));
- };
- PromiseResolver.prototype.isResolved = function () {
- return this.promise.isResolved();
- };
- PromiseResolver.prototype.toJSON = function () {
- return this.promise.toJSON();
- };
- module.exports = PromiseResolver;
- },{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var THIS = {};
- var util = _dereq_("./util.js");
- var nodebackForPromise = _dereq_("./promise_resolver.js")
- ._nodebackForPromise;
- var withAppended = util.withAppended;
- var maybeWrapAsError = util.maybeWrapAsError;
- var canEvaluate = util.canEvaluate;
- var TypeError = _dereq_("./errors").TypeError;
- var defaultSuffix = "Async";
- var defaultPromisified = {__isPromisified__: true};
- var noCopyProps = [
- "arity", "length",
- "name",
- "arguments",
- "caller",
- "callee",
- "prototype",
- "__isPromisified__"
- ];
- var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
- var defaultFilter = function(name) {
- return util.isIdentifier(name) &&
- name.charAt(0) !== "_" &&
- name !== "constructor";
- };
- function propsFilter(key) {
- return !noCopyPropsPattern.test(key);
- }
- function isPromisified(fn) {
- try {
- return fn.__isPromisified__ === true;
- }
- catch (e) {
- return false;
- }
- }
- function hasPromisified(obj, key, suffix) {
- var val = util.getDataPropertyOrDefault(obj, key + suffix,
- defaultPromisified);
- return val ? isPromisified(val) : false;
- }
- function checkValid(ret, suffix, suffixRegexp) {
- for (var i = 0; i < ret.length; i += 2) {
- var key = ret[i];
- if (suffixRegexp.test(key)) {
- var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
- for (var j = 0; j < ret.length; j += 2) {
- if (ret[j] === keyWithoutAsyncSuffix) {
- throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a"
- .replace("%s", suffix));
- }
- }
- }
- }
- }
- function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
- var keys = util.inheritedDataKeys(obj);
- var ret = [];
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- var value = obj[key];
- var passesDefaultFilter = filter === defaultFilter
- ? true : defaultFilter(key, value, obj);
- if (typeof value === "function" &&
- !isPromisified(value) &&
- !hasPromisified(obj, key, suffix) &&
- filter(key, value, obj, passesDefaultFilter)) {
- ret.push(key, value);
- }
- }
- checkValid(ret, suffix, suffixRegexp);
- return ret;
- }
- var escapeIdentRegex = function(str) {
- return str.replace(/([$])/, "\\$");
- };
- var makeNodePromisifiedEval;
- if (!true) {
- var switchCaseArgumentOrder = function(likelyArgumentCount) {
- var ret = [likelyArgumentCount];
- var min = Math.max(0, likelyArgumentCount - 1 - 3);
- for(var i = likelyArgumentCount - 1; i >= min; --i) {
- ret.push(i);
- }
- for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
- ret.push(i);
- }
- return ret;
- };
- var argumentSequence = function(argumentCount) {
- return util.filledRange(argumentCount, "_arg", "");
- };
- var parameterDeclaration = function(parameterCount) {
- return util.filledRange(
- Math.max(parameterCount, 3), "_arg", "");
- };
- var parameterCount = function(fn) {
- if (typeof fn.length === "number") {
- return Math.max(Math.min(fn.length, 1023 + 1), 0);
- }
- return 0;
- };
- makeNodePromisifiedEval =
- function(callback, receiver, originalName, fn) {
- var newParameterCount = Math.max(0, parameterCount(fn) - 1);
- var argumentOrder = switchCaseArgumentOrder(newParameterCount);
- var shouldProxyThis = typeof callback === "string" || receiver === THIS;
- function generateCallForArgumentCount(count) {
- var args = argumentSequence(count).join(", ");
- var comma = count > 0 ? ", " : "";
- var ret;
- if (shouldProxyThis) {
- ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
- } else {
- ret = receiver === undefined
- ? "ret = callback({{args}}, nodeback); break;\n"
- : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
- }
- return ret.replace("{{args}}", args).replace(", ", comma);
- }
- function generateArgumentSwitchCase() {
- var ret = "";
- for (var i = 0; i < argumentOrder.length; ++i) {
- ret += "case " + argumentOrder[i] +":" +
- generateCallForArgumentCount(argumentOrder[i]);
- }
- ret += " \n\
- default: \n\
- var args = new Array(len + 1); \n\
- var i = 0; \n\
- for (var i = 0; i < len; ++i) { \n\
- args[i] = arguments[i]; \n\
- } \n\
- args[i] = nodeback; \n\
- [CodeForCall] \n\
- break; \n\
- ".replace("[CodeForCall]", (shouldProxyThis
- ? "ret = callback.apply(this, args);\n"
- : "ret = callback.apply(receiver, args);\n"));
- return ret;
- }
- var getFunctionCode = typeof callback === "string"
- ? ("this != null ? this['"+callback+"'] : fn")
- : "fn";
- return new Function("Promise",
- "fn",
- "receiver",
- "withAppended",
- "maybeWrapAsError",
- "nodebackForPromise",
- "tryCatch",
- "errorObj",
- "notEnumerableProp",
- "INTERNAL","'use strict'; \n\
- var ret = function (Parameters) { \n\
- 'use strict'; \n\
- var len = arguments.length; \n\
- var promise = new Promise(INTERNAL); \n\
- promise._captureStackTrace(); \n\
- var nodeback = nodebackForPromise(promise); \n\
- var ret; \n\
- var callback = tryCatch([GetFunctionCode]); \n\
- switch(len) { \n\
- [CodeForSwitchCase] \n\
- } \n\
- if (ret === errorObj) { \n\
- promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
- } \n\
- return promise; \n\
- }; \n\
- notEnumerableProp(ret, '__isPromisified__', true); \n\
- return ret; \n\
- "
- .replace("Parameters", parameterDeclaration(newParameterCount))
- .replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
- .replace("[GetFunctionCode]", getFunctionCode))(
- Promise,
- fn,
- receiver,
- withAppended,
- maybeWrapAsError,
- nodebackForPromise,
- util.tryCatch,
- util.errorObj,
- util.notEnumerableProp,
- INTERNAL
- );
- };
- }
- function makeNodePromisifiedClosure(callback, receiver, _, fn) {
- var defaultThis = (function() {return this;})();
- var method = callback;
- if (typeof method === "string") {
- callback = fn;
- }
- function promisified() {
- var _receiver = receiver;
- if (receiver === THIS) _receiver = this;
- var promise = new Promise(INTERNAL);
- promise._captureStackTrace();
- var cb = typeof method === "string" && this !== defaultThis
- ? this[method] : callback;
- var fn = nodebackForPromise(promise);
- try {
- cb.apply(_receiver, withAppended(arguments, fn));
- } catch(e) {
- promise._rejectCallback(maybeWrapAsError(e), true, true);
- }
- return promise;
- }
- util.notEnumerableProp(promisified, "__isPromisified__", true);
- return promisified;
- }
- var makeNodePromisified = canEvaluate
- ? makeNodePromisifiedEval
- : makeNodePromisifiedClosure;
- function promisifyAll(obj, suffix, filter, promisifier) {
- var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
- var methods =
- promisifiableMethods(obj, suffix, suffixRegexp, filter);
- for (var i = 0, len = methods.length; i < len; i+= 2) {
- var key = methods[i];
- var fn = methods[i+1];
- var promisifiedKey = key + suffix;
- if (promisifier === makeNodePromisified) {
- obj[promisifiedKey] =
- makeNodePromisified(key, THIS, key, fn, suffix);
- } else {
- var promisified = promisifier(fn, function() {
- return makeNodePromisified(key, THIS, key, fn, suffix);
- });
- util.notEnumerableProp(promisified, "__isPromisified__", true);
- obj[promisifiedKey] = promisified;
- }
- }
- util.toFastProperties(obj);
- return obj;
- }
- function promisify(callback, receiver) {
- return makeNodePromisified(callback, receiver, undefined, callback);
- }
- Promise.promisify = function (fn, receiver) {
- if (typeof fn !== "function") {
- throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- }
- if (isPromisified(fn)) {
- return fn;
- }
- var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
- util.copyDescriptors(fn, ret, propsFilter);
- return ret;
- };
- Promise.promisifyAll = function (target, options) {
- if (typeof target !== "function" && typeof target !== "object") {
- throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a");
- }
- options = Object(options);
- var suffix = options.suffix;
- if (typeof suffix !== "string") suffix = defaultSuffix;
- var filter = options.filter;
- if (typeof filter !== "function") filter = defaultFilter;
- var promisifier = options.promisifier;
- if (typeof promisifier !== "function") promisifier = makeNodePromisified;
- if (!util.isIdentifier(suffix)) {
- throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a");
- }
- var keys = util.inheritedDataKeys(target);
- for (var i = 0; i < keys.length; ++i) {
- var value = target[keys[i]];
- if (keys[i] !== "constructor" &&
- util.isClass(value)) {
- promisifyAll(value.prototype, suffix, filter, promisifier);
- promisifyAll(value, suffix, filter, promisifier);
- }
- }
- return promisifyAll(target, suffix, filter, promisifier);
- };
- };
- },{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(
- Promise, PromiseArray, tryConvertToPromise, apiRejection) {
- var util = _dereq_("./util.js");
- var isObject = util.isObject;
- var es5 = _dereq_("./es5.js");
- function PropertiesPromiseArray(obj) {
- var keys = es5.keys(obj);
- var len = keys.length;
- var values = new Array(len * 2);
- for (var i = 0; i < len; ++i) {
- var key = keys[i];
- values[i] = obj[key];
- values[i + len] = key;
- }
- this.constructor$(values);
- }
- util.inherits(PropertiesPromiseArray, PromiseArray);
- PropertiesPromiseArray.prototype._init = function () {
- this._init$(undefined, -3) ;
- };
- PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
- this._values[index] = value;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- var val = {};
- var keyOffset = this.length();
- for (var i = 0, len = this.length(); i < len; ++i) {
- val[this._values[i + keyOffset]] = this._values[i];
- }
- this._resolve(val);
- }
- };
- PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
- this._promise._progress({
- key: this._values[index + this.length()],
- value: value
- });
- };
- PropertiesPromiseArray.prototype.shouldCopyValues = function () {
- return false;
- };
- PropertiesPromiseArray.prototype.getActualLength = function (len) {
- return len >> 1;
- };
- function props(promises) {
- var ret;
- var castValue = tryConvertToPromise(promises);
- if (!isObject(castValue)) {
- return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
- } else if (castValue instanceof Promise) {
- ret = castValue._then(
- Promise.props, undefined, undefined, undefined, undefined);
- } else {
- ret = new PropertiesPromiseArray(castValue).promise();
- }
- if (castValue instanceof Promise) {
- ret._propagateFrom(castValue, 4);
- }
- return ret;
- }
- Promise.prototype.props = function () {
- return props(this);
- };
- Promise.props = function (promises) {
- return props(promises);
- };
- };
- },{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
- "use strict";
- function arrayMove(src, srcIndex, dst, dstIndex, len) {
- for (var j = 0; j < len; ++j) {
- dst[j + dstIndex] = src[j + srcIndex];
- src[j + srcIndex] = void 0;
- }
- }
- function Queue(capacity) {
- this._capacity = capacity;
- this._length = 0;
- this._front = 0;
- }
- Queue.prototype._willBeOverCapacity = function (size) {
- return this._capacity < size;
- };
- Queue.prototype._pushOne = function (arg) {
- var length = this.length();
- this._checkCapacity(length + 1);
- var i = (this._front + length) & (this._capacity - 1);
- this[i] = arg;
- this._length = length + 1;
- };
- Queue.prototype._unshiftOne = function(value) {
- var capacity = this._capacity;
- this._checkCapacity(this.length() + 1);
- var front = this._front;
- var i = (((( front - 1 ) &
- ( capacity - 1) ) ^ capacity ) - capacity );
- this[i] = value;
- this._front = i;
- this._length = this.length() + 1;
- };
- Queue.prototype.unshift = function(fn, receiver, arg) {
- this._unshiftOne(arg);
- this._unshiftOne(receiver);
- this._unshiftOne(fn);
- };
- Queue.prototype.push = function (fn, receiver, arg) {
- var length = this.length() + 3;
- if (this._willBeOverCapacity(length)) {
- this._pushOne(fn);
- this._pushOne(receiver);
- this._pushOne(arg);
- return;
- }
- var j = this._front + length - 3;
- this._checkCapacity(length);
- var wrapMask = this._capacity - 1;
- this[(j + 0) & wrapMask] = fn;
- this[(j + 1) & wrapMask] = receiver;
- this[(j + 2) & wrapMask] = arg;
- this._length = length;
- };
- Queue.prototype.shift = function () {
- var front = this._front,
- ret = this[front];
- this[front] = undefined;
- this._front = (front + 1) & (this._capacity - 1);
- this._length--;
- return ret;
- };
- Queue.prototype.length = function () {
- return this._length;
- };
- Queue.prototype._checkCapacity = function (size) {
- if (this._capacity < size) {
- this._resizeTo(this._capacity << 1);
- }
- };
- Queue.prototype._resizeTo = function (capacity) {
- var oldCapacity = this._capacity;
- this._capacity = capacity;
- var front = this._front;
- var length = this._length;
- var moveItemsCount = (front + length) & (oldCapacity - 1);
- arrayMove(this, 0, this, oldCapacity, moveItemsCount);
- };
- module.exports = Queue;
- },{}],29:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(
- Promise, INTERNAL, tryConvertToPromise, apiRejection) {
- var isArray = _dereq_("./util.js").isArray;
- var raceLater = function (promise) {
- return promise.then(function(array) {
- return race(array, promise);
- });
- };
- function race(promises, parent) {
- var maybePromise = tryConvertToPromise(promises);
- if (maybePromise instanceof Promise) {
- return raceLater(maybePromise);
- } else if (!isArray(promises)) {
- return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
- }
- var ret = new Promise(INTERNAL);
- if (parent !== undefined) {
- ret._propagateFrom(parent, 4 | 1);
- }
- var fulfill = ret._fulfill;
- var reject = ret._reject;
- for (var i = 0, len = promises.length; i < len; ++i) {
- var val = promises[i];
- if (val === undefined && !(i in promises)) {
- continue;
- }
- Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
- }
- return ret;
- }
- Promise.race = function (promises) {
- return race(promises, undefined);
- };
- Promise.prototype.race = function () {
- return race(this, undefined);
- };
- };
- },{"./util.js":38}],30:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise,
- PromiseArray,
- apiRejection,
- tryConvertToPromise,
- INTERNAL) {
- var getDomain = Promise._getDomain;
- var async = _dereq_("./async.js");
- var util = _dereq_("./util.js");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- function ReductionPromiseArray(promises, fn, accum, _each) {
- this.constructor$(promises);
- this._promise._captureStackTrace();
- this._preservedValues = _each === INTERNAL ? [] : null;
- this._zerothIsAccum = (accum === undefined);
- this._gotAccum = false;
- this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
- this._valuesPhase = undefined;
- var maybePromise = tryConvertToPromise(accum, this._promise);
- var rejected = false;
- var isPromise = maybePromise instanceof Promise;
- if (isPromise) {
- maybePromise = maybePromise._target();
- if (maybePromise._isPending()) {
- maybePromise._proxyPromiseArray(this, -1);
- } else if (maybePromise._isFulfilled()) {
- accum = maybePromise._value();
- this._gotAccum = true;
- } else {
- this._reject(maybePromise._reason());
- rejected = true;
- }
- }
- if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
- var domain = getDomain();
- this._callback = domain === null ? fn : domain.bind(fn);
- this._accum = accum;
- if (!rejected) async.invoke(init, this, undefined);
- }
- function init() {
- this._init$(undefined, -5);
- }
- util.inherits(ReductionPromiseArray, PromiseArray);
- ReductionPromiseArray.prototype._init = function () {};
- ReductionPromiseArray.prototype._resolveEmptyArray = function () {
- if (this._gotAccum || this._zerothIsAccum) {
- this._resolve(this._preservedValues !== null
- ? [] : this._accum);
- }
- };
- ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var values = this._values;
- values[index] = value;
- var length = this.length();
- var preservedValues = this._preservedValues;
- var isEach = preservedValues !== null;
- var gotAccum = this._gotAccum;
- var valuesPhase = this._valuesPhase;
- var valuesPhaseIndex;
- if (!valuesPhase) {
- valuesPhase = this._valuesPhase = new Array(length);
- for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
- valuesPhase[valuesPhaseIndex] = 0;
- }
- }
- valuesPhaseIndex = valuesPhase[index];
- if (index === 0 && this._zerothIsAccum) {
- this._accum = value;
- this._gotAccum = gotAccum = true;
- valuesPhase[index] = ((valuesPhaseIndex === 0)
- ? 1 : 2);
- } else if (index === -1) {
- this._accum = value;
- this._gotAccum = gotAccum = true;
- } else {
- if (valuesPhaseIndex === 0) {
- valuesPhase[index] = 1;
- } else {
- valuesPhase[index] = 2;
- this._accum = value;
- }
- }
- if (!gotAccum) return;
- var callback = this._callback;
- var receiver = this._promise._boundValue();
- var ret;
- for (var i = this._reducingIndex; i < length; ++i) {
- valuesPhaseIndex = valuesPhase[i];
- if (valuesPhaseIndex === 2) {
- this._reducingIndex = i + 1;
- continue;
- }
- if (valuesPhaseIndex !== 1) return;
- value = values[i];
- this._promise._pushContext();
- if (isEach) {
- preservedValues.push(value);
- ret = tryCatch(callback).call(receiver, value, i, length);
- }
- else {
- ret = tryCatch(callback)
- .call(receiver, this._accum, value, i, length);
- }
- this._promise._popContext();
- if (ret === errorObj) return this._reject(ret.e);
- var maybePromise = tryConvertToPromise(ret, this._promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- if (maybePromise._isPending()) {
- valuesPhase[i] = 4;
- return maybePromise._proxyPromiseArray(this, i);
- } else if (maybePromise._isFulfilled()) {
- ret = maybePromise._value();
- } else {
- return this._reject(maybePromise._reason());
- }
- }
- this._reducingIndex = i + 1;
- this._accum = ret;
- }
- this._resolve(isEach ? preservedValues : this._accum);
- };
- function reduce(promises, fn, initialValue, _each) {
- if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
- return array.promise();
- }
- Promise.prototype.reduce = function (fn, initialValue) {
- return reduce(this, fn, initialValue, null);
- };
- Promise.reduce = function (promises, fn, initialValue, _each) {
- return reduce(promises, fn, initialValue, _each);
- };
- };
- },{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
- "use strict";
- var schedule;
- var util = _dereq_("./util");
- var noAsyncScheduler = function() {
- throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
- };
- if (util.isNode && typeof MutationObserver === "undefined") {
- var GlobalSetImmediate = global.setImmediate;
- var ProcessNextTick = process.nextTick;
- schedule = util.isRecentNode
- ? function(fn) { GlobalSetImmediate.call(global, fn); }
- : function(fn) { ProcessNextTick.call(process, fn); };
- } else if ((typeof MutationObserver !== "undefined") &&
- !(typeof window !== "undefined" &&
- window.navigator &&
- window.navigator.standalone)) {
- schedule = function(fn) {
- var div = document.createElement("div");
- var observer = new MutationObserver(fn);
- observer.observe(div, {attributes: true});
- return function() { div.classList.toggle("foo"); };
- };
- schedule.isStatic = true;
- } else if (typeof setImmediate !== "undefined") {
- schedule = function (fn) {
- setImmediate(fn);
- };
- } else if (typeof setTimeout !== "undefined") {
- schedule = function (fn) {
- setTimeout(fn, 0);
- };
- } else {
- schedule = noAsyncScheduler;
- }
- module.exports = schedule;
- },{"./util":38}],32:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray) {
- var PromiseInspection = Promise.PromiseInspection;
- var util = _dereq_("./util.js");
- function SettledPromiseArray(values) {
- this.constructor$(values);
- }
- util.inherits(SettledPromiseArray, PromiseArray);
- SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
- this._values[index] = inspection;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- this._resolve(this._values);
- }
- };
- SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var ret = new PromiseInspection();
- ret._bitField = 268435456;
- ret._settledValue = value;
- this._promiseResolved(index, ret);
- };
- SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
- var ret = new PromiseInspection();
- ret._bitField = 134217728;
- ret._settledValue = reason;
- this._promiseResolved(index, ret);
- };
- Promise.settle = function (promises) {
- return new SettledPromiseArray(promises).promise();
- };
- Promise.prototype.settle = function () {
- return new SettledPromiseArray(this).promise();
- };
- };
- },{"./util.js":38}],33:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, apiRejection) {
- var util = _dereq_("./util.js");
- var RangeError = _dereq_("./errors.js").RangeError;
- var AggregateError = _dereq_("./errors.js").AggregateError;
- var isArray = util.isArray;
- function SomePromiseArray(values) {
- this.constructor$(values);
- this._howMany = 0;
- this._unwrap = false;
- this._initialized = false;
- }
- util.inherits(SomePromiseArray, PromiseArray);
- SomePromiseArray.prototype._init = function () {
- if (!this._initialized) {
- return;
- }
- if (this._howMany === 0) {
- this._resolve([]);
- return;
- }
- this._init$(undefined, -5);
- var isArrayResolved = isArray(this._values);
- if (!this._isResolved() &&
- isArrayResolved &&
- this._howMany > this._canPossiblyFulfill()) {
- this._reject(this._getRangeError(this.length()));
- }
- };
- SomePromiseArray.prototype.init = function () {
- this._initialized = true;
- this._init();
- };
- SomePromiseArray.prototype.setUnwrap = function () {
- this._unwrap = true;
- };
- SomePromiseArray.prototype.howMany = function () {
- return this._howMany;
- };
- SomePromiseArray.prototype.setHowMany = function (count) {
- this._howMany = count;
- };
- SomePromiseArray.prototype._promiseFulfilled = function (value) {
- this._addFulfilled(value);
- if (this._fulfilled() === this.howMany()) {
- this._values.length = this.howMany();
- if (this.howMany() === 1 && this._unwrap) {
- this._resolve(this._values[0]);
- } else {
- this._resolve(this._values);
- }
- }
- };
- SomePromiseArray.prototype._promiseRejected = function (reason) {
- this._addRejected(reason);
- if (this.howMany() > this._canPossiblyFulfill()) {
- var e = new AggregateError();
- for (var i = this.length(); i < this._values.length; ++i) {
- e.push(this._values[i]);
- }
- this._reject(e);
- }
- };
- SomePromiseArray.prototype._fulfilled = function () {
- return this._totalResolved;
- };
- SomePromiseArray.prototype._rejected = function () {
- return this._values.length - this.length();
- };
- SomePromiseArray.prototype._addRejected = function (reason) {
- this._values.push(reason);
- };
- SomePromiseArray.prototype._addFulfilled = function (value) {
- this._values[this._totalResolved++] = value;
- };
- SomePromiseArray.prototype._canPossiblyFulfill = function () {
- return this.length() - this._rejected();
- };
- SomePromiseArray.prototype._getRangeError = function (count) {
- var message = "Input array must contain at least " +
- this._howMany + " items but contains only " + count + " items";
- return new RangeError(message);
- };
- SomePromiseArray.prototype._resolveEmptyArray = function () {
- this._reject(this._getRangeError(0));
- };
- function some(promises, howMany) {
- if ((howMany | 0) !== howMany || howMany < 0) {
- return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a");
- }
- var ret = new SomePromiseArray(promises);
- var promise = ret.promise();
- ret.setHowMany(howMany);
- ret.init();
- return promise;
- }
- Promise.some = function (promises, howMany) {
- return some(promises, howMany);
- };
- Promise.prototype.some = function (howMany) {
- return some(this, howMany);
- };
- Promise._SomePromiseArray = SomePromiseArray;
- };
- },{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- function PromiseInspection(promise) {
- if (promise !== undefined) {
- promise = promise._target();
- this._bitField = promise._bitField;
- this._settledValue = promise._settledValue;
- }
- else {
- this._bitField = 0;
- this._settledValue = undefined;
- }
- }
- PromiseInspection.prototype.value = function () {
- if (!this.isFulfilled()) {
- throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
- }
- return this._settledValue;
- };
- PromiseInspection.prototype.error =
- PromiseInspection.prototype.reason = function () {
- if (!this.isRejected()) {
- throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
- }
- return this._settledValue;
- };
- PromiseInspection.prototype.isFulfilled =
- Promise.prototype._isFulfilled = function () {
- return (this._bitField & 268435456) > 0;
- };
- PromiseInspection.prototype.isRejected =
- Promise.prototype._isRejected = function () {
- return (this._bitField & 134217728) > 0;
- };
- PromiseInspection.prototype.isPending =
- Promise.prototype._isPending = function () {
- return (this._bitField & 402653184) === 0;
- };
- PromiseInspection.prototype.isResolved =
- Promise.prototype._isResolved = function () {
- return (this._bitField & 402653184) > 0;
- };
- Promise.prototype.isPending = function() {
- return this._target()._isPending();
- };
- Promise.prototype.isRejected = function() {
- return this._target()._isRejected();
- };
- Promise.prototype.isFulfilled = function() {
- return this._target()._isFulfilled();
- };
- Promise.prototype.isResolved = function() {
- return this._target()._isResolved();
- };
- Promise.prototype._value = function() {
- return this._settledValue;
- };
- Promise.prototype._reason = function() {
- this._unsetRejectionIsUnhandled();
- return this._settledValue;
- };
- Promise.prototype.value = function() {
- var target = this._target();
- if (!target.isFulfilled()) {
- throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
- }
- return target._settledValue;
- };
- Promise.prototype.reason = function() {
- var target = this._target();
- if (!target.isRejected()) {
- throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
- }
- target._unsetRejectionIsUnhandled();
- return target._settledValue;
- };
- Promise.PromiseInspection = PromiseInspection;
- };
- },{}],35:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var util = _dereq_("./util.js");
- var errorObj = util.errorObj;
- var isObject = util.isObject;
- function tryConvertToPromise(obj, context) {
- if (isObject(obj)) {
- if (obj instanceof Promise) {
- return obj;
- }
- else if (isAnyBluebirdPromise(obj)) {
- var ret = new Promise(INTERNAL);
- obj._then(
- ret._fulfillUnchecked,
- ret._rejectUncheckedCheckError,
- ret._progressUnchecked,
- ret,
- null
- );
- return ret;
- }
- var then = util.tryCatch(getThen)(obj);
- if (then === errorObj) {
- if (context) context._pushContext();
- var ret = Promise.reject(then.e);
- if (context) context._popContext();
- return ret;
- } else if (typeof then === "function") {
- return doThenable(obj, then, context);
- }
- }
- return obj;
- }
- function getThen(obj) {
- return obj.then;
- }
- var hasProp = {}.hasOwnProperty;
- function isAnyBluebirdPromise(obj) {
- return hasProp.call(obj, "_promise0");
- }
- function doThenable(x, then, context) {
- var promise = new Promise(INTERNAL);
- var ret = promise;
- if (context) context._pushContext();
- promise._captureStackTrace();
- if (context) context._popContext();
- var synchronous = true;
- var result = util.tryCatch(then).call(x,
- resolveFromThenable,
- rejectFromThenable,
- progressFromThenable);
- synchronous = false;
- if (promise && result === errorObj) {
- promise._rejectCallback(result.e, true, true);
- promise = null;
- }
- function resolveFromThenable(value) {
- if (!promise) return;
- promise._resolveCallback(value);
- promise = null;
- }
- function rejectFromThenable(reason) {
- if (!promise) return;
- promise._rejectCallback(reason, synchronous, true);
- promise = null;
- }
- function progressFromThenable(value) {
- if (!promise) return;
- if (typeof promise._progress === "function") {
- promise._progress(value);
- }
- }
- return ret;
- }
- return tryConvertToPromise;
- };
- },{"./util.js":38}],36:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var util = _dereq_("./util.js");
- var TimeoutError = Promise.TimeoutError;
- var afterTimeout = function (promise, message) {
- if (!promise.isPending()) return;
-
- var err;
- if(!util.isPrimitive(message) && (message instanceof Error)) {
- err = message;
- } else {
- if (typeof message !== "string") {
- message = "operation timed out";
- }
- err = new TimeoutError(message);
- }
- util.markAsOriginatingFromRejection(err);
- promise._attachExtraTrace(err);
- promise._cancel(err);
- };
- var afterValue = function(value) { return delay(+this).thenReturn(value); };
- var delay = Promise.delay = function (value, ms) {
- if (ms === undefined) {
- ms = value;
- value = undefined;
- var ret = new Promise(INTERNAL);
- setTimeout(function() { ret._fulfill(); }, ms);
- return ret;
- }
- ms = +ms;
- return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
- };
- Promise.prototype.delay = function (ms) {
- return delay(this, ms);
- };
- function successClear(value) {
- var handle = this;
- if (handle instanceof Number) handle = +handle;
- clearTimeout(handle);
- return value;
- }
- function failureClear(reason) {
- var handle = this;
- if (handle instanceof Number) handle = +handle;
- clearTimeout(handle);
- throw reason;
- }
- Promise.prototype.timeout = function (ms, message) {
- ms = +ms;
- var ret = this.then().cancellable();
- ret._cancellationParent = this;
- var handle = setTimeout(function timeoutTimeout() {
- afterTimeout(ret, message);
- }, ms);
- return ret._then(successClear, failureClear, undefined, handle, undefined);
- };
- };
- },{"./util.js":38}],37:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function (Promise, apiRejection, tryConvertToPromise,
- createContext) {
- var TypeError = _dereq_("./errors.js").TypeError;
- var inherits = _dereq_("./util.js").inherits;
- var PromiseInspection = Promise.PromiseInspection;
- function inspectionMapper(inspections) {
- var len = inspections.length;
- for (var i = 0; i < len; ++i) {
- var inspection = inspections[i];
- if (inspection.isRejected()) {
- return Promise.reject(inspection.error());
- }
- inspections[i] = inspection._settledValue;
- }
- return inspections;
- }
- function thrower(e) {
- setTimeout(function(){throw e;}, 0);
- }
- function castPreservingDisposable(thenable) {
- var maybePromise = tryConvertToPromise(thenable);
- if (maybePromise !== thenable &&
- typeof thenable._isDisposable === "function" &&
- typeof thenable._getDisposer === "function" &&
- thenable._isDisposable()) {
- maybePromise._setDisposable(thenable._getDisposer());
- }
- return maybePromise;
- }
- function dispose(resources, inspection) {
- var i = 0;
- var len = resources.length;
- var ret = Promise.defer();
- function iterator() {
- if (i >= len) return ret.resolve();
- var maybePromise = castPreservingDisposable(resources[i++]);
- if (maybePromise instanceof Promise &&
- maybePromise._isDisposable()) {
- try {
- maybePromise = tryConvertToPromise(
- maybePromise._getDisposer().tryDispose(inspection),
- resources.promise);
- } catch (e) {
- return thrower(e);
- }
- if (maybePromise instanceof Promise) {
- return maybePromise._then(iterator, thrower,
- null, null, null);
- }
- }
- iterator();
- }
- iterator();
- return ret.promise;
- }
- function disposerSuccess(value) {
- var inspection = new PromiseInspection();
- inspection._settledValue = value;
- inspection._bitField = 268435456;
- return dispose(this, inspection).thenReturn(value);
- }
- function disposerFail(reason) {
- var inspection = new PromiseInspection();
- inspection._settledValue = reason;
- inspection._bitField = 134217728;
- return dispose(this, inspection).thenThrow(reason);
- }
- function Disposer(data, promise, context) {
- this._data = data;
- this._promise = promise;
- this._context = context;
- }
- Disposer.prototype.data = function () {
- return this._data;
- };
- Disposer.prototype.promise = function () {
- return this._promise;
- };
- Disposer.prototype.resource = function () {
- if (this.promise().isFulfilled()) {
- return this.promise().value();
- }
- return null;
- };
- Disposer.prototype.tryDispose = function(inspection) {
- var resource = this.resource();
- var context = this._context;
- if (context !== undefined) context._pushContext();
- var ret = resource !== null
- ? this.doDispose(resource, inspection) : null;
- if (context !== undefined) context._popContext();
- this._promise._unsetDisposable();
- this._data = null;
- return ret;
- };
- Disposer.isDisposer = function (d) {
- return (d != null &&
- typeof d.resource === "function" &&
- typeof d.tryDispose === "function");
- };
- function FunctionDisposer(fn, promise, context) {
- this.constructor$(fn, promise, context);
- }
- inherits(FunctionDisposer, Disposer);
- FunctionDisposer.prototype.doDispose = function (resource, inspection) {
- var fn = this.data();
- return fn.call(resource, resource, inspection);
- };
- function maybeUnwrapDisposer(value) {
- if (Disposer.isDisposer(value)) {
- this.resources[this.index]._setDisposable(value);
- return value.promise();
- }
- return value;
- }
- Promise.using = function () {
- var len = arguments.length;
- if (len < 2) return apiRejection(
- "you must pass at least 2 arguments to Promise.using");
- var fn = arguments[len - 1];
- if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
- var input;
- var spreadArgs = true;
- if (len === 2 && Array.isArray(arguments[0])) {
- input = arguments[0];
- len = input.length;
- spreadArgs = false;
- } else {
- input = arguments;
- len--;
- }
- var resources = new Array(len);
- for (var i = 0; i < len; ++i) {
- var resource = input[i];
- if (Disposer.isDisposer(resource)) {
- var disposer = resource;
- resource = resource.promise();
- resource._setDisposable(disposer);
- } else {
- var maybePromise = tryConvertToPromise(resource);
- if (maybePromise instanceof Promise) {
- resource =
- maybePromise._then(maybeUnwrapDisposer, null, null, {
- resources: resources,
- index: i
- }, undefined);
- }
- }
- resources[i] = resource;
- }
- var promise = Promise.settle(resources)
- .then(inspectionMapper)
- .then(function(vals) {
- promise._pushContext();
- var ret;
- try {
- ret = spreadArgs
- ? fn.apply(undefined, vals) : fn.call(undefined, vals);
- } finally {
- promise._popContext();
- }
- return ret;
- })
- ._then(
- disposerSuccess, disposerFail, undefined, resources, undefined);
- resources.promise = promise;
- return promise;
- };
- Promise.prototype._setDisposable = function (disposer) {
- this._bitField = this._bitField | 262144;
- this._disposer = disposer;
- };
- Promise.prototype._isDisposable = function () {
- return (this._bitField & 262144) > 0;
- };
- Promise.prototype._getDisposer = function () {
- return this._disposer;
- };
- Promise.prototype._unsetDisposable = function () {
- this._bitField = this._bitField & (~262144);
- this._disposer = undefined;
- };
- Promise.prototype.disposer = function (fn) {
- if (typeof fn === "function") {
- return new FunctionDisposer(fn, this, createContext());
- }
- throw new TypeError();
- };
- };
- },{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
- "use strict";
- var es5 = _dereq_("./es5.js");
- var canEvaluate = typeof navigator == "undefined";
- var haveGetters = (function(){
- try {
- var o = {};
- es5.defineProperty(o, "f", {
- get: function () {
- return 3;
- }
- });
- return o.f === 3;
- }
- catch (e) {
- return false;
- }
- })();
- var errorObj = {e: {}};
- var tryCatchTarget;
- function tryCatcher() {
- try {
- var target = tryCatchTarget;
- tryCatchTarget = null;
- return target.apply(this, arguments);
- } catch (e) {
- errorObj.e = e;
- return errorObj;
- }
- }
- function tryCatch(fn) {
- tryCatchTarget = fn;
- return tryCatcher;
- }
- var inherits = function(Child, Parent) {
- var hasProp = {}.hasOwnProperty;
- function T() {
- this.constructor = Child;
- this.constructor$ = Parent;
- for (var propertyName in Parent.prototype) {
- if (hasProp.call(Parent.prototype, propertyName) &&
- propertyName.charAt(propertyName.length-1) !== "$"
- ) {
- this[propertyName + "$"] = Parent.prototype[propertyName];
- }
- }
- }
- T.prototype = Parent.prototype;
- Child.prototype = new T();
- return Child.prototype;
- };
- function isPrimitive(val) {
- return val == null || val === true || val === false ||
- typeof val === "string" || typeof val === "number";
- }
- function isObject(value) {
- return !isPrimitive(value);
- }
- function maybeWrapAsError(maybeError) {
- if (!isPrimitive(maybeError)) return maybeError;
- return new Error(safeToString(maybeError));
- }
- function withAppended(target, appendee) {
- var len = target.length;
- var ret = new Array(len + 1);
- var i;
- for (i = 0; i < len; ++i) {
- ret[i] = target[i];
- }
- ret[i] = appendee;
- return ret;
- }
- function getDataPropertyOrDefault(obj, key, defaultValue) {
- if (es5.isES5) {
- var desc = Object.getOwnPropertyDescriptor(obj, key);
- if (desc != null) {
- return desc.get == null && desc.set == null
- ? desc.value
- : defaultValue;
- }
- } else {
- return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
- }
- }
- function notEnumerableProp(obj, name, value) {
- if (isPrimitive(obj)) return obj;
- var descriptor = {
- value: value,
- configurable: true,
- enumerable: false,
- writable: true
- };
- es5.defineProperty(obj, name, descriptor);
- return obj;
- }
- function thrower(r) {
- throw r;
- }
- var inheritedDataKeys = (function() {
- var excludedPrototypes = [
- Array.prototype,
- Object.prototype,
- Function.prototype
- ];
- var isExcludedProto = function(val) {
- for (var i = 0; i < excludedPrototypes.length; ++i) {
- if (excludedPrototypes[i] === val) {
- return true;
- }
- }
- return false;
- };
- if (es5.isES5) {
- var getKeys = Object.getOwnPropertyNames;
- return function(obj) {
- var ret = [];
- var visitedKeys = Object.create(null);
- while (obj != null && !isExcludedProto(obj)) {
- var keys;
- try {
- keys = getKeys(obj);
- } catch (e) {
- return ret;
- }
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (visitedKeys[key]) continue;
- visitedKeys[key] = true;
- var desc = Object.getOwnPropertyDescriptor(obj, key);
- if (desc != null && desc.get == null && desc.set == null) {
- ret.push(key);
- }
- }
- obj = es5.getPrototypeOf(obj);
- }
- return ret;
- };
- } else {
- var hasProp = {}.hasOwnProperty;
- return function(obj) {
- if (isExcludedProto(obj)) return [];
- var ret = [];
- /*jshint forin:false */
- enumeration: for (var key in obj) {
- if (hasProp.call(obj, key)) {
- ret.push(key);
- } else {
- for (var i = 0; i < excludedPrototypes.length; ++i) {
- if (hasProp.call(excludedPrototypes[i], key)) {
- continue enumeration;
- }
- }
- ret.push(key);
- }
- }
- return ret;
- };
- }
- })();
- var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
- function isClass(fn) {
- try {
- if (typeof fn === "function") {
- var keys = es5.names(fn.prototype);
- var hasMethods = es5.isES5 && keys.length > 1;
- var hasMethodsOtherThanConstructor = keys.length > 0 &&
- !(keys.length === 1 && keys[0] === "constructor");
- var hasThisAssignmentAndStaticMethods =
- thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
- if (hasMethods || hasMethodsOtherThanConstructor ||
- hasThisAssignmentAndStaticMethods) {
- return true;
- }
- }
- return false;
- } catch (e) {
- return false;
- }
- }
- function toFastProperties(obj) {
- /*jshint -W027,-W055,-W031*/
- function f() {}
- f.prototype = obj;
- var l = 8;
- while (l--) new f();
- return obj;
- eval(obj);
- }
- var rident = /^[a-z$_][a-z$_0-9]*$/i;
- function isIdentifier(str) {
- return rident.test(str);
- }
- function filledRange(count, prefix, suffix) {
- var ret = new Array(count);
- for(var i = 0; i < count; ++i) {
- ret[i] = prefix + i + suffix;
- }
- return ret;
- }
- function safeToString(obj) {
- try {
- return obj + "";
- } catch (e) {
- return "[no string representation]";
- }
- }
- function markAsOriginatingFromRejection(e) {
- try {
- notEnumerableProp(e, "isOperational", true);
- }
- catch(ignore) {}
- }
- function originatesFromRejection(e) {
- if (e == null) return false;
- return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
- e["isOperational"] === true);
- }
- function canAttachTrace(obj) {
- return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
- }
- var ensureErrorObject = (function() {
- if (!("stack" in new Error())) {
- return function(value) {
- if (canAttachTrace(value)) return value;
- try {throw new Error(safeToString(value));}
- catch(err) {return err;}
- };
- } else {
- return function(value) {
- if (canAttachTrace(value)) return value;
- return new Error(safeToString(value));
- };
- }
- })();
- function classString(obj) {
- return {}.toString.call(obj);
- }
- function copyDescriptors(from, to, filter) {
- var keys = es5.names(from);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (filter(key)) {
- try {
- es5.defineProperty(to, key, es5.getDescriptor(from, key));
- } catch (ignore) {}
- }
- }
- }
- var ret = {
- isClass: isClass,
- isIdentifier: isIdentifier,
- inheritedDataKeys: inheritedDataKeys,
- getDataPropertyOrDefault: getDataPropertyOrDefault,
- thrower: thrower,
- isArray: es5.isArray,
- haveGetters: haveGetters,
- notEnumerableProp: notEnumerableProp,
- isPrimitive: isPrimitive,
- isObject: isObject,
- canEvaluate: canEvaluate,
- errorObj: errorObj,
- tryCatch: tryCatch,
- inherits: inherits,
- withAppended: withAppended,
- maybeWrapAsError: maybeWrapAsError,
- toFastProperties: toFastProperties,
- filledRange: filledRange,
- toString: safeToString,
- canAttachTrace: canAttachTrace,
- ensureErrorObject: ensureErrorObject,
- originatesFromRejection: originatesFromRejection,
- markAsOriginatingFromRejection: markAsOriginatingFromRejection,
- classString: classString,
- copyDescriptors: copyDescriptors,
- hasDevTools: typeof chrome !== "undefined" && chrome &&
- typeof chrome.loadTimes === "function",
- isNode: typeof process !== "undefined" &&
- classString(process).toLowerCase() === "[object process]"
- };
- ret.isRecentNode = ret.isNode && (function() {
- var version = process.versions.node.split(".").map(Number);
- return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
- })();
- if (ret.isNode) ret.toFastProperties(process);
- try {throw new Error(); } catch (e) {ret.lastLineError = e;}
- module.exports = ret;
- },{"./es5.js":14}]},{},[4])(4)
- }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"_process":26}],3:[function(require,module,exports){
- (function (global){
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
- * @license MIT
- */
- /* eslint-disable no-proto */
- 'use strict'
- var base64 = require('base64-js')
- var ieee754 = require('ieee754')
- var isArray = require('isarray')
- exports.Buffer = Buffer
- exports.SlowBuffer = SlowBuffer
- exports.INSPECT_MAX_BYTES = 50
- Buffer.poolSize = 8192 // not used by this implementation
- var rootParent = {}
- /**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Use Object implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * Due to various browser bugs, sometimes the Object implementation will be used even
- * when the browser supports typed arrays.
- *
- * Note:
- *
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
- *
- * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
- * on objects.
- *
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
- *
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
- * incorrect length in some situations.
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
- * get the Object implementation, which is slower but behaves correctly.
- */
- Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
- ? global.TYPED_ARRAY_SUPPORT
- : typedArraySupport()
- function typedArraySupport () {
- function Bar () {}
- try {
- var arr = new Uint8Array(1)
- arr.foo = function () { return 42 }
- arr.constructor = Bar
- return arr.foo() === 42 && // typed array instances can be augmented
- arr.constructor === Bar && // constructor can be set
- typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
- arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
- } catch (e) {
- return false
- }
- }
- function kMaxLength () {
- return Buffer.TYPED_ARRAY_SUPPORT
- ? 0x7fffffff
- : 0x3fffffff
- }
- /**
- * Class: Buffer
- * =============
- *
- * The Buffer constructor returns instances of `Uint8Array` that are augmented
- * with function properties for all the node `Buffer` API functions. We use
- * `Uint8Array` so that square bracket notation works as expected -- it returns
- * a single octet.
- *
- * By augmenting the instances, we can avoid modifying the `Uint8Array`
- * prototype.
- */
- function Buffer (arg) {
- if (!(this instanceof Buffer)) {
- // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
- if (arguments.length > 1) return new Buffer(arg, arguments[1])
- return new Buffer(arg)
- }
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- this.length = 0
- this.parent = undefined
- }
- // Common case.
- if (typeof arg === 'number') {
- return fromNumber(this, arg)
- }
- // Slightly less common case.
- if (typeof arg === 'string') {
- return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
- }
- // Unusual.
- return fromObject(this, arg)
- }
- function fromNumber (that, length) {
- that = allocate(that, length < 0 ? 0 : checked(length) | 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- for (var i = 0; i < length; i++) {
- that[i] = 0
- }
- }
- return that
- }
- function fromString (that, string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
- // Assumption: byteLength() return value is always < kMaxLength.
- var length = byteLength(string, encoding) | 0
- that = allocate(that, length)
- that.write(string, encoding)
- return that
- }
- function fromObject (that, object) {
- if (Buffer.isBuffer(object)) return fromBuffer(that, object)
- if (isArray(object)) return fromArray(that, object)
- if (object == null) {
- throw new TypeError('must start with number, buffer, array or string')
- }
- if (typeof ArrayBuffer !== 'undefined') {
- if (object.buffer instanceof ArrayBuffer) {
- return fromTypedArray(that, object)
- }
- if (object instanceof ArrayBuffer) {
- return fromArrayBuffer(that, object)
- }
- }
- if (object.length) return fromArrayLike(that, object)
- return fromJsonObject(that, object)
- }
- function fromBuffer (that, buffer) {
- var length = checked(buffer.length) | 0
- that = allocate(that, length)
- buffer.copy(that, 0, 0, length)
- return that
- }
- function fromArray (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
- }
- // Duplicate of fromArray() to keep fromArray() monomorphic.
- function fromTypedArray (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- // Truncating the elements is probably not what people expect from typed
- // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
- // of the old Buffer constructor.
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
- }
- function fromArrayBuffer (that, array) {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- array.byteLength
- that = Buffer._augment(new Uint8Array(array))
- } else {
- // Fallback: Return an object instance of the Buffer class
- that = fromTypedArray(that, new Uint8Array(array))
- }
- return that
- }
- function fromArrayLike (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
- }
- // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
- // Returns a zero-length buffer for inputs that don't conform to the spec.
- function fromJsonObject (that, object) {
- var array
- var length = 0
- if (object.type === 'Buffer' && isArray(object.data)) {
- array = object.data
- length = checked(array.length) | 0
- }
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- Buffer.prototype.__proto__ = Uint8Array.prototype
- Buffer.__proto__ = Uint8Array
- } else {
- // pre-set for values that may exist in the future
- Buffer.prototype.length = undefined
- Buffer.prototype.parent = undefined
- }
- function allocate (that, length) {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = Buffer._augment(new Uint8Array(length))
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- that.length = length
- that._isBuffer = true
- }
- var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
- if (fromPool) that.parent = rootParent
- return that
- }
- function checked (length) {
- // Note: cannot use `length < kMaxLength` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= kMaxLength()) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
- }
- return length | 0
- }
- function SlowBuffer (subject, encoding) {
- if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
- var buf = new Buffer(subject, encoding)
- delete buf.parent
- return buf
- }
- Buffer.isBuffer = function isBuffer (b) {
- return !!(b != null && b._isBuffer)
- }
- Buffer.compare = function compare (a, b) {
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError('Arguments must be Buffers')
- }
- if (a === b) return 0
- var x = a.length
- var y = b.length
- var i = 0
- var len = Math.min(x, y)
- while (i < len) {
- if (a[i] !== b[i]) break
- ++i
- }
- if (i !== len) {
- x = a[i]
- y = b[i]
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
- Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'binary':
- case 'base64':
- case 'raw':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
- }
- Buffer.concat = function concat (list, length) {
- if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
- if (list.length === 0) {
- return new Buffer(0)
- }
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; i++) {
- length += list[i].length
- }
- }
- var buf = new Buffer(length)
- var pos = 0
- for (i = 0; i < list.length; i++) {
- var item = list[i]
- item.copy(buf, pos)
- pos += item.length
- }
- return buf
- }
- function byteLength (string, encoding) {
- if (typeof string !== 'string') string = '' + string
- var len = string.length
- if (len === 0) return 0
- // Use a for loop to avoid recursion
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'binary':
- // Deprecated
- case 'raw':
- case 'raws':
- return len
- case 'utf8':
- case 'utf-8':
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.byteLength = byteLength
- function slowToString (encoding, start, end) {
- var loweredCase = false
- start = start | 0
- end = end === undefined || end === Infinity ? this.length : end | 0
- if (!encoding) encoding = 'utf8'
- if (start < 0) start = 0
- if (end > this.length) end = this.length
- if (end <= start) return ''
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
- case 'ascii':
- return asciiSlice(this, start, end)
- case 'binary':
- return binarySlice(this, start, end)
- case 'base64':
- return base64Slice(this, start, end)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.prototype.toString = function toString () {
- var length = this.length | 0
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
- }
- Buffer.prototype.equals = function equals (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
- }
- Buffer.prototype.inspect = function inspect () {
- var str = ''
- var max = exports.INSPECT_MAX_BYTES
- if (this.length > 0) {
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
- if (this.length > max) str += ' ... '
- }
- return '<Buffer ' + str + '>'
- }
- Buffer.prototype.compare = function compare (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return 0
- return Buffer.compare(this, b)
- }
- Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
- if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
- else if (byteOffset < -0x80000000) byteOffset = -0x80000000
- byteOffset >>= 0
- if (this.length === 0) return -1
- if (byteOffset >= this.length) return -1
- // Negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
- if (typeof val === 'string') {
- if (val.length === 0) return -1 // special case: looking for empty string always fails
- return String.prototype.indexOf.call(this, val, byteOffset)
- }
- if (Buffer.isBuffer(val)) {
- return arrayIndexOf(this, val, byteOffset)
- }
- if (typeof val === 'number') {
- if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
- return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
- }
- return arrayIndexOf(this, [ val ], byteOffset)
- }
- function arrayIndexOf (arr, val, byteOffset) {
- var foundIndex = -1
- for (var i = 0; byteOffset + i < arr.length; i++) {
- if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
- if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
- } else {
- foundIndex = -1
- }
- }
- return -1
- }
- throw new TypeError('val must be string, number or Buffer')
- }
- // `get` is deprecated
- Buffer.prototype.get = function get (offset) {
- console.log('.get() is deprecated. Access using array indexes instead.')
- return this.readUInt8(offset)
- }
- // `set` is deprecated
- Buffer.prototype.set = function set (v, offset) {
- console.log('.set() is deprecated. Access using array indexes instead.')
- return this.writeUInt8(v, offset)
- }
- function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0
- var remaining = buf.length - offset
- if (!length) {
- length = remaining
- } else {
- length = Number(length)
- if (length > remaining) {
- length = remaining
- }
- }
- // must be an even number of digits
- var strLen = string.length
- if (strLen % 2 !== 0) throw new Error('Invalid hex string')
- if (length > strLen / 2) {
- length = strLen / 2
- }
- for (var i = 0; i < length; i++) {
- var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (isNaN(parsed)) throw new Error('Invalid hex string')
- buf[offset + i] = parsed
- }
- return i
- }
- function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
- }
- function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
- }
- function binaryWrite (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
- }
- function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
- }
- function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
- }
- Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8'
- length = this.length
- offset = 0
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset
- length = this.length
- offset = 0
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset | 0
- if (isFinite(length)) {
- length = length | 0
- if (encoding === undefined) encoding = 'utf8'
- } else {
- encoding = length
- length = undefined
- }
- // legacy write(string, encoding, offset, length) - remove in v0.13
- } else {
- var swap = encoding
- encoding = offset
- offset = length | 0
- length = swap
- }
- var remaining = this.length - offset
- if (length === undefined || length > remaining) length = remaining
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('attempt to write outside buffer bounds')
- }
- if (!encoding) encoding = 'utf8'
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
- case 'ascii':
- return asciiWrite(this, string, offset, length)
- case 'binary':
- return binaryWrite(this, string, offset, length)
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
- }
- }
- function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return base64.fromByteArray(buf)
- } else {
- return base64.fromByteArray(buf.slice(start, end))
- }
- }
- function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end)
- var res = []
- var i = start
- while (i < end) {
- var firstByte = buf[i]
- var codePoint = null
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte
- }
- break
- case 2:
- secondByte = buf[i + 1]
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint
- }
- }
- break
- case 3:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint
- }
- }
- break
- case 4:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- fourthByte = buf[i + 3]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint
- }
- }
- }
- }
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD
- bytesPerSequence = 1
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000
- res.push(codePoint >>> 10 & 0x3FF | 0xD800)
- codePoint = 0xDC00 | codePoint & 0x3FF
- }
- res.push(codePoint)
- i += bytesPerSequence
- }
- return decodeCodePointsArray(res)
- }
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
- // the lowest limit is Chrome, with 0x10000 args.
- // We go 1 magnitude less, for safety
- var MAX_ARGUMENTS_LENGTH = 0x1000
- function decodeCodePointsArray (codePoints) {
- var len = codePoints.length
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
- }
- // Decode in chunks to avoid "call stack size exceeded".
- var res = ''
- var i = 0
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- )
- }
- return res
- }
- function asciiSlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
- for (var i = start; i < end; i++) {
- ret += String.fromCharCode(buf[i] & 0x7F)
- }
- return ret
- }
- function binarySlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
- for (var i = start; i < end; i++) {
- ret += String.fromCharCode(buf[i])
- }
- return ret
- }
- function hexSlice (buf, start, end) {
- var len = buf.length
- if (!start || start < 0) start = 0
- if (!end || end < 0 || end > len) end = len
- var out = ''
- for (var i = start; i < end; i++) {
- out += toHex(buf[i])
- }
- return out
- }
- function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
- }
- return res
- }
- Buffer.prototype.slice = function slice (start, end) {
- var len = this.length
- start = ~~start
- end = end === undefined ? len : ~~end
- if (start < 0) {
- start += len
- if (start < 0) start = 0
- } else if (start > len) {
- start = len
- }
- if (end < 0) {
- end += len
- if (end < 0) end = 0
- } else if (end > len) {
- end = len
- }
- if (end < start) end = start
- var newBuf
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- newBuf = Buffer._augment(this.subarray(start, end))
- } else {
- var sliceLen = end - start
- newBuf = new Buffer(sliceLen, undefined)
- for (var i = 0; i < sliceLen; i++) {
- newBuf[i] = this[i + start]
- }
- }
- if (newBuf.length) newBuf.parent = this.parent || this
- return newBuf
- }
- /*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
- function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
- }
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- return val
- }
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length)
- }
- var val = this[offset + --byteLength]
- var mul = 1
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul
- }
- return val
- }
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
- }
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- return this[offset] | (this[offset + 1] << 8)
- }
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
- }
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
- }
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
- }
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- mul *= 0x80
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- return val
- }
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var i = byteLength
- var mul = 1
- var val = this[offset + --i]
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul
- }
- mul *= 0x80
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- return val
- }
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
- }
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset] | (this[offset + 1] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset + 1] | (this[offset] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
- }
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
- }
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, true, 23, 4)
- }
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, false, 23, 4)
- }
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, true, 52, 8)
- }
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, false, 52, 8)
- }
- function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('value is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('index out of range')
- }
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
- var mul = 1
- var i = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
- var i = byteLength - 1
- var mul = 1
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- this[offset] = (value & 0xff)
- return offset + 1
- }
- function objectWriteUInt16 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
- (littleEndian ? i : 1 - i) * 8
- }
- }
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
- return offset + 2
- }
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
- return offset + 2
- }
- function objectWriteUInt32 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffffffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
- }
- }
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
- return offset + 4
- }
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
- return offset + 4
- }
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
- var i = 0
- var mul = 1
- var sub = value < 0 ? 1 : 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
- var i = byteLength - 1
- var mul = 1
- var sub = value < 0 ? 1 : 0
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- if (value < 0) value = 0xff + value + 1
- this[offset] = (value & 0xff)
- return offset + 1
- }
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
- return offset + 2
- }
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
- return offset + 2
- }
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
- return offset + 4
- }
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (value < 0) value = 0xffffffff + value + 1
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
- return offset + 4
- }
- function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (value > max || value < min) throw new RangeError('value is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('index out of range')
- if (offset < 0) throw new RangeError('index out of range')
- }
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
- }
- ieee754.write(buf, value, offset, littleEndian, 23, 4)
- return offset + 4
- }
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
- }
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
- }
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
- }
- ieee754.write(buf, value, offset, littleEndian, 52, 8)
- return offset + 8
- }
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
- }
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
- }
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!start) start = 0
- if (!end && end !== 0) end = this.length
- if (targetStart >= target.length) targetStart = target.length
- if (!targetStart) targetStart = 0
- if (end > 0 && end < start) end = start
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
- }
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
- // Are we oob?
- if (end > this.length) end = this.length
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start
- }
- var len = end - start
- var i
- if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (i = len - 1; i >= 0; i--) {
- target[i + targetStart] = this[i + start]
- }
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
- // ascending copy from start
- for (i = 0; i < len; i++) {
- target[i + targetStart] = this[i + start]
- }
- } else {
- target._set(this.subarray(start, start + len), targetStart)
- }
- return len
- }
- // fill(value, start=0, end=buffer.length)
- Buffer.prototype.fill = function fill (value, start, end) {
- if (!value) value = 0
- if (!start) start = 0
- if (!end) end = this.length
- if (end < start) throw new RangeError('end < start')
- // Fill 0 bytes; we're done
- if (end === start) return
- if (this.length === 0) return
- if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
- if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
- var i
- if (typeof value === 'number') {
- for (i = start; i < end; i++) {
- this[i] = value
- }
- } else {
- var bytes = utf8ToBytes(value.toString())
- var len = bytes.length
- for (i = start; i < end; i++) {
- this[i] = bytes[i % len]
- }
- }
- return this
- }
- /**
- * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
- * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
- */
- Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
- if (typeof Uint8Array !== 'undefined') {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- return (new Buffer(this)).buffer
- } else {
- var buf = new Uint8Array(this.length)
- for (var i = 0, len = buf.length; i < len; i += 1) {
- buf[i] = this[i]
- }
- return buf.buffer
- }
- } else {
- throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
- }
- }
- // HELPER FUNCTIONS
- // ================
- var BP = Buffer.prototype
- /**
- * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
- */
- Buffer._augment = function _augment (arr) {
- arr.constructor = Buffer
- arr._isBuffer = true
- // save reference to original Uint8Array set method before overwriting
- arr._set = arr.set
- // deprecated
- arr.get = BP.get
- arr.set = BP.set
- arr.write = BP.write
- arr.toString = BP.toString
- arr.toLocaleString = BP.toString
- arr.toJSON = BP.toJSON
- arr.equals = BP.equals
- arr.compare = BP.compare
- arr.indexOf = BP.indexOf
- arr.copy = BP.copy
- arr.slice = BP.slice
- arr.readUIntLE = BP.readUIntLE
- arr.readUIntBE = BP.readUIntBE
- arr.readUInt8 = BP.readUInt8
- arr.readUInt16LE = BP.readUInt16LE
- arr.readUInt16BE = BP.readUInt16BE
- arr.readUInt32LE = BP.readUInt32LE
- arr.readUInt32BE = BP.readUInt32BE
- arr.readIntLE = BP.readIntLE
- arr.readIntBE = BP.readIntBE
- arr.readInt8 = BP.readInt8
- arr.readInt16LE = BP.readInt16LE
- arr.readInt16BE = BP.readInt16BE
- arr.readInt32LE = BP.readInt32LE
- arr.readInt32BE = BP.readInt32BE
- arr.readFloatLE = BP.readFloatLE
- arr.readFloatBE = BP.readFloatBE
- arr.readDoubleLE = BP.readDoubleLE
- arr.readDoubleBE = BP.readDoubleBE
- arr.writeUInt8 = BP.writeUInt8
- arr.writeUIntLE = BP.writeUIntLE
- arr.writeUIntBE = BP.writeUIntBE
- arr.writeUInt16LE = BP.writeUInt16LE
- arr.writeUInt16BE = BP.writeUInt16BE
- arr.writeUInt32LE = BP.writeUInt32LE
- arr.writeUInt32BE = BP.writeUInt32BE
- arr.writeIntLE = BP.writeIntLE
- arr.writeIntBE = BP.writeIntBE
- arr.writeInt8 = BP.writeInt8
- arr.writeInt16LE = BP.writeInt16LE
- arr.writeInt16BE = BP.writeInt16BE
- arr.writeInt32LE = BP.writeInt32LE
- arr.writeInt32BE = BP.writeInt32BE
- arr.writeFloatLE = BP.writeFloatLE
- arr.writeFloatBE = BP.writeFloatBE
- arr.writeDoubleLE = BP.writeDoubleLE
- arr.writeDoubleBE = BP.writeDoubleBE
- arr.fill = BP.fill
- arr.inspect = BP.inspect
- arr.toArrayBuffer = BP.toArrayBuffer
- return arr
- }
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
- function base64clean (str) {
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = stringtrim(str).replace(INVALID_BASE64_RE, '')
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '='
- }
- return str
- }
- function stringtrim (str) {
- if (str.trim) return str.trim()
- return str.replace(/^\s+|\s+$/g, '')
- }
- function toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
- }
- function utf8ToBytes (string, units) {
- units = units || Infinity
- var codePoint
- var length = string.length
- var leadSurrogate = null
- var bytes = []
- for (var i = 0; i < length; i++) {
- codePoint = string.charCodeAt(i)
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- }
- // valid lead
- leadSurrogate = codePoint
- continue
- }
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- leadSurrogate = codePoint
- continue
- }
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- }
- leadSurrogate = null
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint)
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else {
- throw new Error('Invalid code point')
- }
- }
- return bytes
- }
- function asciiToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; i++) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF)
- }
- return byteArray
- }
- function utf16leToBytes (str, units) {
- var c, hi, lo
- var byteArray = []
- for (var i = 0; i < str.length; i++) {
- if ((units -= 2) < 0) break
- c = str.charCodeAt(i)
- hi = c >> 8
- lo = c % 256
- byteArray.push(lo)
- byteArray.push(hi)
- }
- return byteArray
- }
- function base64ToBytes (str) {
- return base64.toByteArray(base64clean(str))
- }
- function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; i++) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i]
- }
- return i
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"base64-js":1,"ieee754":5,"isarray":4}],4:[function(require,module,exports){
- var toString = {}.toString;
- module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
- };
- },{}],5:[function(require,module,exports){
- exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
- i += d
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
- }
- exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
- value = Math.abs(value)
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = ((value * c) - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- buffer[offset + i - d] |= s * 128
- }
- },{}],6:[function(require,module,exports){
- var Pipe = require('../pipe').Pipe;
- var Context = function Context(){
- };
- Context.prototype.setResult = function(result) {
- this.result = result;
- this.hasResult = true;
- return this;
- };
- Context.prototype.exit = function() {
- this.exiting = true;
- return this;
- };
- Context.prototype.switchTo = function(next, pipe) {
- if (typeof next === 'string' || next instanceof Pipe) {
- this.nextPipe = next;
- } else {
- this.next = next;
- if (pipe) {
- this.nextPipe = pipe;
- }
- }
- return this;
- };
- Context.prototype.push = function(child, name) {
- child.parent = this;
- if (typeof name !== 'undefined') {
- child.childName = name;
- }
- child.root = this.root || this;
- child.options = child.options || this.options;
- if (!this.children) {
- this.children = [child];
- this.nextAfterChildren = this.next || null;
- this.next = child;
- } else {
- this.children[this.children.length - 1].next = child;
- this.children.push(child);
- }
- child.next = this;
- return this;
- };
- exports.Context = Context;
- },{"../pipe":20}],7:[function(require,module,exports){
- var Context = require('./context').Context;
- var dateReviver = require('../date-reviver');
- var DiffContext = function DiffContext(left, right) {
- this.left = left;
- this.right = right;
- this.pipe = 'diff';
- };
- DiffContext.prototype = new Context();
- DiffContext.prototype.setResult = function(result) {
- if (this.options.cloneDiffValues) {
- var clone = typeof this.options.cloneDiffValues === 'function' ?
- this.options.cloneDiffValues : function(value) {
- return JSON.parse(JSON.stringify(value), dateReviver);
- };
- if (typeof result[0] === 'object') {
- result[0] = clone(result[0]);
- }
- if (typeof result[1] === 'object') {
- result[1] = clone(result[1]);
- }
- }
- return Context.prototype.setResult.apply(this, arguments);
- };
- exports.DiffContext = DiffContext;
- },{"../date-reviver":10,"./context":6}],8:[function(require,module,exports){
- var Context = require('./context').Context;
- var PatchContext = function PatchContext(left, delta) {
- this.left = left;
- this.delta = delta;
- this.pipe = 'patch';
- };
- PatchContext.prototype = new Context();
- exports.PatchContext = PatchContext;
- },{"./context":6}],9:[function(require,module,exports){
- var Context = require('./context').Context;
- var ReverseContext = function ReverseContext(delta) {
- this.delta = delta;
- this.pipe = 'reverse';
- };
- ReverseContext.prototype = new Context();
- exports.ReverseContext = ReverseContext;
- },{"./context":6}],10:[function(require,module,exports){
- // use as 2nd parameter for JSON.parse to revive Date instances
- module.exports = function dateReviver(key, value) {
- var parts;
- if (typeof value === 'string') {
- parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value);
- if (parts) {
- return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +(parts[7] || 0)));
- }
- }
- return value;
- };
- },{}],11:[function(require,module,exports){
- var Processor = require('./processor').Processor;
- var Pipe = require('./pipe').Pipe;
- var DiffContext = require('./contexts/diff').DiffContext;
- var PatchContext = require('./contexts/patch').PatchContext;
- var ReverseContext = require('./contexts/reverse').ReverseContext;
- var trivial = require('./filters/trivial');
- var nested = require('./filters/nested');
- var arrays = require('./filters/arrays');
- var dates = require('./filters/dates');
- var texts = require('./filters/texts');
- var DiffPatcher = function DiffPatcher(options) {
- this.processor = new Processor(options);
- this.processor.pipe(new Pipe('diff').append(
- nested.collectChildrenDiffFilter,
- trivial.diffFilter,
- dates.diffFilter,
- texts.diffFilter,
- nested.objectsDiffFilter,
- arrays.diffFilter
- ).shouldHaveResult());
- this.processor.pipe(new Pipe('patch').append(
- nested.collectChildrenPatchFilter,
- arrays.collectChildrenPatchFilter,
- trivial.patchFilter,
- texts.patchFilter,
- nested.patchFilter,
- arrays.patchFilter
- ).shouldHaveResult());
- this.processor.pipe(new Pipe('reverse').append(
- nested.collectChildrenReverseFilter,
- arrays.collectChildrenReverseFilter,
- trivial.reverseFilter,
- texts.reverseFilter,
- nested.reverseFilter,
- arrays.reverseFilter
- ).shouldHaveResult());
- };
- DiffPatcher.prototype.options = function() {
- return this.processor.options.apply(this.processor, arguments);
- };
- DiffPatcher.prototype.diff = function(left, right) {
- return this.processor.process(new DiffContext(left, right));
- };
- DiffPatcher.prototype.patch = function(left, delta) {
- return this.processor.process(new PatchContext(left, delta));
- };
- DiffPatcher.prototype.reverse = function(delta) {
- return this.processor.process(new ReverseContext(delta));
- };
- DiffPatcher.prototype.unpatch = function(right, delta) {
- return this.patch(right, this.reverse(delta));
- };
- exports.DiffPatcher = DiffPatcher;
- },{"./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){
- exports.isBrowser = typeof window !== 'undefined';
- },{}],13:[function(require,module,exports){
- var DiffContext = require('../contexts/diff').DiffContext;
- var PatchContext = require('../contexts/patch').PatchContext;
- var ReverseContext = require('../contexts/reverse').ReverseContext;
- var lcs = require('./lcs');
- var ARRAY_MOVE = 3;
- var isArray = (typeof Array.isArray === 'function') ?
- // use native function
- Array.isArray :
- // use instanceof operator
- function(a) {
- return a instanceof Array;
- };
- var arrayIndexOf = typeof Array.prototype.indexOf === 'function' ?
- function(array, item) {
- return array.indexOf(item);
- } : function(array, item) {
- var length = array.length;
- for (var i = 0; i < length; i++) {
- if (array[i] === item) {
- return i;
- }
- }
- return -1;
- };
- function arraysHaveMatchByRef(array1, array2, len1, len2) {
- for (var index1 = 0; index1 < len1; index1++) {
- var val1 = array1[index1];
- for (var index2 = 0; index2 < len2; index2++) {
- var val2 = array2[index2];
- if (val1 === val2) {
- return true;
- }
- }
- }
- }
- function matchItems(array1, array2, index1, index2, context) {
- var value1 = array1[index1];
- var value2 = array2[index2];
- if (value1 === value2) {
- return true;
- }
- if (typeof value1 !== 'object' || typeof value2 !== 'object') {
- return false;
- }
- var objectHash = context.objectHash;
- if (!objectHash) {
- // no way to match objects was provided, try match by position
- return context.matchByPosition && index1 === index2;
- }
- var hash1;
- var hash2;
- if (typeof index1 === 'number') {
- context.hashCache1 = context.hashCache1 || [];
- hash1 = context.hashCache1[index1];
- if (typeof hash1 === 'undefined') {
- context.hashCache1[index1] = hash1 = objectHash(value1, index1);
- }
- } else {
- hash1 = objectHash(value1);
- }
- if (typeof hash1 === 'undefined') {
- return false;
- }
- if (typeof index2 === 'number') {
- context.hashCache2 = context.hashCache2 || [];
- hash2 = context.hashCache2[index2];
- if (typeof hash2 === 'undefined') {
- context.hashCache2[index2] = hash2 = objectHash(value2, index2);
- }
- } else {
- hash2 = objectHash(value2);
- }
- if (typeof hash2 === 'undefined') {
- return false;
- }
- return hash1 === hash2;
- }
- var diffFilter = function arraysDiffFilter(context) {
- if (!context.leftIsArray) {
- return;
- }
- var matchContext = {
- objectHash: context.options && context.options.objectHash,
- matchByPosition: context.options && context.options.matchByPosition
- };
- var commonHead = 0;
- var commonTail = 0;
- var index;
- var index1;
- var index2;
- var array1 = context.left;
- var array2 = context.right;
- var len1 = array1.length;
- var len2 = array2.length;
- var child;
- if (len1 > 0 && len2 > 0 && !matchContext.objectHash &&
- typeof matchContext.matchByPosition !== 'boolean') {
- matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
- }
- // separate common head
- while (commonHead < len1 && commonHead < len2 &&
- matchItems(array1, array2, commonHead, commonHead, matchContext)) {
- index = commonHead;
- child = new DiffContext(context.left[index], context.right[index]);
- context.push(child, index);
- commonHead++;
- }
- // separate common tail
- while (commonTail + commonHead < len1 && commonTail + commonHead < len2 &&
- matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
- index1 = len1 - 1 - commonTail;
- index2 = len2 - 1 - commonTail;
- child = new DiffContext(context.left[index1], context.right[index2]);
- context.push(child, index2);
- commonTail++;
- }
- var result;
- if (commonHead + commonTail === len1) {
- if (len1 === len2) {
- // arrays are identical
- context.setResult(undefined).exit();
- return;
- }
- // trivial case, a block (1 or more consecutive items) was added
- result = result || {
- _t: 'a'
- };
- for (index = commonHead; index < len2 - commonTail; index++) {
- result[index] = [array2[index]];
- }
- context.setResult(result).exit();
- return;
- }
- if (commonHead + commonTail === len2) {
- // trivial case, a block (1 or more consecutive items) was removed
- result = result || {
- _t: 'a'
- };
- for (index = commonHead; index < len1 - commonTail; index++) {
- result['_' + index] = [array1[index], 0, 0];
- }
- context.setResult(result).exit();
- return;
- }
- // reset hash cache
- delete matchContext.hashCache1;
- delete matchContext.hashCache2;
- // diff is not trivial, find the LCS (Longest Common Subsequence)
- var trimmed1 = array1.slice(commonHead, len1 - commonTail);
- var trimmed2 = array2.slice(commonHead, len2 - commonTail);
- var seq = lcs.get(
- trimmed1, trimmed2,
- matchItems,
- matchContext
- );
- var removedItems = [];
- result = result || {
- _t: 'a'
- };
- for (index = commonHead; index < len1 - commonTail; index++) {
- if (arrayIndexOf(seq.indices1, index - commonHead) < 0) {
- // removed
- result['_' + index] = [array1[index], 0, 0];
- removedItems.push(index);
- }
- }
- var detectMove = true;
- if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
- detectMove = false;
- }
- var includeValueOnMove = false;
- if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
- includeValueOnMove = true;
- }
- var removedItemsLength = removedItems.length;
- for (index = commonHead; index < len2 - commonTail; index++) {
- var indexOnArray2 = arrayIndexOf(seq.indices2, index - commonHead);
- if (indexOnArray2 < 0) {
- // added, try to match with a removed item and register as position move
- var isMove = false;
- if (detectMove && removedItemsLength > 0) {
- for (var removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
- index1 = removedItems[removeItemIndex1];
- if (matchItems(trimmed1, trimmed2, index1 - commonHead,
- index - commonHead, matchContext)) {
- // store position move as: [originalValue, newPosition, ARRAY_MOVE]
- result['_' + index1].splice(1, 2, index, ARRAY_MOVE);
- if (!includeValueOnMove) {
- // don't include moved value on diff, to save bytes
- result['_' + index1][0] = '';
- }
- index2 = index;
- child = new DiffContext(context.left[index1], context.right[index2]);
- context.push(child, index2);
- removedItems.splice(removeItemIndex1, 1);
- isMove = true;
- break;
- }
- }
- }
- if (!isMove) {
- // added
- result[index] = [array2[index]];
- }
- } else {
- // match, do inner diff
- index1 = seq.indices1[indexOnArray2] + commonHead;
- index2 = seq.indices2[indexOnArray2] + commonHead;
- child = new DiffContext(context.left[index1], context.right[index2]);
- context.push(child, index2);
- }
- }
- context.setResult(result).exit();
- };
- diffFilter.filterName = 'arrays';
- var compare = {
- numerically: function(a, b) {
- return a - b;
- },
- numericallyBy: function(name) {
- return function(a, b) {
- return a[name] - b[name];
- };
- }
- };
- var patchFilter = function nestedPatchFilter(context) {
- if (!context.nested) {
- return;
- }
- if (context.delta._t !== 'a') {
- return;
- }
- var index, index1;
- var delta = context.delta;
- var array = context.left;
- // first, separate removals, insertions and modifications
- var toRemove = [];
- var toInsert = [];
- var toModify = [];
- for (index in delta) {
- if (index !== '_t') {
- if (index[0] === '_') {
- // removed item from original array
- if (delta[index][2] === 0 || delta[index][2] === ARRAY_MOVE) {
- toRemove.push(parseInt(index.slice(1), 10));
- } else {
- throw new Error('only removal or move can be applied at original array indices' +
- ', invalid diff type: ' + delta[index][2]);
- }
- } else {
- if (delta[index].length === 1) {
- // added item at new array
- toInsert.push({
- index: parseInt(index, 10),
- value: delta[index][0]
- });
- } else {
- // modified item at new array
- toModify.push({
- index: parseInt(index, 10),
- delta: delta[index]
- });
- }
- }
- }
- }
- // remove items, in reverse order to avoid sawing our own floor
- toRemove = toRemove.sort(compare.numerically);
- for (index = toRemove.length - 1; index >= 0; index--) {
- index1 = toRemove[index];
- var indexDiff = delta['_' + index1];
- var removedValue = array.splice(index1, 1)[0];
- if (indexDiff[2] === ARRAY_MOVE) {
- // reinsert later
- toInsert.push({
- index: indexDiff[1],
- value: removedValue
- });
- }
- }
- // insert items, in reverse order to avoid moving our own floor
- toInsert = toInsert.sort(compare.numericallyBy('index'));
- var toInsertLength = toInsert.length;
- for (index = 0; index < toInsertLength; index++) {
- var insertion = toInsert[index];
- array.splice(insertion.index, 0, insertion.value);
- }
- // apply modifications
- var toModifyLength = toModify.length;
- var child;
- if (toModifyLength > 0) {
- for (index = 0; index < toModifyLength; index++) {
- var modification = toModify[index];
- child = new PatchContext(context.left[modification.index], modification.delta);
- context.push(child, modification.index);
- }
- }
- if (!context.children) {
- context.setResult(context.left).exit();
- return;
- }
- context.exit();
- };
- patchFilter.filterName = 'arrays';
- var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
- if (!context || !context.children) {
- return;
- }
- if (context.delta._t !== 'a') {
- return;
- }
- var length = context.children.length;
- var child;
- for (var index = 0; index < length; index++) {
- child = context.children[index];
- context.left[child.childName] = child.result;
- }
- context.setResult(context.left).exit();
- };
- collectChildrenPatchFilter.filterName = 'arraysCollectChildren';
- var reverseFilter = function arraysReverseFilter(context) {
- if (!context.nested) {
- if (context.delta[2] === ARRAY_MOVE) {
- context.newName = '_' + context.delta[1];
- context.setResult([context.delta[0], parseInt(context.childName.substr(1), 10), ARRAY_MOVE]).exit();
- }
- return;
- }
- if (context.delta._t !== 'a') {
- return;
- }
- var name, child;
- for (name in context.delta) {
- if (name === '_t') {
- continue;
- }
- child = new ReverseContext(context.delta[name]);
- context.push(child, name);
- }
- context.exit();
- };
- reverseFilter.filterName = 'arrays';
- var reverseArrayDeltaIndex = function(delta, index, itemDelta) {
- if (typeof index === 'string' && index[0] === '_') {
- return parseInt(index.substr(1), 10);
- } else if (isArray(itemDelta) && itemDelta[2] === 0) {
- return '_' + index;
- }
- var reverseIndex = +index;
- for (var deltaIndex in delta) {
- var deltaItem = delta[deltaIndex];
- if (isArray(deltaItem)) {
- if (deltaItem[2] === ARRAY_MOVE) {
- var moveFromIndex = parseInt(deltaIndex.substr(1), 10);
- var moveToIndex = deltaItem[1];
- if (moveToIndex === +index) {
- return moveFromIndex;
- }
- if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
- reverseIndex++;
- } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
- reverseIndex--;
- }
- } else if (deltaItem[2] === 0) {
- var deleteIndex = parseInt(deltaIndex.substr(1), 10);
- if (deleteIndex <= reverseIndex) {
- reverseIndex++;
- }
- } else if (deltaItem.length === 1 && deltaIndex <= reverseIndex) {
- reverseIndex--;
- }
- }
- }
- return reverseIndex;
- };
- var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) {
- if (!context || !context.children) {
- return;
- }
- if (context.delta._t !== 'a') {
- return;
- }
- var length = context.children.length;
- var child;
- var delta = {
- _t: 'a'
- };
- for (var index = 0; index < length; index++) {
- child = context.children[index];
- var name = child.newName;
- if (typeof name === 'undefined') {
- name = reverseArrayDeltaIndex(context.delta, child.childName, child.result);
- }
- if (delta[name] !== child.result) {
- delta[name] = child.result;
- }
- }
- context.setResult(delta).exit();
- };
- collectChildrenReverseFilter.filterName = 'arraysCollectChildren';
- exports.diffFilter = diffFilter;
- exports.patchFilter = patchFilter;
- exports.collectChildrenPatchFilter = collectChildrenPatchFilter;
- exports.reverseFilter = reverseFilter;
- exports.collectChildrenReverseFilter = collectChildrenReverseFilter;
- },{"../contexts/diff":7,"../contexts/patch":8,"../contexts/reverse":9,"./lcs":15}],14:[function(require,module,exports){
- var diffFilter = function datesDiffFilter(context) {
- if (context.left instanceof Date) {
- if (context.right instanceof Date) {
- if (context.left.getTime() !== context.right.getTime()) {
- context.setResult([context.left, context.right]);
- } else {
- context.setResult(undefined);
- }
- } else {
- context.setResult([context.left, context.right]);
- }
- context.exit();
- } else if (context.right instanceof Date) {
- context.setResult([context.left, context.right]).exit();
- }
- };
- diffFilter.filterName = 'dates';
- exports.diffFilter = diffFilter;
- },{}],15:[function(require,module,exports){
- /*
- LCS implementation that supports arrays or strings
- reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
- */
- var defaultMatch = function(array1, array2, index1, index2) {
- return array1[index1] === array2[index2];
- };
- var lengthMatrix = function(array1, array2, match, context) {
- var len1 = array1.length;
- var len2 = array2.length;
- var x, y;
- // initialize empty matrix of len1+1 x len2+1
- var matrix = [len1 + 1];
- for (x = 0; x < len1 + 1; x++) {
- matrix[x] = [len2 + 1];
- for (y = 0; y < len2 + 1; y++) {
- matrix[x][y] = 0;
- }
- }
- matrix.match = match;
- // save sequence lengths for each coordinate
- for (x = 1; x < len1 + 1; x++) {
- for (y = 1; y < len2 + 1; y++) {
- if (match(array1, array2, x - 1, y - 1, context)) {
- matrix[x][y] = matrix[x - 1][y - 1] + 1;
- } else {
- matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);
- }
- }
- }
- return matrix;
- };
- var backtrack = function(matrix, array1, array2, index1, index2, context) {
- if (index1 === 0 || index2 === 0) {
- return {
- sequence: [],
- indices1: [],
- indices2: []
- };
- }
- if (matrix.match(array1, array2, index1 - 1, index2 - 1, context)) {
- var subsequence = backtrack(matrix, array1, array2, index1 - 1, index2 - 1, context);
- subsequence.sequence.push(array1[index1 - 1]);
- subsequence.indices1.push(index1 - 1);
- subsequence.indices2.push(index2 - 1);
- return subsequence;
- }
- if (matrix[index1][index2 - 1] > matrix[index1 - 1][index2]) {
- return backtrack(matrix, array1, array2, index1, index2 - 1, context);
- } else {
- return backtrack(matrix, array1, array2, index1 - 1, index2, context);
- }
- };
- var get = function(array1, array2, match, context) {
- context = context || {};
- var matrix = lengthMatrix(array1, array2, match || defaultMatch, context);
- var result = backtrack(matrix, array1, array2, array1.length, array2.length, context);
- if (typeof array1 === 'string' && typeof array2 === 'string') {
- result.sequence = result.sequence.join('');
- }
- return result;
- };
- exports.get = get;
- },{}],16:[function(require,module,exports){
- var DiffContext = require('../contexts/diff').DiffContext;
- var PatchContext = require('../contexts/patch').PatchContext;
- var ReverseContext = require('../contexts/reverse').ReverseContext;
- var collectChildrenDiffFilter = function collectChildrenDiffFilter(context) {
- if (!context || !context.children) {
- return;
- }
- var length = context.children.length;
- var child;
- var result = context.result;
- for (var index = 0; index < length; index++) {
- child = context.children[index];
- if (typeof child.result === 'undefined') {
- continue;
- }
- result = result || {};
- result[child.childName] = child.result;
- }
- if (result && context.leftIsArray) {
- result._t = 'a';
- }
- context.setResult(result).exit();
- };
- collectChildrenDiffFilter.filterName = 'collectChildren';
- var objectsDiffFilter = function objectsDiffFilter(context) {
- if (context.leftIsArray || context.leftType !== 'object') {
- return;
- }
- var name, child, propertyFilter = context.options.propertyFilter;
- for (name in context.left) {
- if (!Object.prototype.hasOwnProperty.call(context.left, name)) {
- continue;
- }
- if (propertyFilter && !propertyFilter(name, context)) {
- continue;
- }
- child = new DiffContext(context.left[name], context.right[name]);
- context.push(child, name);
- }
- for (name in context.right) {
- if (!Object.prototype.hasOwnProperty.call(context.right, name)) {
- continue;
- }
- if (propertyFilter && !propertyFilter(name, context)) {
- continue;
- }
- if (typeof context.left[name] === 'undefined') {
- child = new DiffContext(undefined, context.right[name]);
- context.push(child, name);
- }
- }
- if (!context.children || context.children.length === 0) {
- context.setResult(undefined).exit();
- return;
- }
- context.exit();
- };
- objectsDiffFilter.filterName = 'objects';
- var patchFilter = function nestedPatchFilter(context) {
- if (!context.nested) {
- return;
- }
- if (context.delta._t) {
- return;
- }
- var name, child;
- for (name in context.delta) {
- child = new PatchContext(context.left[name], context.delta[name]);
- context.push(child, name);
- }
- context.exit();
- };
- patchFilter.filterName = 'objects';
- var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
- if (!context || !context.children) {
- return;
- }
- if (context.delta._t) {
- return;
- }
- var length = context.children.length;
- var child;
- for (var index = 0; index < length; index++) {
- child = context.children[index];
- if (Object.prototype.hasOwnProperty.call(context.left, child.childName) && child.result === undefined) {
- delete context.left[child.childName];
- } else if (context.left[child.childName] !== child.result) {
- context.left[child.childName] = child.result;
- }
- }
- context.setResult(context.left).exit();
- };
- collectChildrenPatchFilter.filterName = 'collectChildren';
- var reverseFilter = function nestedReverseFilter(context) {
- if (!context.nested) {
- return;
- }
- if (context.delta._t) {
- return;
- }
- var name, child;
- for (name in context.delta) {
- child = new ReverseContext(context.delta[name]);
- context.push(child, name);
- }
- context.exit();
- };
- reverseFilter.filterName = 'objects';
- var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) {
- if (!context || !context.children) {
- return;
- }
- if (context.delta._t) {
- return;
- }
- var length = context.children.length;
- var child;
- var delta = {};
- for (var index = 0; index < length; index++) {
- child = context.children[index];
- if (delta[child.childName] !== child.result) {
- delta[child.childName] = child.result;
- }
- }
- context.setResult(delta).exit();
- };
- collectChildrenReverseFilter.filterName = 'collectChildren';
- exports.collectChildrenDiffFilter = collectChildrenDiffFilter;
- exports.objectsDiffFilter = objectsDiffFilter;
- exports.patchFilter = patchFilter;
- exports.collectChildrenPatchFilter = collectChildrenPatchFilter;
- exports.reverseFilter = reverseFilter;
- exports.collectChildrenReverseFilter = collectChildrenReverseFilter;
- },{"../contexts/diff":7,"../contexts/patch":8,"../contexts/reverse":9}],17:[function(require,module,exports){
- /* global diff_match_patch */
- var TEXT_DIFF = 2;
- var DEFAULT_MIN_LENGTH = 60;
- var cachedDiffPatch = null;
- var getDiffMatchPatch = function(required) {
- /*jshint camelcase: false */
- if (!cachedDiffPatch) {
- var instance;
- if (typeof diff_match_patch !== 'undefined') {
- // already loaded, probably a browser
- instance = typeof diff_match_patch === 'function' ?
- new diff_match_patch() : new diff_match_patch.diff_match_patch();
- } else if (typeof require === 'function') {
- try {
- var dmpModuleName = 'diff_match_patch_uncompressed';
- var dmp = require('../../public/external/' + dmpModuleName);
- instance = new dmp.diff_match_patch();
- } catch (err) {
- instance = null;
- }
- }
- if (!instance) {
- if (!required) {
- return null;
- }
- var error = new Error('text diff_match_patch library not found');
- error.diff_match_patch_not_found = true;
- throw error;
- }
- cachedDiffPatch = {
- diff: function(txt1, txt2) {
- return instance.patch_toText(instance.patch_make(txt1, txt2));
- },
- patch: function(txt1, patch) {
- var results = instance.patch_apply(instance.patch_fromText(patch), txt1);
- for (var i = 0; i < results[1].length; i++) {
- if (!results[1][i]) {
- var error = new Error('text patch failed');
- error.textPatchFailed = true;
- }
- }
- return results[0];
- }
- };
- }
- return cachedDiffPatch;
- };
- var diffFilter = function textsDiffFilter(context) {
- if (context.leftType !== 'string') {
- return;
- }
- var minLength = (context.options && context.options.textDiff &&
- context.options.textDiff.minLength) || DEFAULT_MIN_LENGTH;
- if (context.left.length < minLength ||
- context.right.length < minLength) {
- context.setResult([context.left, context.right]).exit();
- return;
- }
- // large text, try to use a text-diff algorithm
- var diffMatchPatch = getDiffMatchPatch();
- if (!diffMatchPatch) {
- // diff-match-patch library not available, fallback to regular string replace
- context.setResult([context.left, context.right]).exit();
- return;
- }
- var diff = diffMatchPatch.diff;
- context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit();
- };
- diffFilter.filterName = 'texts';
- var patchFilter = function textsPatchFilter(context) {
- if (context.nested) {
- return;
- }
- if (context.delta[2] !== TEXT_DIFF) {
- return;
- }
- // text-diff, use a text-patch algorithm
- var patch = getDiffMatchPatch(true).patch;
- context.setResult(patch(context.left, context.delta[0])).exit();
- };
- patchFilter.filterName = 'texts';
- var textDeltaReverse = function(delta) {
- var i, l, lines, line, lineTmp, header = null,
- headerRegex = /^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/,
- lineHeader, lineAdd, lineRemove;
- lines = delta.split('\n');
- for (i = 0, l = lines.length; i < l; i++) {
- line = lines[i];
- var lineStart = line.slice(0, 1);
- if (lineStart === '@') {
- header = headerRegex.exec(line);
- lineHeader = i;
- lineAdd = null;
- lineRemove = null;
- // fix header
- lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@';
- } else if (lineStart === '+') {
- lineAdd = i;
- lines[i] = '-' + lines[i].slice(1);
- if (lines[i - 1].slice(0, 1) === '+') {
- // swap lines to keep default order (-+)
- lineTmp = lines[i];
- lines[i] = lines[i - 1];
- lines[i - 1] = lineTmp;
- }
- } else if (lineStart === '-') {
- lineRemove = i;
- lines[i] = '+' + lines[i].slice(1);
- }
- }
- return lines.join('\n');
- };
- var reverseFilter = function textsReverseFilter(context) {
- if (context.nested) {
- return;
- }
- if (context.delta[2] !== TEXT_DIFF) {
- return;
- }
- // text-diff, use a text-diff algorithm
- context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit();
- };
- reverseFilter.filterName = 'texts';
- exports.diffFilter = diffFilter;
- exports.patchFilter = patchFilter;
- exports.reverseFilter = reverseFilter;
- },{}],18:[function(require,module,exports){
- var isArray = (typeof Array.isArray === 'function') ?
- // use native function
- Array.isArray :
- // use instanceof operator
- function(a) {
- return a instanceof Array;
- };
- var diffFilter = function trivialMatchesDiffFilter(context) {
- if (context.left === context.right) {
- context.setResult(undefined).exit();
- return;
- }
- if (typeof context.left === 'undefined') {
- if (typeof context.right === 'function') {
- throw new Error('functions are not supported');
- }
- context.setResult([context.right]).exit();
- return;
- }
- if (typeof context.right === 'undefined') {
- context.setResult([context.left, 0, 0]).exit();
- return;
- }
- if (typeof context.left === 'function' || typeof context.right === 'function') {
- throw new Error('functions are not supported');
- }
- context.leftType = context.left === null ? 'null' : typeof context.left;
- context.rightType = context.right === null ? 'null' : typeof context.right;
- if (context.leftType !== context.rightType) {
- context.setResult([context.left, context.right]).exit();
- return;
- }
- if (context.leftType === 'boolean' || context.leftType === 'number') {
- context.setResult([context.left, context.right]).exit();
- return;
- }
- if (context.leftType === 'object') {
- context.leftIsArray = isArray(context.left);
- }
- if (context.rightType === 'object') {
- context.rightIsArray = isArray(context.right);
- }
- if (context.leftIsArray !== context.rightIsArray) {
- context.setResult([context.left, context.right]).exit();
- return;
- }
- };
- diffFilter.filterName = 'trivial';
- var patchFilter = function trivialMatchesPatchFilter(context) {
- if (typeof context.delta === 'undefined') {
- context.setResult(context.left).exit();
- return;
- }
- context.nested = !isArray(context.delta);
- if (context.nested) {
- return;
- }
- if (context.delta.length === 1) {
- context.setResult(context.delta[0]).exit();
- return;
- }
- if (context.delta.length === 2) {
- context.setResult(context.delta[1]).exit();
- return;
- }
- if (context.delta.length === 3 && context.delta[2] === 0) {
- context.setResult(undefined).exit();
- return;
- }
- };
- patchFilter.filterName = 'trivial';
- var reverseFilter = function trivialReferseFilter(context) {
- if (typeof context.delta === 'undefined') {
- context.setResult(context.delta).exit();
- return;
- }
- context.nested = !isArray(context.delta);
- if (context.nested) {
- return;
- }
- if (context.delta.length === 1) {
- context.setResult([context.delta[0], 0, 0]).exit();
- return;
- }
- if (context.delta.length === 2) {
- context.setResult([context.delta[1], context.delta[0]]).exit();
- return;
- }
- if (context.delta.length === 3 && context.delta[2] === 0) {
- context.setResult([context.delta[0]]).exit();
- return;
- }
- };
- reverseFilter.filterName = 'trivial';
- exports.diffFilter = diffFilter;
- exports.patchFilter = patchFilter;
- exports.reverseFilter = reverseFilter;
- },{}],19:[function(require,module,exports){
- var environment = require('./environment');
- var DiffPatcher = require('./diffpatcher').DiffPatcher;
- exports.DiffPatcher = DiffPatcher;
- exports.create = function(options){
- return new DiffPatcher(options);
- };
- exports.dateReviver = require('./date-reviver');
- var defaultInstance;
- exports.diff = function() {
- if (!defaultInstance) {
- defaultInstance = new DiffPatcher();
- }
- return defaultInstance.diff.apply(defaultInstance, arguments);
- };
- exports.patch = function() {
- if (!defaultInstance) {
- defaultInstance = new DiffPatcher();
- }
- return defaultInstance.patch.apply(defaultInstance, arguments);
- };
- exports.unpatch = function() {
- if (!defaultInstance) {
- defaultInstance = new DiffPatcher();
- }
- return defaultInstance.unpatch.apply(defaultInstance, arguments);
- };
- exports.reverse = function() {
- if (!defaultInstance) {
- defaultInstance = new DiffPatcher();
- }
- return defaultInstance.reverse.apply(defaultInstance, arguments);
- };
- if (environment.isBrowser) {
- exports.homepage = '{{package-homepage}}';
- exports.version = '{{package-version}}';
- } else {
- var packageInfoModuleName = '../package.json';
- var packageInfo = require(packageInfoModuleName);
- exports.homepage = packageInfo.homepage;
- exports.version = packageInfo.version;
- var formatterModuleName = './formatters';
- var formatters = require(formatterModuleName);
- exports.formatters = formatters;
- // shortcut for console
- exports.console = formatters.console;
- }
- },{"./date-reviver":10,"./diffpatcher":11,"./environment":12}],20:[function(require,module,exports){
- var Pipe = function Pipe(name) {
- this.name = name;
- this.filters = [];
- };
- Pipe.prototype.process = function(input) {
- if (!this.processor) {
- throw new Error('add this pipe to a processor before using it');
- }
- var debug = this.debug;
- var length = this.filters.length;
- var context = input;
- for (var index = 0; index < length; index++) {
- var filter = this.filters[index];
- if (debug) {
- this.log('filter: ' + filter.filterName);
- }
- filter(context);
- if (typeof context === 'object' && context.exiting) {
- context.exiting = false;
- break;
- }
- }
- if (!context.next && this.resultCheck) {
- this.resultCheck(context);
- }
- };
- Pipe.prototype.log = function(msg) {
- console.log('[jsondiffpatch] ' + this.name + ' pipe, ' + msg);
- };
- Pipe.prototype.append = function() {
- this.filters.push.apply(this.filters, arguments);
- return this;
- };
- Pipe.prototype.prepend = function() {
- this.filters.unshift.apply(this.filters, arguments);
- return this;
- };
- Pipe.prototype.indexOf = function(filterName) {
- if (!filterName) {
- throw new Error('a filter name is required');
- }
- for (var index = 0; index < this.filters.length; index++) {
- var filter = this.filters[index];
- if (filter.filterName === filterName) {
- return index;
- }
- }
- throw new Error('filter not found: ' + filterName);
- };
- Pipe.prototype.list = function() {
- var names = [];
- for (var index = 0; index < this.filters.length; index++) {
- var filter = this.filters[index];
- names.push(filter.filterName);
- }
- return names;
- };
- Pipe.prototype.after = function(filterName) {
- var index = this.indexOf(filterName);
- var params = Array.prototype.slice.call(arguments, 1);
- if (!params.length) {
- throw new Error('a filter is required');
- }
- params.unshift(index + 1, 0);
- Array.prototype.splice.apply(this.filters, params);
- return this;
- };
- Pipe.prototype.before = function(filterName) {
- var index = this.indexOf(filterName);
- var params = Array.prototype.slice.call(arguments, 1);
- if (!params.length) {
- throw new Error('a filter is required');
- }
- params.unshift(index, 0);
- Array.prototype.splice.apply(this.filters, params);
- return this;
- };
- Pipe.prototype.clear = function() {
- this.filters.length = 0;
- return this;
- };
- Pipe.prototype.shouldHaveResult = function(should) {
- if (should === false) {
- this.resultCheck = null;
- return;
- }
- if (this.resultCheck) {
- return;
- }
- var pipe = this;
- this.resultCheck = function(context) {
- if (!context.hasResult) {
- console.log(context);
- var error = new Error(pipe.name + ' failed');
- error.noResult = true;
- throw error;
- }
- };
- return this;
- };
- exports.Pipe = Pipe;
- },{}],21:[function(require,module,exports){
- var Processor = function Processor(options){
- this.selfOptions = options || {};
- this.pipes = {};
- };
- Processor.prototype.options = function(options) {
- if (options) {
- this.selfOptions = options;
- }
- return this.selfOptions;
- };
- Processor.prototype.pipe = function(name, pipe) {
- if (typeof name === 'string') {
- if (typeof pipe === 'undefined') {
- return this.pipes[name];
- } else {
- this.pipes[name] = pipe;
- }
- }
- if (name && name.name) {
- pipe = name;
- if (pipe.processor === this) { return pipe; }
- this.pipes[pipe.name] = pipe;
- }
- pipe.processor = this;
- return pipe;
- };
- Processor.prototype.process = function(input, pipe) {
- var context = input;
- context.options = this.options();
- var nextPipe = pipe || input.pipe || 'default';
- var lastPipe, lastContext;
- while (nextPipe) {
- if (typeof context.nextAfterChildren !== 'undefined') {
- // children processed and coming back to parent
- context.next = context.nextAfterChildren;
- context.nextAfterChildren = null;
- }
- if (typeof nextPipe === 'string') {
- nextPipe = this.pipe(nextPipe);
- }
- nextPipe.process(context);
- lastContext = context;
- lastPipe = nextPipe;
- nextPipe = null;
- if (context) {
- if (context.next) {
- context = context.next;
- nextPipe = lastContext.nextPipe || context.pipe || lastPipe;
- }
- }
- }
- return context.hasResult ? context.result : undefined;
- };
- exports.Processor = Processor;
- },{}],22:[function(require,module,exports){
- exports.RateLimiter = require('./lib/rateLimiter');
- exports.TokenBucket = require('./lib/tokenBucket');
- },{"./lib/rateLimiter":24,"./lib/tokenBucket":25}],23:[function(require,module,exports){
- (function (process){
- var getMilliseconds = function() {
- if (typeof process !== 'undefined' && process.hrtime) {
- var hrtime = process.hrtime();
- var seconds = hrtime[0];
- var nanoseconds = hrtime[1];
- return seconds * 1e3 + Math.floor(nanoseconds / 1e6);
- }
- return new Date().getTime();
- }
- module.exports = getMilliseconds;
- }).call(this,require('_process'))
- },{"_process":26}],24:[function(require,module,exports){
- (function (process){
- var TokenBucket = require('./tokenBucket');
- var getMilliseconds = require('./clock');
- /**
- * A generic rate limiter. Underneath the hood, this uses a token bucket plus
- * an additional check to limit how many tokens we can remove each interval.
- * @author John Hurliman <jhurliman@jhurliman.org>
- *
- * @param {Number} tokensPerInterval Maximum number of tokens that can be
- * removed at any given moment and over the course of one interval.
- * @param {String|Number} interval The interval length in milliseconds, or as
- * one of the following strings: 'second', 'minute', 'hour', day'.
- * @param {Boolean} fireImmediately Optional. Whether or not the callback
- * will fire immediately when rate limiting is in effect (default is false).
- */
- var RateLimiter = function(tokensPerInterval, interval, fireImmediately) {
- this.tokenBucket = new TokenBucket(tokensPerInterval, tokensPerInterval,
- interval, null);
- // Fill the token bucket to start
- this.tokenBucket.content = tokensPerInterval;
- this.curIntervalStart = getMilliseconds();
- this.tokensThisInterval = 0;
- this.fireImmediately = fireImmediately;
- };
- RateLimiter.prototype = {
- tokenBucket: null,
- curIntervalStart: 0,
- tokensThisInterval: 0,
- fireImmediately: false,
- /**
- * Remove the requested number of tokens and fire the given callback. If the
- * rate limiter contains enough tokens and we haven't spent too many tokens
- * in this interval already, this will happen immediately. Otherwise, the
- * removal and callback will happen when enough tokens become available.
- * @param {Number} count The number of tokens to remove.
- * @param {Function} callback(err, remainingTokens)
- * @returns {Boolean} True if the callback was fired immediately, otherwise
- * false.
- */
- removeTokens: function(count, callback) {
- // Make sure the request isn't for more than we can handle
- if (count > this.tokenBucket.bucketSize) {
- process.nextTick(callback.bind(null, 'Requested tokens ' + count +
- ' exceeds maximum tokens per interval ' + this.tokenBucket.bucketSize,
- null));
- return false;
- }
- var self = this;
- var now = getMilliseconds();
- // Advance the current interval and reset the current interval token count
- // if needed
- if (now < this.curIntervalStart
- || now - this.curIntervalStart >= this.tokenBucket.interval) {
- this.curIntervalStart = now;
- this.tokensThisInterval = 0;
- }
- // If we don't have enough tokens left in this interval, wait until the
- // next interval
- if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {
- if (this.fireImmediately) {
- process.nextTick(callback.bind(null, null, -1));
- } else {
- var waitInterval = Math.ceil(
- this.curIntervalStart + this.tokenBucket.interval - now);
- setTimeout(function() {
- self.tokenBucket.removeTokens(count, afterTokensRemoved);
- }, waitInterval);
- }
- return false;
- }
- // Remove the requested number of tokens from the token bucket
- return this.tokenBucket.removeTokens(count, afterTokensRemoved);
- function afterTokensRemoved(err, tokensRemaining) {
- if (err) return callback(err, null);
- self.tokensThisInterval += count;
- callback(null, tokensRemaining);
- }
- },
- /**
- * Attempt to remove the requested number of tokens and return immediately.
- * If the bucket (and any parent buckets) contains enough tokens and we
- * haven't spent too many tokens in this interval already, this will return
- * true. Otherwise, false is returned.
- * @param {Number} count The number of tokens to remove.
- * @param {Boolean} True if the tokens were successfully removed, otherwise
- * false.
- */
- tryRemoveTokens: function(count) {
- // Make sure the request isn't for more than we can handle
- if (count > this.tokenBucket.bucketSize)
- return false;
- var now = getMilliseconds();
- // Advance the current interval and reset the current interval token count
- // if needed
- if (now < this.curIntervalStart
- || now - this.curIntervalStart >= this.tokenBucket.interval) {
- this.curIntervalStart = now;
- this.tokensThisInterval = 0;
- }
- // If we don't have enough tokens left in this interval, return false
- if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval)
- return false;
- // Try to remove the requested number of tokens from the token bucket
- var removed = this.tokenBucket.tryRemoveTokens(count);
- if (removed) {
- this.tokensThisInterval += count;
- }
- return removed;
- },
- /**
- * Returns the number of tokens remaining in the TokenBucket.
- * @returns {Number} The number of tokens remaining.
- */
- getTokensRemaining: function () {
- this.tokenBucket.drip();
- return this.tokenBucket.content;
- }
- };
- module.exports = RateLimiter;
- }).call(this,require('_process'))
- },{"./clock":23,"./tokenBucket":25,"_process":26}],25:[function(require,module,exports){
- (function (process){
- /**
- * A hierarchical token bucket for rate limiting. See
- * http://en.wikipedia.org/wiki/Token_bucket for more information.
- * @author John Hurliman <jhurliman@cull.tv>
- *
- * @param {Number} bucketSize Maximum number of tokens to hold in the bucket.
- * Also known as the burst rate.
- * @param {Number} tokensPerInterval Number of tokens to drip into the bucket
- * over the course of one interval.
- * @param {String|Number} interval The interval length in milliseconds, or as
- * one of the following strings: 'second', 'minute', 'hour', day'.
- * @param {TokenBucket} parentBucket Optional. A token bucket that will act as
- * the parent of this bucket.
- */
- var TokenBucket = function(bucketSize, tokensPerInterval, interval, parentBucket) {
- this.bucketSize = bucketSize;
- this.tokensPerInterval = tokensPerInterval;
- if (typeof interval === 'string') {
- switch (interval) {
- case 'sec': case 'second':
- this.interval = 1000; break;
- case 'min': case 'minute':
- this.interval = 1000 * 60; break;
- case 'hr': case 'hour':
- this.interval = 1000 * 60 * 60; break;
- case 'day':
- this.interval = 1000 * 60 * 60 * 24; break;
- default:
- throw new Error('Invaid interval ' + interval);
- }
- } else {
- this.interval = interval;
- }
- this.parentBucket = parentBucket;
- this.content = 0;
- this.lastDrip = +new Date();
- };
- TokenBucket.prototype = {
- bucketSize: 1,
- tokensPerInterval: 1,
- interval: 1000,
- parentBucket: null,
- content: 0,
- lastDrip: 0,
- /**
- * Remove the requested number of tokens and fire the given callback. If the
- * bucket (and any parent buckets) contains enough tokens this will happen
- * immediately. Otherwise, the removal and callback will happen when enough
- * tokens become available.
- * @param {Number} count The number of tokens to remove.
- * @param {Function} callback(err, remainingTokens)
- * @returns {Boolean} True if the callback was fired immediately, otherwise
- * false.
- */
- removeTokens: function(count, callback) {
- var self = this;
- // Is this an infinite size bucket?
- if (!this.bucketSize) {
- process.nextTick(callback.bind(null, null, count, Number.POSITIVE_INFINITY));
- return true;
- }
- // Make sure the bucket can hold the requested number of tokens
- if (count > this.bucketSize) {
- process.nextTick(callback.bind(null, 'Requested tokens ' + count + ' exceeds bucket size ' +
- this.bucketSize, null));
- return false;
- }
- // Drip new tokens into this bucket
- this.drip();
- // If we don't have enough tokens in this bucket, come back later
- if (count > this.content)
- return comeBackLater();
- if (this.parentBucket) {
- // Remove the requested from the parent bucket first
- return this.parentBucket.removeTokens(count, function(err, remainingTokens) {
- if (err) return callback(err, null);
- // Check that we still have enough tokens in this bucket
- if (count > self.content)
- return comeBackLater();
- // Tokens were removed from the parent bucket, now remove them from
- // this bucket and fire the callback. Note that we look at the current
- // bucket and parent bucket's remaining tokens and return the smaller
- // of the two values
- self.content -= count;
- callback(null, Math.min(remainingTokens, self.content));
- });
- } else {
- // Remove the requested tokens from this bucket and fire the callback
- this.content -= count;
- process.nextTick(callback.bind(null, null, this.content));
- return true;
- }
- function comeBackLater() {
- // How long do we need to wait to make up the difference in tokens?
- var waitInterval = Math.ceil(
- (count - self.content) * (self.interval / self.tokensPerInterval));
- setTimeout(function() { self.removeTokens(count, callback); }, waitInterval);
- return false;
- }
- },
- /**
- * Attempt to remove the requested number of tokens and return immediately.
- * If the bucket (and any parent buckets) contains enough tokens this will
- * return true, otherwise false is returned.
- * @param {Number} count The number of tokens to remove.
- * @param {Boolean} True if the tokens were successfully removed, otherwise
- * false.
- */
- tryRemoveTokens: function(count) {
- // Is this an infinite size bucket?
- if (!this.bucketSize)
- return true;
- // Make sure the bucket can hold the requested number of tokens
- if (count > this.bucketSize)
- return false;
- // Drip new tokens into this bucket
- this.drip();
- // If we don't have enough tokens in this bucket, return false
- if (count > this.content)
- return false;
- // Try to remove the requested tokens from the parent bucket
- if (this.parentBucket && !this.parent.tryRemoveTokens(count))
- return false;
- // Remove the requested tokens from this bucket and return
- this.content -= count;
- return true;
- },
- /**
- * Add any new tokens to the bucket since the last drip.
- * @returns {Boolean} True if new tokens were added, otherwise false.
- */
- drip: function() {
- if (!this.tokensPerInterval) {
- this.content = this.bucketSize;
- return;
- }
- var now = +new Date();
- var deltaMS = Math.max(now - this.lastDrip, 0);
- this.lastDrip = now;
- var dripAmount = deltaMS * (this.tokensPerInterval / this.interval);
- this.content = Math.min(this.content + dripAmount, this.bucketSize);
- }
- };
- module.exports = TokenBucket;
- }).call(this,require('_process'))
- },{"_process":26}],26:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // 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
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // 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.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.prependListener = noop;
- process.prependOnceListener = noop;
- process.listeners = function (name) { return [] }
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- },{}],27:[function(require,module,exports){
- module.exports = OmegaPac;
- },{}],28:[function(require,module,exports){
- var BrowserStorage, Promise, Storage,
- 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; },
- hasProp = {}.hasOwnProperty;
- Storage = require('./storage');
- Promise = require('bluebird');
- BrowserStorage = (function(superClass) {
- extend(BrowserStorage, superClass);
- function BrowserStorage(storage, prefix) {
- this.storage = storage;
- this.prefix = prefix != null ? prefix : '';
- this.proto = Object.getPrototypeOf(this.storage);
- }
- BrowserStorage.prototype.get = function(keys) {
- var i, key, len, map, value;
- map = {};
- if (typeof keys === 'string') {
- map[keys] = void 0;
- } else if (Array.isArray(keys)) {
- for (i = 0, len = keys.length; i < len; i++) {
- key = keys[i];
- map[key] = void 0;
- }
- } else if (typeof keys === 'object') {
- map = keys;
- }
- for (key in map) {
- if (!hasProp.call(map, key)) continue;
- try {
- value = JSON.parse(this.proto.getItem.call(this.storage, this.prefix + key));
- } catch (error) {}
- if (value != null) {
- map[key] = value;
- }
- if (typeof map[key] === 'undefined') {
- delete map[key];
- }
- }
- return Promise.resolve(map);
- };
- BrowserStorage.prototype.set = function(items) {
- var key, value;
- for (key in items) {
- if (!hasProp.call(items, key)) continue;
- value = items[key];
- value = JSON.stringify(value);
- this.proto.setItem.call(this.storage, this.prefix + key, value);
- }
- return Promise.resolve(items);
- };
- BrowserStorage.prototype.remove = function(keys) {
- var i, index, key, len;
- if (keys == null) {
- if (!this.prefix) {
- this.proto.clear.call(this.storage);
- } else {
- index = 0;
- while (true) {
- key = this.proto.key.call(index);
- if (key === null) {
- break;
- }
- if (this.key.substr(0, this.prefix.length) === this.prefix) {
- this.proto.removeItem.call(this.storage, this.prefix + keys);
- } else {
- index++;
- }
- }
- }
- }
- if (typeof keys === 'string') {
- this.proto.removeItem.call(this.storage, this.prefix + keys);
- }
- for (i = 0, len = keys.length; i < len; i++) {
- key = keys[i];
- this.proto.removeItem.call(this.storage, this.prefix + key);
- }
- return Promise.resolve();
- };
- return BrowserStorage;
- })(Storage);
- module.exports = BrowserStorage;
- },{"./storage":34,"bluebird":2}],29:[function(require,module,exports){
- module.exports = function() {
- return {
- schemaVersion: 2,
- "-enableQuickSwitch": false,
- "-refreshOnProfileChange": true,
- "-startupProfileName": "",
- "-quickSwitchProfiles": [],
- "-revertProxyChanges": true,
- "-confirmDeletion": true,
- "-showInspectMenu": true,
- "-addConditionsToBottom": false,
- "-showExternalProfile": true,
- "-downloadInterval": 1440,
- "+proxy": {
- bypassList: [
- {
- pattern: "127.0.0.1",
- conditionType: "BypassCondition"
- }, {
- pattern: "::1",
- conditionType: "BypassCondition"
- }, {
- pattern: "localhost",
- conditionType: "BypassCondition"
- }
- ],
- profileType: "FixedProfile",
- name: "proxy",
- color: "#99ccee",
- fallbackProxy: {
- port: 8080,
- scheme: "http",
- host: "proxy.example.com"
- }
- },
- "+auto switch": {
- profileType: "SwitchProfile",
- rules: [
- {
- condition: {
- pattern: "internal.example.com",
- conditionType: "HostWildcardCondition"
- },
- profileName: "direct"
- }, {
- condition: {
- pattern: "*.example.com",
- conditionType: "HostWildcardCondition"
- },
- profileName: "proxy"
- }
- ],
- name: "auto switch",
- color: "#99dd99",
- defaultProfileName: "direct"
- }
- };
- };
- },{}],30:[function(require,module,exports){
- var ContentTypeRejectedError, HttpError, HttpNotFoundError, HttpServerError, NetworkError,
- 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; },
- hasProp = {}.hasOwnProperty;
- NetworkError = (function(superClass) {
- extend(NetworkError, superClass);
- function NetworkError(err) {
- NetworkError.__super__.constructor.apply(this, arguments);
- this.cause = err;
- this.name = 'NetworkError';
- }
- return NetworkError;
- })(Error);
- HttpError = (function(superClass) {
- extend(HttpError, superClass);
- function HttpError() {
- var ref;
- HttpError.__super__.constructor.apply(this, arguments);
- this.statusCode = (ref = this.cause) != null ? ref.statusCode : void 0;
- this.name = 'HttpError';
- }
- return HttpError;
- })(NetworkError);
- HttpNotFoundError = (function(superClass) {
- extend(HttpNotFoundError, superClass);
- function HttpNotFoundError() {
- HttpNotFoundError.__super__.constructor.apply(this, arguments);
- this.name = 'HttpNotFoundError';
- }
- return HttpNotFoundError;
- })(HttpError);
- HttpServerError = (function(superClass) {
- extend(HttpServerError, superClass);
- function HttpServerError() {
- HttpServerError.__super__.constructor.apply(this, arguments);
- this.name = 'HttpServerError';
- }
- return HttpServerError;
- })(HttpError);
- ContentTypeRejectedError = (function(superClass) {
- extend(ContentTypeRejectedError, superClass);
- function ContentTypeRejectedError() {
- ContentTypeRejectedError.__super__.constructor.apply(this, arguments);
- this.name = 'ContentTypeRejectedError';
- }
- return ContentTypeRejectedError;
- })(Error);
- module.exports = {
- NetworkError: NetworkError,
- HttpError: HttpError,
- HttpNotFoundError: HttpNotFoundError,
- HttpServerError: HttpServerError,
- ContentTypeRejectedError: ContentTypeRejectedError
- };
- },{}],31:[function(require,module,exports){
- /* @module omega-target/log */
- var Log, replacer;
- Log = require('./log');
- replacer = function(key, value) {
- switch (key) {
- case "username":
- case "password":
- case "host":
- case "port":
- return "<secret>";
- default:
- return value;
- }
- };
- module.exports = Log = {
- /**
- * Pretty-print an object and return the result string.
- * @param {{}} obj The object to format
- * @returns {String} the formatted object in string
- */
- str: function(obj) {
- if (typeof obj === 'object' && obj !== null) {
- if (obj.debugStr != null) {
- if (typeof obj.debugStr === 'function') {
- return obj.debugStr();
- } else {
- return obj.debugStr;
- }
- } else if (obj instanceof Error) {
- return obj.stack || obj.message;
- } else {
- return JSON.stringify(obj, replacer, 4);
- }
- } else if (typeof obj === 'function') {
- if (obj.name) {
- return "<f: " + obj.name + ">";
- } else {
- return obj.toString();
- }
- } else {
- return '' + obj;
- }
- },
- /**
- * Print something to the log.
- * @param {...{}} args The objects to log
- */
- log: console.log.bind(console),
- /**
- * Print something to the error log.
- * @param {...{}} args The objects to log
- */
- error: console.error.bind(console),
- /**
- * Log a function call with target and arguments
- * @param {string} name The name of the method
- * @param {Array} args The arguments to the method call
- */
- func: function(name, args) {
- return this.log(name, '(', [].slice.call(args), ')');
- },
- /**
- * Log a method call with target and arguments
- * @param {string} name The name of the method
- * @param {{}} self The target of the method call
- * @param {Array} args The arguments to the method call
- */
- method: function(name, self, args) {
- return this.log(this.str(self), '<<', name, [].slice.call(args));
- }
- };
- },{"./log":31}],32:[function(require,module,exports){
- /* @module omega-target/options */
- var Log, OmegaPac, Options, Promise, Storage, jsondiffpatch,
- bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
- 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; },
- hasProp = {}.hasOwnProperty;
- Promise = require('bluebird');
- Log = require('./log');
- Storage = require('./storage');
- OmegaPac = require('omega-pac');
- jsondiffpatch = require('jsondiffpatch');
- Options = (function() {
- /**
- * The entire set of options including profiles and other settings.
- * @typedef OmegaOptions
- * @type {object}
- */
- /**
- * All the options, in a map from key to value.
- * @type OmegaOptions
- */
- var NoOptionsError, ProfileNotExistError;
- Options.prototype._options = null;
- Options.prototype._storage = null;
- Options.prototype._state = null;
- Options.prototype._currentProfileName = null;
- Options.prototype._revertToProfileName = null;
- Options.prototype._watchingProfiles = {};
- Options.prototype._tempProfile = null;
- Options.prototype._tempProfileActive = false;
- Options.prototype.fallbackProfileName = 'system';
- Options.prototype._isSystem = false;
- Options.prototype.debugStr = 'Options';
- Options.prototype.ready = null;
- Options.ProfileNotExistError = ProfileNotExistError = (function(superClass) {
- extend(ProfileNotExistError, superClass);
- function ProfileNotExistError(profileName1) {
- this.profileName = profileName1;
- ProfileNotExistError.__super__.constructor.apply(this, arguments).constructor("Profile " + this.profileName + " does not exist!");
- }
- return ProfileNotExistError;
- })(Error);
- Options.NoOptionsError = NoOptionsError = (function(superClass) {
- extend(NoOptionsError, superClass);
- function NoOptionsError() {
- NoOptionsError.__super__.constructor.apply(this, arguments);
- }
- return NoOptionsError;
- })(Error);
- /**
- * Transform options values (especially profiles) for syncing.
- * @param {{}} value The value to transform
- * @param {{}} key The key of the options
- * @returns {{}} The transformed value
- */
- Options.transformValueForSync = function(value, key) {
- var k, profile, v;
- if (key[0] === '+') {
- if (OmegaPac.Profiles.updateUrl(value)) {
- profile = {};
- for (k in value) {
- v = value[k];
- if (k === 'lastUpdate' || k === 'ruleList' || k === 'pacScript') {
- continue;
- }
- profile[k] = v;
- }
- value = profile;
- }
- }
- return value;
- };
- function Options(options, _storage, _state, log, sync, proxyImpl) {
- this._storage = _storage;
- this._state = _state;
- this.log = log;
- this.sync = sync;
- this.proxyImpl = proxyImpl;
- this._setOptions = bind(this._setOptions, this);
- this._options = {};
- this._tempProfileRules = {};
- this._tempProfileRulesByProfile = {};
- if (this._storage == null) {
- this._storage = Storage();
- }
- if (this._state == null) {
- this._state = Storage();
- }
- if (this.log == null) {
- this.log = Log;
- }
- if (options == null) {
- this.init();
- } else {
- this.ready = this._storage.remove().then((function(_this) {
- return function() {
- return _this._storage.set(options);
- };
- })(this)).then((function(_this) {
- return function() {
- return _this.init();
- };
- })(this));
- }
- }
- /**
- * Attempt to load options from local and remote storage.
- * @param {?{}} args Extra arguments
- * @param {number=3} args.retry Number of retries before giving up.
- * @returns {Promise<OmegaOptions>} The loaded options
- */
- Options.prototype.loadOptions = function(arg) {
- var loadRaw, ref, retry;
- retry = (arg != null ? arg : {}).retry;
- if (retry == null) {
- retry = 3;
- }
- if (typeof this._syncWatchStop === "function") {
- this._syncWatchStop();
- }
- this._syncWatchStop = null;
- if (typeof this._watchStop === "function") {
- this._watchStop();
- }
- this._watchStop = null;
- loadRaw = typeof options !== "undefined" && options !== null ? Promise.resolve(options) : !((ref = this.sync) != null ? ref.enabled : void 0) ? (this.sync == null ? this._state.set({
- 'syncOptions': 'unsupported'
- }) : void 0, this._storage.get(null)) : (this._state.set({
- 'syncOptions': 'sync'
- }), this._syncWatchStop = this.sync.watchAndPull(this._storage), this.sync.copyTo(this._storage)["catch"](Storage.StorageUnavailableError, (function(_this) {
- return function() {
- console.error('Warning: Sync storage is not available in this ' + 'browser! Disabling options sync.');
- if (typeof _this._syncWatchStop === "function") {
- _this._syncWatchStop();
- }
- _this._syncWatchStop = null;
- _this.sync = null;
- return _this._state.set({
- 'syncOptions': 'unsupported'
- });
- };
- })(this)).then((function(_this) {
- return function() {
- return _this._storage.get(null);
- };
- })(this)));
- return this.optionsLoaded = loadRaw.then((function(_this) {
- return function(options) {
- return _this.upgrade(options);
- };
- })(this)).then((function(_this) {
- return function(arg1) {
- var changes, options;
- options = arg1[0], changes = arg1[1];
- return _this._storage.apply({
- changes: changes
- })["return"](options);
- };
- })(this)).tap((function(_this) {
- return function(options) {
- _this._options = options;
- _this._watchStop = _this._watch();
- return _this._state.get({
- 'syncOptions': ''
- }).then(function(arg1) {
- var syncOptions;
- syncOptions = arg1.syncOptions;
- if (syncOptions) {
- return;
- }
- _this._state.set({
- 'syncOptions': 'conflict'
- });
- return _this.sync.storage.get('schemaVersion').then(function(arg2) {
- var schemaVersion;
- schemaVersion = arg2.schemaVersion;
- if (!schemaVersion) {
- return _this._state.set({
- 'syncOptions': 'pristine'
- });
- }
- });
- });
- };
- })(this))["catch"]((function(_this) {
- return function(e) {
- var getFallbackOptions;
- if (!(retry > 0)) {
- return Promise.reject(e);
- }
- getFallbackOptions = Promise.resolve().then(function() {
- if (e instanceof NoOptionsError) {
- _this._state.get({
- 'firstRun': 'new',
- 'web.switchGuide': 'showOnFirstUse'
- }).then(function(items) {
- return _this._state.set(items);
- });
- if (_this.sync == null) {
- return null;
- }
- return _this._state.get({
- 'syncOptions': ''
- }).then(function(arg1) {
- var syncOptions;
- syncOptions = arg1.syncOptions;
- if (syncOptions === 'conflict') {
- return;
- }
- return _this.sync.storage.get(null).then(function(options) {
- if (!options['schemaVersion']) {
- _this._state.set({
- 'syncOptions': 'pristine'
- });
- return null;
- } else {
- _this._state.set({
- 'syncOptions': 'sync'
- });
- _this.sync.enabled = true;
- _this.log.log('Options#loadOptions::fromSync', options);
- return options;
- }
- })["catch"](function() {
- return null;
- });
- });
- } else {
- _this.log.error(e.stack);
- _this._state.remove(['syncOptions']);
- return null;
- }
- });
- return getFallbackOptions.then(function(options) {
- var prevEnabled;
- if (options == null) {
- options = _this.parseOptions(_this.getDefaultOptions());
- }
- if (_this.sync != null) {
- prevEnabled = _this.sync.enabled;
- _this.sync.enabled = false;
- }
- return _this._storage.remove().then(function() {
- return _this._storage.set(options);
- }).then(function() {
- if (_this.sync != null) {
- _this.sync.enabled = prevEnabled;
- }
- return _this.loadOptions({
- retry: retry - 1
- });
- });
- });
- };
- })(this));
- };
- /**
- * Attempt to initialize (or reinitialize) options.
- * @returns {Promise<OmegaOptions>} A promise that is fulfilled on ready.
- */
- Options.prototype.init = function() {
- this.ready = this.loadOptions().then((function(_this) {
- return function() {
- if (_this._options['-startupProfileName']) {
- return _this.applyProfile(_this._options['-startupProfileName']);
- } else {
- return _this._state.get({
- 'currentProfileName': _this.fallbackProfileName,
- 'isSystemProfile': false
- }).then(function(st) {
- if (st['isSystemProfile']) {
- return _this.applyProfile('system');
- } else {
- return _this.applyProfile(st['currentProfileName'] || _this.fallbackProfileName);
- }
- });
- }
- };
- })(this))["catch"]((function(_this) {
- return function(err) {
- if (!err instanceof ProfileNotExistError) {
- _this.log.error(err);
- }
- return _this.applyProfile(_this.fallbackProfileName);
- };
- })(this))["catch"]((function(_this) {
- return function(err) {
- return _this.log.error(err);
- };
- })(this)).then((function(_this) {
- return function() {
- return _this.getAll();
- };
- })(this));
- this.ready.then((function(_this) {
- return function() {
- var ref;
- if ((ref = _this.sync) != null ? ref.enabled : void 0) {
- _this.sync.requestPush(_this._options);
- }
- _this._state.get({
- 'firstRun': ''
- }).then(function(arg) {
- var firstRun;
- firstRun = arg.firstRun;
- if (firstRun) {
- return _this.onFirstRun(firstRun);
- }
- });
- if (_this._options['-downloadInterval'] > 0) {
- return _this.updateProfile();
- }
- };
- })(this));
- return this.ready;
- };
- Options.prototype.toString = function() {
- return "<Options>";
- };
- /**
- * Return a localized, human-readable description of the given profile.
- * In base class, this method is not implemented and will always return null.
- * @param {?{}} profile The profile to print
- * @returns {string} Description of the profile with details
- */
- Options.prototype.printProfile = function(profile) {
- return null;
- };
- /**
- * Upgrade options from previous versions.
- * For now, this method only supports schemaVersion 1 and 2. If so, it upgrades
- * the options to version 2 (the latest version). Otherwise it rejects.
- * It is recommended for the derived classes to call super() two times in the
- * beginning and in the end of the implementation to check the schemaVersion
- * and to apply future upgrades, respectively.
- * Example: super(options).catch -> super(doCustomUpgrades(options), changes)
- * @param {?OmegaOptions} options The legacy options to upgrade
- * @param {{}={}} changes Previous pending changes to be applied. Default to
- * an empty dictionary. Please provide this argument when calling super().
- * @returns {Promise<[OmegaOptions, {}]>} The new options and the changes.
- */
- Options.prototype.upgrade = function(options, changes) {
- var autoDetectUsed, version;
- if (changes == null) {
- changes = {};
- }
- version = options != null ? options['schemaVersion'] : void 0;
- if (version === 1) {
- autoDetectUsed = false;
- OmegaPac.Profiles.each(options, function(key, profile) {
- var refs;
- if (!autoDetectUsed) {
- refs = OmegaPac.Profiles.directReferenceSet(profile);
- if (refs['+auto_detect']) {
- return autoDetectUsed = true;
- }
- }
- });
- if (autoDetectUsed) {
- options['+auto_detect'] = OmegaPac.Profiles.create({
- name: 'auto_detect',
- profileType: 'PacProfile',
- pacUrl: 'http://wpad/wpad.dat',
- color: '#00cccc'
- });
- }
- version = changes['schemaVersion'] = options['schemaVersion'] = 2;
- }
- if (version === 2) {
- return Promise.resolve([options, changes]);
- } else {
- return Promise.reject(new Error("Invalid schemaVerion " + version + "!"));
- }
- };
- /**
- * Parse options in various formats (including JSON & base64).
- * @param {OmegaOptions|string} options The options to parse
- * @returns {Promise<OmegaOptions>} The parsed options.
- */
- Options.prototype.parseOptions = function(options) {
- var Buffer, _;
- if (typeof options === 'string') {
- if (options[0] !== '{') {
- try {
- Buffer = require('buffer').Buffer;
- options = new Buffer(options, 'base64').toString('utf8');
- } catch (error) {
- _ = error;
- options = null;
- }
- }
- options = (function() {
- try {
- return JSON.parse(options);
- } catch (error) {}
- })();
- }
- if (!options) {
- throw new Error('Invalid options!');
- }
- return options;
- };
- /**
- * Reset the options to the given options or initial options.
- * @param {?OmegaOptions} options The options to set. Defaults to initial.
- * @returns {Promise<OmegaOptions>} The options just applied
- */
- Options.prototype.reset = function(options) {
- this.log.method('Options#reset', this, arguments);
- if (options == null) {
- options = this.getDefaultOptions();
- }
- return this.upgrade(this.parseOptions(options)).then((function(_this) {
- return function(arg) {
- var opt;
- opt = arg[0];
- if (_this.sync != null) {
- _this.sync.enabled = false;
- }
- _this._state.remove(['syncOptions']);
- return _this._storage.remove().then(function() {
- return _this._storage.set(opt);
- }).then(function() {
- return _this.init();
- });
- };
- })(this));
- };
- /**
- * Called on the first initialization of options.
- * @param {reason} reason The value of 'firstRun' in state.
- */
- Options.prototype.onFirstRun = function(reason) {
- return null;
- };
- /**
- * Return the default options used initially and on resets.
- * @returns {?OmegaOptions} The default options.
- */
- Options.prototype.getDefaultOptions = function() {
- return require('./default_options')();
- };
- /**
- * Return all options.
- * @returns {?OmegaOptions} The options.
- */
- Options.prototype.getAll = function() {
- return this._options;
- };
- /**
- * Get profile by name.
- * @returns {?{}} The profile, or undefined if no such profile.
- */
- Options.prototype.profile = function(name) {
- return OmegaPac.Profiles.byName(name, this._options);
- };
- /**
- * Apply the patch to the current options.
- * @param {jsondiffpatch} patch The patch to apply
- * @returns {Promise<OmegaOptions>} The updated options
- */
- Options.prototype.patch = function(patch) {
- var changes, delta, key;
- if (!patch) {
- return;
- }
- this.log.method('Options#patch', this, arguments);
- this._options = jsondiffpatch.patch(this._options, patch);
- changes = {};
- for (key in patch) {
- if (!hasProp.call(patch, key)) continue;
- delta = patch[key];
- if (delta.length === 3 && delta[1] === 0 && delta[2] === 0) {
- changes[key] = void 0;
- } else {
- changes[key] = this._options[key];
- }
- }
- return this._setOptions(changes);
- };
- Options.prototype._setOptions = function(changes, args) {
- var checkRev, currentProfileAffected, j, key, len, profilesChanged, ref, ref1, ref2, ref3, removed, result, value;
- removed = [];
- checkRev = (ref = args != null ? args.checkRevision : void 0) != null ? ref : false;
- profilesChanged = false;
- currentProfileAffected = false;
- for (key in changes) {
- if (!hasProp.call(changes, key)) continue;
- value = changes[key];
- if (typeof value === 'undefined') {
- delete this._options[key];
- removed.push(key);
- if (key[0] === '+') {
- profilesChanged = true;
- if (key === '+' + this._currentProfileName) {
- currentProfileAffected = 'removed';
- }
- }
- } else {
- if (key[0] === '+') {
- if (checkRev && this._options[key]) {
- result = OmegaPac.Revision.compare(this._options[key].revision, value.revision);
- if (result >= 0) {
- continue;
- }
- }
- profilesChanged = true;
- }
- this._options[key] = value;
- }
- if (!currentProfileAffected && this._watchingProfiles[key]) {
- currentProfileAffected = 'changed';
- }
- }
- switch (currentProfileAffected) {
- case 'removed':
- this.applyProfile(this.fallbackProfileName);
- break;
- case 'changed':
- this.applyProfile(this._currentProfileName, {
- update: false
- });
- break;
- default:
- if (profilesChanged) {
- this._setAvailableProfiles();
- }
- }
- if ((ref1 = args != null ? args.persist : void 0) != null ? ref1 : true) {
- if ((ref2 = this.sync) != null ? ref2.enabled : void 0) {
- if ((ref3 = this.sync) != null) {
- ref3.requestPush(changes);
- }
- }
- for (j = 0, len = removed.length; j < len; j++) {
- key = removed[j];
- delete changes[key];
- }
- return this._storage.set(changes).then((function(_this) {
- return function() {
- _this._storage.remove(removed);
- return _this._options;
- };
- })(this));
- }
- };
- Options.prototype._watch = function() {
- var handler;
- handler = (function(_this) {
- return function(changes) {
- var monitorWebRequests, quickSwitchProfiles, refresh, showExternal, showMenu;
- if (changes) {
- _this._setOptions(changes, {
- checkRevision: true,
- persist: false
- });
- } else {
- changes = _this._options;
- }
- refresh = changes['-refreshOnProfileChange'];
- if (refresh != null) {
- _this._state.set({
- 'refreshOnProfileChange': refresh
- });
- }
- if (Object.prototype.hasOwnProperty.call(changes, '-showExternalProfile')) {
- showExternal = changes['-showExternalProfile'];
- if (showExternal == null) {
- showExternal = true;
- _this._setOptions({
- '-showExternalProfile': true
- }, {
- persist: true
- });
- }
- _this._state.set({
- 'showExternalProfile': showExternal
- });
- }
- quickSwitchProfiles = changes['-quickSwitchProfiles'];
- quickSwitchProfiles = _this._cleanUpQuickSwitchProfiles(quickSwitchProfiles);
- if ((changes['-enableQuickSwitch'] != null) || (quickSwitchProfiles != null)) {
- _this.reloadQuickSwitch();
- }
- if (changes['-downloadInterval'] != null) {
- _this.schedule('updateProfile', _this._options['-downloadInterval'], function() {
- return _this.updateProfile();
- });
- }
- if ((changes['-showInspectMenu'] != null) || changes === _this._options) {
- showMenu = _this._options['-showInspectMenu'];
- if (showMenu == null) {
- showMenu = true;
- _this._setOptions({
- '-showInspectMenu': true
- }, {
- persist: true
- });
- }
- _this.setInspect({
- showMenu: showMenu
- });
- }
- if ((changes['-monitorWebRequests'] != null) || changes === _this._options) {
- monitorWebRequests = _this._options['-monitorWebRequests'];
- if (monitorWebRequests == null) {
- monitorWebRequests = true;
- _this._setOptions({
- '-monitorWebRequests': true
- }, {
- persist: true
- });
- }
- return _this.setMonitorWebRequests(monitorWebRequests);
- }
- };
- })(this);
- handler();
- return this._storage.watch(null, handler);
- };
- Options.prototype._cleanUpQuickSwitchProfiles = function(quickSwitchProfiles) {
- var seenQuickSwitchProfile, validQuickSwitchProfiles;
- if (quickSwitchProfiles == null) {
- return;
- }
- seenQuickSwitchProfile = {};
- validQuickSwitchProfiles = quickSwitchProfiles.filter((function(_this) {
- return function(name) {
- var key;
- if (!name) {
- return false;
- }
- key = OmegaPac.Profiles.nameAsKey(name);
- if (seenQuickSwitchProfile[key]) {
- return false;
- }
- if (!OmegaPac.Profiles.byName(name, _this._options)) {
- return false;
- }
- seenQuickSwitchProfile[key] = true;
- return true;
- };
- })(this));
- if (validQuickSwitchProfiles.length !== quickSwitchProfiles.length) {
- this._setOptions({
- '-quickSwitchProfiles': validQuickSwitchProfiles
- }, {
- persist: true
- });
- }
- return validQuickSwitchProfiles;
- };
- /**
- * Reload the quick switch according to settings.
- * @returns {Promise} A promise which is fulfilled when the quick switch is set
- */
- Options.prototype.reloadQuickSwitch = function() {
- var profiles;
- profiles = this._options['-quickSwitchProfiles'];
- if (profiles.length < 2) {
- profiles = null;
- }
- if (this._options['-enableQuickSwitch']) {
- return this.setQuickSwitch(profiles, !!profiles);
- } else {
- return this.setQuickSwitch(null, !!profiles);
- }
- };
- /**
- * Apply the settings related to element proxy inspection.
- * In base class, this method is not implemented and will not do anything.
- * @param {{}} settings
- * @param {boolean} settings.showMenu Whether to show the menu or not
- * @returns {Promise} A promise which is fulfilled when the settings apply
- */
- Options.prototype.setInspect = function() {
- return Promise.resolve();
- };
- /**
- * Apply the settings related to web request monitoring.
- * In base class, this method is not implemented and will not do anything.
- * @param {boolean} enabled Whether network shall be monitored or not
- * @returns {Promise} A promise which is fulfilled when the settings apply
- */
- Options.prototype.setMonitorWebRequests = function() {
- return Promise.resolve();
- };
- /**
- * @callback watchCallback
- * @param {Object.<string, {}>} changes A map from keys to values.
- */
- /**
- * Watch for any changes to the options
- * @param {watchCallback} callback Called everytime the value of a key changes
- * @returns {function} Calling the returned function will stop watching.
- */
- Options.prototype.watch = function(callback) {
- return this._storage.watch(null, callback);
- };
- Options.prototype._profileNotFound = function(name) {
- this.log.error("Profile " + name + " not found! Things may go very, very wrong.");
- return OmegaPac.Profiles.create({
- name: name,
- profileType: 'VirtualProfile',
- defaultProfileName: 'direct'
- });
- };
- /**
- * Get PAC script for profile.
- * @param {?string|Object} profile The name of the profile, or the profile.
- * @param {bool=false} compress Compress the script if true.
- * @returns {string} The compiled
- */
- Options.prototype.pacForProfile = function(profile, compress) {
- var ast;
- if (compress == null) {
- compress = false;
- }
- ast = OmegaPac.PacGenerator.script(this._options, profile, {
- profileNotFound: this._profileNotFound.bind(this)
- });
- if (compress) {
- ast = OmegaPac.PacGenerator.compress(ast);
- }
- return Promise.resolve(OmegaPac.PacGenerator.ascii(ast.print_to_string()));
- };
- Options.prototype._setAvailableProfiles = function() {
- var allReferenceSet, currentIncludable, profile, profiles, results;
- profile = this._currentProfileName ? this.currentProfile() : null;
- profiles = {};
- currentIncludable = profile && OmegaPac.Profiles.isIncludable(profile);
- allReferenceSet = null;
- if (!profile || !OmegaPac.Profiles.isInclusive(profile)) {
- results = [];
- }
- OmegaPac.Profiles.each(this._options, (function(_this) {
- return function(key, p) {
- profiles[key] = {
- name: p.name,
- profileType: p.profileType,
- color: p.color,
- desc: _this.printProfile(p),
- builtin: p.builtin ? true : void 0
- };
- if (p.profileType === 'VirtualProfile') {
- profiles[key].defaultProfileName = p.defaultProfileName;
- if (allReferenceSet == null) {
- allReferenceSet = profile ? OmegaPac.Profiles.allReferenceSet(profile, _this._options, {
- profileNotFound: _this._profileNotFound.bind(_this)
- }) : {};
- }
- if (allReferenceSet[key]) {
- profiles[key].validResultProfiles = OmegaPac.Profiles.validResultProfilesFor(p, _this._options).map(function(result) {
- return result.name;
- });
- }
- }
- if (currentIncludable && OmegaPac.Profiles.isIncludable(p)) {
- return results != null ? results.push(p.name) : void 0;
- }
- };
- })(this));
- if (profile && OmegaPac.Profiles.isInclusive(profile)) {
- results = OmegaPac.Profiles.validResultProfilesFor(profile, this._options);
- results = results.map(function(profile) {
- return profile.name;
- });
- }
- return this._state.set({
- 'availableProfiles': profiles,
- 'validResultProfiles': results
- });
- };
- /**
- * Apply the profile by name.
- * @param {?string} name The name of the profile, or null for default.
- * @param {?{}} options Some options
- * @param {bool=true} options.proxy Set proxy for the applied profile if true
- * @param {bool=true} options.update Try to update this profile and referenced
- * profiles after the proxy is set.
- * @param {bool=false} options.system Whether options is in system mode.
- * @param {{}=undefined} options.reason will be passed to currentProfileChanged
- * @returns {Promise} A promise which is fulfilled when the profile is applied.
- */
- Options.prototype.applyProfile = function(name, options) {
- var applyProxy, j, key, l, len, len1, list, profile, ref, removedKeys, rule;
- this.log.method('Options#applyProfile', this, arguments);
- profile = OmegaPac.Profiles.byName(name, this._options);
- if (!profile) {
- return Promise.reject(new ProfileNotExistError(name));
- }
- this._currentProfileName = profile.name;
- this._isSystem = (options != null ? options.system : void 0) || (profile.profileType === 'SystemProfile');
- this._watchingProfiles = OmegaPac.Profiles.allReferenceSet(profile, this._options, {
- profileNotFound: this._profileNotFound.bind(this)
- });
- this._state.set({
- 'currentProfileName': this._currentProfileName,
- 'isSystemProfile': this._isSystem,
- 'currentProfileCanAddRule': (profile.rules != null) && profile.profileType !== 'VirtualProfile'
- });
- this._setAvailableProfiles();
- this.currentProfileChanged(options != null ? options.reason : void 0);
- if ((options != null) && options.proxy === false) {
- return Promise.resolve();
- }
- this._tempProfileActive = false;
- if ((this._tempProfile != null) && OmegaPac.Profiles.isIncludable(profile)) {
- this._tempProfileActive = true;
- if (this._tempProfile.defaultProfileName !== profile.name) {
- this._tempProfile.defaultProfileName = profile.name;
- this._tempProfile.color = profile.color;
- OmegaPac.Profiles.updateRevision(this._tempProfile);
- }
- removedKeys = [];
- ref = this._tempProfileRulesByProfile;
- for (key in ref) {
- if (!hasProp.call(ref, key)) continue;
- list = ref[key];
- if (!OmegaPac.Profiles.byKey(key, this._options)) {
- removedKeys.push(key);
- for (j = 0, len = list.length; j < len; j++) {
- rule = list[j];
- rule.profileName = null;
- this._tempProfile.rules.splice(this._tempProfile.rules.indexOf(rule), 1);
- }
- }
- }
- if (removedKeys.length > 0) {
- for (l = 0, len1 = removedKeys.length; l < len1; l++) {
- key = removedKeys[l];
- delete this._tempProfileRulesByProfile[key];
- }
- OmegaPac.Profiles.updateRevision(this._tempProfile);
- }
- this._watchingProfiles = OmegaPac.Profiles.allReferenceSet(this._tempProfile, this._options, {
- profileNotFound: this._profileNotFound.bind(this)
- });
- applyProxy = this.proxyImpl.applyProfile(this._tempProfile, profile, this._options);
- } else {
- applyProxy = this.proxyImpl.applyProfile(profile, profile, this._options);
- }
- if ((options != null) && options.update === false) {
- return applyProxy;
- }
- applyProxy.then((function(_this) {
- return function() {
- var ref1, updateProfiles;
- if (!(_this._options['-downloadInterval'] > 0)) {
- return;
- }
- if (_this._currentProfileName !== profile.name) {
- return;
- }
- updateProfiles = [];
- ref1 = _this._watchingProfiles;
- for (key in ref1) {
- name = ref1[key];
- updateProfiles.push(name);
- }
- if (updateProfiles.length > 0) {
- return _this.updateProfile(updateProfiles);
- }
- };
- })(this));
- return applyProxy;
- };
- /**
- * Get the current applied profile.
- * @returns {{}} The current profile
- */
- Options.prototype.currentProfile = function() {
- if (this._currentProfileName) {
- return OmegaPac.Profiles.byName(this._currentProfileName, this._options);
- } else {
- return this._externalProfile;
- }
- };
- /**
- * Return true if in system mode.
- * @returns {boolean} True if system mode is activated
- */
- Options.prototype.isSystem = function() {
- return this._isSystem;
- };
- /**
- * Called when current profile has changed.
- * In base class, this method is not implemented and will not do anything.
- */
- Options.prototype.currentProfileChanged = function() {
- return null;
- };
- /**
- * Set or disable the quick switch profiles.
- * In base class, this method is not implemented and will not do anything.
- * @param {string[]|null} quickSwitch The profile names, or null to disable
- * @param {boolean} canEnable Whether user can enable quick switch or not.
- * @returns {Promise} A promise which is fulfilled when the quick switch is set
- */
- Options.prototype.setQuickSwitch = function(quickSwitch, canEnable) {
- return Promise.resolve();
- };
- /**
- * Schedule a task that runs every periodInMinutes.
- * In base class, this method is not implemented and will not do anything.
- * @param {string} name The name of the schedule. If there is a previous
- * schedule with the same name, it will be replaced by the new one.
- * @param {number} periodInMinutes The interval of the schedule
- * @param {function} callback The callback to call when the task runs
- * @returns {Promise} A promise which is fulfilled when the schedule is set
- */
- Options.prototype.schedule = function(name, periodInMinutes, callback) {
- return Promise.resolve();
- };
- /**
- * Return true if the match result of current profile does not change with URLs
- * @returns {bool} Whether @match always return the same result for requests
- */
- Options.prototype.isCurrentProfileStatic = function() {
- var currentProfile;
- if (!this._currentProfileName) {
- return true;
- }
- if (this._tempProfileActive) {
- return false;
- }
- currentProfile = this.currentProfile();
- if (OmegaPac.Profiles.isInclusive(currentProfile)) {
- return false;
- }
- return true;
- };
- /**
- * Update the profile by name.
- * @param {(string|string[]|null)} name The name of the profiles,
- * or null for all.
- * @param {?bool} opt_bypass_cache Do not read from the cache if true
- * @returns {Promise<Object.<string,({}|Error)>>} A map from keys to updated
- * profiles or errors.
- * A value is an error if `value instanceof Error`. Otherwise the value is an
- * updated profile.
- */
- Options.prototype.updateProfile = function(name, opt_bypass_cache) {
- var results;
- this.log.method('Options#updateProfile', this, arguments);
- results = {};
- OmegaPac.Profiles.each(this._options, (function(_this) {
- return function(key, profile) {
- var fetchResult, type_hints, url;
- if (name != null) {
- if (Array.isArray(name)) {
- if (!(name.indexOf(profile.name) >= 0)) {
- return;
- }
- } else {
- if (profile.name !== name) {
- return;
- }
- }
- }
- url = OmegaPac.Profiles.updateUrl(profile);
- if (url) {
- type_hints = OmegaPac.Profiles.updateContentTypeHints(profile);
- fetchResult = _this.fetchUrl(url, opt_bypass_cache, type_hints);
- return results[key] = fetchResult.then(function(data) {
- var changes;
- if (!data) {
- return profile;
- }
- profile = OmegaPac.Profiles.byKey(key, _this._options);
- profile.lastUpdate = new Date().toISOString();
- if (OmegaPac.Profiles.update(profile, data)) {
- OmegaPac.Profiles.dropCache(profile);
- changes = {};
- changes[key] = profile;
- return _this._setOptions(changes)["return"](profile);
- } else {
- return profile;
- }
- })["catch"](function(reason) {
- if (reason instanceof Error) {
- return reason;
- } else {
- return new Error(reason);
- }
- });
- }
- };
- })(this));
- return Promise.props(results);
- };
- /**
- * Make an HTTP GET request to fetch the content of the url.
- * In base class, this method is not implemented and will always reject.
- * @param {string} url The name of the profiles,
- * @param {?bool} opt_bypass_cache Do not read from the cache if true
- * @param {?string} opt_type_hints MIME type hints for downloaded content.
- * @returns {Promise<String>} The text content fetched from the url
- */
- Options.prototype.fetchUrl = function(url, opt_bypass_cache, opt_type_hints) {
- return Promise.reject(new Error('not implemented'));
- };
- Options.prototype._replaceRefChanges = function(fromName, toName, changes) {
- var i, j, quickSwitch, ref;
- if (changes == null) {
- changes = {};
- }
- OmegaPac.Profiles.each(this._options, function(key, p) {
- if (p.name === fromName || p.name === toName) {
- return;
- }
- if (OmegaPac.Profiles.replaceRef(p, fromName, toName)) {
- OmegaPac.Profiles.updateRevision(p);
- return changes[OmegaPac.Profiles.nameAsKey(p)] = p;
- }
- });
- if (this._options['-startupProfileName'] === fromName) {
- changes['-startupProfileName'] = toName;
- }
- quickSwitch = this._options['-quickSwitchProfiles'];
- if (quickSwitch.indexOf(toName) < 0) {
- for (i = j = 0, ref = quickSwitch.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
- if (quickSwitch[i] === fromName) {
- quickSwitch[i] = toName;
- changes['-quickSwitchProfiles'] = quickSwitch;
- }
- }
- }
- return changes;
- };
- /**
- * Replace all references of profile fromName to toName.
- * @param {String} fromName The original profile name
- * @param {String} toname The target profile name
- * @returns {Promise<OmegaOptions>} The updated options
- */
- Options.prototype.replaceRef = function(fromName, toName) {
- var changes, fromKey, key, profile, value;
- this.log.method('Options#replaceRef', this, arguments);
- profile = OmegaPac.Profiles.byName(fromName, this._options);
- if (!profile) {
- return Promise.reject(new ProfileNotExistError(fromName));
- }
- changes = this._replaceRefChanges(fromName, toName);
- for (key in changes) {
- if (!hasProp.call(changes, key)) continue;
- value = changes[key];
- this._options[key] = value;
- }
- fromKey = OmegaPac.Profiles.nameAsKey(fromName);
- if (this._watchingProfiles[fromKey]) {
- if (this._currentProfileName === fromName) {
- this._currentProfileName = toName;
- }
- this.applyProfile(this._currentProfileName);
- }
- return this._setOptions(changes);
- };
- /**
- * Rename a profile and update references and options
- * @param {String} fromName The original profile name
- * @param {String} toname The target profile name
- * @returns {Promise<OmegaOptions>} The updated options
- */
- Options.prototype.renameProfile = function(fromName, toName) {
- var changes, fromKey, key, profile, value;
- this.log.method('Options#renameProfile', this, arguments);
- if (OmegaPac.Profiles.byName(toName, this._options)) {
- return Promise.reject(new Error("Target name " + name + " already taken!"));
- }
- profile = OmegaPac.Profiles.byName(fromName, this._options);
- if (!profile) {
- return Promise.reject(new ProfileNotExistError(fromName));
- }
- profile.name = toName;
- changes = {};
- changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
- this._replaceRefChanges(fromName, toName, changes);
- for (key in changes) {
- if (!hasProp.call(changes, key)) continue;
- value = changes[key];
- this._options[key] = value;
- }
- fromKey = OmegaPac.Profiles.nameAsKey(fromName);
- changes[fromKey] = void 0;
- delete this._options[fromKey];
- if (this._watchingProfiles[fromKey]) {
- if (this._currentProfileName === fromName) {
- this._currentProfileName = toName;
- }
- this.applyProfile(this._currentProfileName);
- }
- return this._setOptions(changes);
- };
- /**
- * Add a temp rule.
- * @param {String} domain The domain for the temp rule.
- * @param {String} profileName The profile to apply for the domain.
- * @returns {Promise} A promise which is fulfilled when the rule is applied.
- */
- Options.prototype.addTempRule = function(domain, profileName) {
- var changed, currentProfile, key, list, profile, rule, rulesByProfile;
- this.log.method('Options#addTempRule', this, arguments);
- if (!this._currentProfileName) {
- return Promise.resolve();
- }
- profile = OmegaPac.Profiles.byName(profileName, this._options);
- if (!profile) {
- return Promise.reject(new ProfileNotExistError(profileName));
- }
- if (this._tempProfile == null) {
- this._tempProfile = OmegaPac.Profiles.create('', 'SwitchProfile');
- currentProfile = this.currentProfile();
- this._tempProfile.color = currentProfile.color;
- this._tempProfile.defaultProfileName = currentProfile.name;
- }
- changed = false;
- rule = this._tempProfileRules[domain];
- if (rule && rule.profileName) {
- if (rule.profileName !== profileName) {
- key = OmegaPac.Profiles.nameAsKey(rule.profileName);
- list = this._tempProfileRulesByProfile[key];
- list.splice(list.indexOf(rule), 1);
- rule.profileName = profileName;
- changed = true;
- }
- } else {
- rule = {
- condition: {
- conditionType: 'HostWildcardCondition',
- pattern: '*.' + domain
- },
- profileName: profileName,
- isTempRule: true
- };
- this._tempProfile.rules.push(rule);
- this._tempProfileRules[domain] = rule;
- changed = true;
- }
- key = OmegaPac.Profiles.nameAsKey(profileName);
- rulesByProfile = this._tempProfileRulesByProfile[key];
- if (rulesByProfile == null) {
- rulesByProfile = this._tempProfileRulesByProfile[key] = [];
- }
- rulesByProfile.push(rule);
- if (changed) {
- OmegaPac.Profiles.updateRevision(this._tempProfile);
- return this.applyProfile(this._currentProfileName);
- } else {
- return Promise.resolve();
- }
- };
- /**
- * Find a temp rule by domain.
- * @param {String} domain The domain of the temp rule.
- * @returns {Promise<?String>} The profile name for the domain, or null if such
- * rule does not exist.
- */
- Options.prototype.queryTempRule = function(domain) {
- var rule;
- rule = this._tempProfileRules[domain];
- if (rule) {
- if (rule.profileName) {
- return rule.profileName;
- } else {
- delete this._tempProfileRules[domain];
- }
- }
- return null;
- };
- /**
- * Add a condition to the current active switch profile.
- * @param {Object.<String,{}>} cond The condition to add
- * @param {string>} profileName The name of the result profile of the rule.
- * @returns {Promise} A promise which is fulfilled when the condition is saved.
- */
- Options.prototype.addCondition = function(condition, profileName) {
- var changes, cond, i, j, l, len, profile, ref, tag, target;
- this.log.method('Options#addCondition', this, arguments);
- if (!this._currentProfileName) {
- return Promise.resolve();
- }
- profile = OmegaPac.Profiles.byName(this._currentProfileName, this._options);
- if ((profile != null ? profile.rules : void 0) == null) {
- return Promise.reject(new Error("Cannot add condition to Profile " + this.profile.name + " (" + profile.type + ")"));
- }
- target = OmegaPac.Profiles.byName(profileName, this._options);
- if (target == null) {
- return Promise.reject(new ProfileNotExistError(profileName));
- }
- if (!Array.isArray(condition)) {
- condition = [condition];
- }
- for (j = 0, len = condition.length; j < len; j++) {
- cond = condition[j];
- tag = OmegaPac.Conditions.tag(cond);
- for (i = l = 0, ref = profile.rules.length; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
- if (OmegaPac.Conditions.tag(profile.rules[i].condition) === tag) {
- profile.rules.splice(i, 1);
- break;
- }
- }
- if (this._options['-addConditionsToBottom']) {
- profile.rules.push({
- condition: cond,
- profileName: profileName
- });
- } else {
- profile.rules.unshift({
- condition: cond,
- profileName: profileName
- });
- }
- }
- OmegaPac.Profiles.updateRevision(profile);
- changes = {};
- changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
- return this._setOptions(changes);
- };
- /**
- * Set the defaultProfileName of the profile.
- * @param {string>} profileName The name of the profile to modify.
- * @param {string>} defaultProfileName The defaultProfileName to set.
- * @returns {Promise} A promise which is fulfilled when the profile is saved.
- */
- Options.prototype.setDefaultProfile = function(profileName, defaultProfileName) {
- var changes, profile, target;
- this.log.method('Options#setDefaultProfile', this, arguments);
- profile = OmegaPac.Profiles.byName(profileName, this._options);
- if (profile == null) {
- return Promise.reject(new ProfileNotExistError(profileName));
- } else if (profile.defaultProfileName == null) {
- return Promise.reject(new Error(("Profile " + this.profile.name + " ") + "(@{profile.type}) does not have defaultProfileName!"));
- }
- target = OmegaPac.Profiles.byName(defaultProfileName, this._options);
- if (target == null) {
- return Promise.reject(new ProfileNotExistError(defaultProfileName));
- }
- profile.defaultProfileName = defaultProfileName;
- OmegaPac.Profiles.updateRevision(profile);
- changes = {};
- changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
- return this._setOptions(changes);
- };
- /**
- * Add a profile to the options
- * @param {{}} profile The profile to create
- * @returns {Promise<{}>} The saved profile
- */
- Options.prototype.addProfile = function(profile) {
- var changes;
- this.log.method('Options#addProfile', this, arguments);
- if (OmegaPac.Profiles.byName(profile.name, this._options)) {
- return Promise.reject(new Error("Target name " + profile.name + " already taken!"));
- } else {
- changes = {};
- changes[OmegaPac.Profiles.nameAsKey(profile)] = profile;
- return this._setOptions(changes);
- }
- };
- /**
- * Get the matching results of a request
- * @param {{}} request The request to test
- * @returns {Promise<{profile: {}, results: {}[]}>} The last matched profile
- * and the matching details
- */
- Options.prototype.matchProfile = function(request) {
- var lastProfile, next, profile, result, results;
- if (!this._currentProfileName) {
- return Promise.resolve({
- profile: this._externalProfile,
- results: []
- });
- }
- results = [];
- profile = this._tempProfileActive ? this._tempProfile : OmegaPac.Profiles.byName(this._currentProfileName, this._options);
- while (profile) {
- lastProfile = profile;
- result = OmegaPac.Profiles.match(profile, request);
- if (result == null) {
- break;
- }
- results.push(result);
- if (Array.isArray(result)) {
- next = result[0];
- } else if (result.profileName) {
- next = OmegaPac.Profiles.nameAsKey(result.profileName);
- } else {
- break;
- }
- profile = OmegaPac.Profiles.byKey(next, this._options);
- }
- return Promise.resolve({
- profile: lastProfile,
- results: results
- });
- };
- /**
- * Notify Options that the proxy settings are set externally.
- * @param {{}} profile The external profile
- * @param {?{}} args Extra arguments
- * @param {boolean=false} args.noRevert If true, do not revert changes.
- * @param {boolean=false} args.internal If true, treat the profile change as
- * caused by the options itself instead of external reasons.
- * @returns {Promise} A promise which is fulfilled when the profile is set
- */
- Options.prototype.setExternalProfile = function(profile, args) {
- var p;
- if (this._options['-revertProxyChanges'] && !this._isSystem) {
- if (profile.name !== this._currentProfileName && this._currentProfileName) {
- if (!(args != null ? args.noRevert : void 0)) {
- this.applyProfile(this._revertToProfileName);
- this._revertToProfileName = null;
- return;
- } else {
- if (this._revertToProfileName == null) {
- this._revertToProfileName = this._currentProfileName;
- }
- }
- }
- }
- p = OmegaPac.Profiles.byName(profile.name, this._options);
- if (p) {
- if (args != null ? args.internal : void 0) {
- return this.applyProfile(p.name, {
- proxy: false
- });
- } else {
- return this.applyProfile(p.name, {
- proxy: false,
- system: this._isSystem,
- reason: 'external'
- });
- }
- } else {
- this._currentProfileName = null;
- this._externalProfile = profile;
- if (profile.color == null) {
- profile.color = '#49afcd';
- }
- this._state.set({
- 'currentProfileName': '',
- 'externalProfile': profile,
- 'validResultProfiles': [],
- 'currentProfileCanAddRule': false
- });
- this.currentProfileChanged('external');
- }
- };
- /**
- * Switch options syncing on and off.
- * @param {boolean} enabled Whether to enable syncing
- * @param {?{}} args Extra arguments
- * @param {boolean=false} args.force If true, overwrite options when conflict
- * @returns {Promise} A promise which is fulfilled when the syncing is switched
- */
- Options.prototype.setOptionsSync = function(enabled, args) {
- this.log.method('Options#setOptionsSync', this, arguments);
- if (this.sync == null) {
- return Promise.reject(new Error('Options syncing is unsupported.'));
- }
- return this._state.get({
- 'syncOptions': ''
- }).then((function(_this) {
- return function(arg) {
- var syncOptions;
- syncOptions = arg.syncOptions;
- if (!enabled) {
- if (syncOptions === 'sync') {
- _this._state.set({
- 'syncOptions': 'conflict'
- });
- }
- _this.sync.enabled = false;
- if (typeof _this._syncWatchStop === "function") {
- _this._syncWatchStop();
- }
- _this._syncWatchStop = null;
- return;
- }
- if (syncOptions === 'conflict') {
- if (!(args != null ? args.force : void 0)) {
- return Promise.reject(new Error('Syncing not enabled due to conflict. Retry with force to overwrite local options and enable syncing.'));
- }
- }
- if (syncOptions === 'sync') {
- return;
- }
- return _this._state.set({
- 'syncOptions': 'sync'
- }).then(function() {
- if (syncOptions === 'conflict') {
- _this.sync.enabled = false;
- return _this._storage.remove().then(function() {
- _this.sync.enabled = true;
- return _this.init();
- });
- } else {
- _this.sync.enabled = true;
- if (typeof _this._syncWatchStop === "function") {
- _this._syncWatchStop();
- }
- _this.sync.requestPush(_this._options);
- _this._syncWatchStop = _this.sync.watchAndPull(_this._storage);
- }
- });
- };
- })(this));
- };
- /**
- * Clear the sync storage, resetting syncing state to pristine.
- * @returns {Promise} A promise which is fulfilled when the syncing is reset.
- */
- Options.prototype.resetOptionsSync = function() {
- this.log.method('Options#resetOptionsSync', this, arguments);
- if (this.sync == null) {
- return Promise.reject(new Error('Options syncing is unsupported.'));
- }
- this.sync.enabled = false;
- if (typeof this._syncWatchStop === "function") {
- this._syncWatchStop();
- }
- this._syncWatchStop = null;
- this._state.set({
- 'syncOptions': 'conflict'
- });
- return this.sync.storage.remove().then((function(_this) {
- return function() {
- return _this._state.set({
- 'syncOptions': 'pristine'
- });
- };
- })(this));
- };
- return Options;
- })();
- module.exports = Options;
- },{"./default_options":29,"./log":31,"./storage":34,"bluebird":2,"buffer":3,"jsondiffpatch":19,"omega-pac":27}],33:[function(require,module,exports){
- /* @module omega-target/options_sync */
- var Log, OptionsSync, Promise, Revision, Storage, TokenBucket, jsondiffpatch,
- hasProp = {}.hasOwnProperty;
- Promise = require('bluebird');
- Storage = require('./storage');
- Log = require('./log');
- Revision = require('omega-pac').Revision;
- jsondiffpatch = require('jsondiffpatch');
- TokenBucket = require('limiter').TokenBucket;
- OptionsSync = (function() {
- OptionsSync.TokenBucket = TokenBucket;
- OptionsSync.prototype._timeout = null;
- OptionsSync.prototype._bucket = null;
- OptionsSync.prototype._waiting = false;
- /**
- * The debounce timeout (ms) for requestPush scheduling. See requestPush.
- * @type number
- */
- OptionsSync.prototype.debounce = 1000;
- /**
- * The throttling timeout (ms) for watchAndPull. See watchAndPull.
- * @type number
- */
- OptionsSync.prototype.pullThrottle = 1000;
- /**
- * The remote storage of syncing.
- * @type Storage
- */
- OptionsSync.prototype.storage = null;
- function OptionsSync(storage, _bucket) {
- var base1;
- this.storage = storage;
- this._bucket = _bucket;
- this._pending = {};
- if (this._bucket == null) {
- this._bucket = new TokenBucket(10, 10, 'minute', null);
- }
- if ((base1 = this._bucket).clear == null) {
- base1.clear = (function(_this) {
- return function() {
- return _this._bucket.tryRemoveTokens(_this._bucket.content);
- };
- })(this);
- }
- }
- /**
- * Transform storage values for syncing. The default implementation applies no
- * transformation, but the behavior can be altered by assigning to this field.
- * Note: Transformation is applied before merging.
- * @param {{}} value The value to transform
- * @param {{}} key The key of the item
- * @returns {{}} The transformed value
- */
- OptionsSync.prototype.transformValue = function(v) {
- return v;
- };
- /**
- * Merge newVal and oldVal of a given key. The default implementation choose
- * between newVal and oldVal based on the following rules:
- * 1. Choose oldVal if syncOptions is 'disabled' in either oldVal or newVal.
- * 2. Choose oldVal if it has a revision newer than or equal to that of newVal.
- * 3. Choose oldVal if it deeply equals newVal.
- * 4. Otherwise, choose newVal.
- *
- * @param {string} key The key of the item
- * @param {} newVal The new value
- * @param {} oldVal The old value
- * @returns {} The merged result
- */
- OptionsSync.prototype.merge = (function() {
- var diff;
- diff = jsondiffpatch.create({
- objectHash: function(obj) {
- return JSON.stringify(obj);
- },
- textDiff: {
- minLength: 1 / 0
- }
- });
- return function(key, newVal, oldVal) {
- var result;
- if (newVal === oldVal) {
- return oldVal;
- }
- if ((oldVal != null ? oldVal.syncOptions : void 0) === 'disabled' || (newVal != null ? newVal.syncOptions : void 0) === 'disabled') {
- return oldVal;
- }
- if (((oldVal != null ? oldVal.revision : void 0) != null) && ((newVal != null ? newVal.revision : void 0) != null)) {
- result = Revision.compare(oldVal.revision, newVal.revision);
- if (result >= 0) {
- return oldVal;
- }
- }
- if (diff.diff(oldVal, newVal) == null) {
- return oldVal;
- }
- return newVal;
- };
- })();
- /**
- * Whether syncing is enabled or not. See requestPush for the effect.
- * @type boolean
- */
- OptionsSync.prototype.enabled = true;
- /**
- * Request pushing the changes to remote storage. The changes are cached first,
- * and then the actual write operations are scheduled if enabled is true.
- * The actual operation is delayed and debounced, combining continuous writes
- * in a short period into a single write operation.
- * @param {Object.<string, {}>} changes A map from keys to values.
- */
- OptionsSync.prototype.requestPush = function(changes) {
- var key, value;
- if (this._timeout != null) {
- clearTimeout(this._timeout);
- }
- for (key in changes) {
- if (!hasProp.call(changes, key)) continue;
- value = changes[key];
- if (typeof value !== 'undefined') {
- value = this.transformValue(value, key);
- if (typeof value === 'undefined') {
- continue;
- }
- }
- this._pending[key] = value;
- }
- if (!this.enabled) {
- return;
- }
- return this._timeout = setTimeout(this._doPush.bind(this), this.debounce);
- };
- /**
- * Returning the pending changes not written to the remote storage.
- * @returns {Object.<string, {}>} The pending changes.
- */
- OptionsSync.prototype.pendingChanges = function() {
- return this._pending;
- };
- OptionsSync.prototype._doPush = function() {
- this._timeout = null;
- if (this._waiting) {
- return;
- }
- this._waiting = true;
- return this._bucket.removeTokens(1, (function(_this) {
- return function() {
- return _this.storage.get(null).then(function(base) {
- var changes;
- changes = _this._pending;
- _this._pending = {};
- _this._waiting = false;
- return Storage.operationsForChanges(changes, {
- base: base,
- merge: _this.merge
- });
- }).then(function(arg) {
- var doSet, remove, set;
- set = arg.set, remove = arg.remove;
- doSet = Object.keys(set).length === 0 ? Promise.resolve(0) : (Log.log('OptionsSync::set', set), _this.storage.set(set)["return"](1));
- return doSet.then(function(cost) {
- set = {};
- if (remove.length > 0) {
- if (_this._bucket.tryRemoveTokens(cost)) {
- Log.log('OptionsSync::remove', remove);
- return _this.storage.remove(remove);
- } else {
- return Promise.reject('bucket');
- }
- }
- })["catch"](function(e) {
- var i, key, len, value, valuesAffected;
- for (key in set) {
- if (!hasProp.call(set, key)) continue;
- value = set[key];
- if (!(key in _this._pending)) {
- _this._pending[key] = value;
- }
- }
- for (i = 0, len = remove.length; i < len; i++) {
- key = remove[i];
- if (!(key in _this._pending)) {
- _this._pending[key] = void 0;
- }
- }
- if (e === 'bucket') {
- return _this._doPush();
- } else if (e instanceof Storage.RateLimitExceededError) {
- Log.log('OptionsSync::rateLimitExceeded');
- _this._bucket.clear();
- _this.requestPush({});
- } else if (e instanceof Storage.QuotaExceededError) {
- valuesAffected = 0;
- for (key in set) {
- if (!hasProp.call(set, key)) continue;
- value = set[key];
- if (key[0] === '+' && value.syncOptions !== 'disabled') {
- value.syncOptions = 'disabled';
- value.syncError = {
- reason: 'quotaPerItem'
- };
- valuesAffected++;
- }
- }
- if (valuesAffected > 0) {
- _this.requestPush({});
- } else {
- _this._pending = {};
- }
- } else {
- return Promise.reject(e);
- }
- });
- });
- };
- })(this));
- };
- OptionsSync.prototype._logOperations = function(text, operations) {
- if (Object.keys(operations.set).length) {
- Log.log(text + '::set', operations.set);
- }
- if (operations.remove.length) {
- return Log.log(text + '::remove', operations.remove);
- }
- };
- /**
- * Pull the remote storage for changes, and write them to local.
- * @param {Storage} local The local storage to be written to
- * @returns {function} Calling the returned function will stop watching.
- */
- OptionsSync.prototype.copyTo = function(local) {
- return Promise.join(local.get(null), this.storage.get(null), (function(_this) {
- return function(base, changes) {
- var key, ref;
- for (key in base) {
- if (!hasProp.call(base, key)) continue;
- if (!(key in changes)) {
- if (key[0] === '+' && !((ref = base[key]) != null ? ref.syncOptions : void 0) === 'disabled') {
- changes[key] = void 0;
- }
- }
- }
- return local.apply({
- changes: changes,
- base: base,
- merge: _this.merge
- }).then(function(operations) {
- return _this._logOperations('OptionsSync::copyTo', operations);
- });
- };
- })(this));
- };
- /**
- * Watch the remote storage for changes, and write them to local.
- * The actual writing is throttled by pullThrottle with initial delay.
- * @param {Storage} local The local storage to be written to
- * @returns {function} Calling the returned function will stop watching.
- */
- OptionsSync.prototype.watchAndPull = function(local) {
- var doPull, pull, pullScheduled;
- pullScheduled = null;
- pull = {};
- doPull = (function(_this) {
- return function() {
- return local.get(null).then(function(base) {
- var changes;
- changes = pull;
- pull = {};
- pullScheduled = null;
- return Storage.operationsForChanges(changes, {
- base: base,
- merge: _this.merge
- });
- }).then(function(operations) {
- _this._logOperations('OptionsSync::pull', operations);
- return local.apply(operations);
- });
- };
- })(this);
- return this.storage.watch(null, (function(_this) {
- return function(changes) {
- var key, value;
- for (key in changes) {
- if (!hasProp.call(changes, key)) continue;
- value = changes[key];
- pull[key] = value;
- }
- if (pullScheduled != null) {
- return;
- }
- return pullScheduled = setTimeout(doPull, _this.pullThrottle);
- };
- })(this));
- };
- return OptionsSync;
- })();
- module.exports = OptionsSync;
- },{"./log":31,"./storage":34,"bluebird":2,"jsondiffpatch":19,"limiter":22,"omega-pac":27}],34:[function(require,module,exports){
- /* @module omega-target/storage */
- var Log, Promise, Storage,
- 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; },
- hasProp = {}.hasOwnProperty;
- Promise = require('bluebird');
- Log = require('./log');
- Storage = (function() {
- var QuotaExceededError, RateLimitExceededError, StorageUnavailableError;
- function Storage() {}
- /**
- * Any operation that fails due to rate limiting should reject with an instance
- * of RateLimitExceededError, when implemented in derived classes of Storage.
- */
- Storage.RateLimitExceededError = RateLimitExceededError = (function(superClass) {
- extend(RateLimitExceededError, superClass);
- function RateLimitExceededError() {
- RateLimitExceededError.__super__.constructor.apply(this, arguments);
- }
- return RateLimitExceededError;
- })(Error);
- /**
- * Any operation that fails due to storage quota should reject with an instance
- * of QuotaExceededError, when implemented in derived classes of Storage.
- */
- Storage.QuotaExceededError = QuotaExceededError = (function(superClass) {
- extend(QuotaExceededError, superClass);
- function QuotaExceededError() {
- QuotaExceededError.__super__.constructor.apply(this, arguments);
- }
- return QuotaExceededError;
- })(Error);
- /**
- * If this storage is not available for some reason, all operations should
- * reject with an instance of StorageUnavailableError, when implemented in
- * derived classes of Storage.
- * This error is considered fatal and unrecoverable in the current environment.
- * Further access to this storage should be avoided until restart.
- */
- Storage.StorageUnavailableError = StorageUnavailableError = (function(superClass) {
- extend(StorageUnavailableError, superClass);
- function StorageUnavailableError() {
- StorageUnavailableError.__super__.constructor.apply(this, arguments);
- }
- return StorageUnavailableError;
- })(Error);
- /**
- * A set of operations to be performed on a Storage.
- * @typedef WriteOperations
- * @type {object}
- * @property {Object.<string, {}>} set - A map from keys to new values of the
- * items to set
- * @property {{}[]} remove - An array of keys to remove
- */
- /**
- * Calculate the actual operations against storage that should be performed to
- * replay the changes on a storage.
- * @param {Object.<string, {}>} changes The changes to apply
- * @param {?{}} args Extra arguments
- * @param {Object.<string, {}>?} args.base The original items in the storage.
- * @param {function(key, newVal, oldVal)} args.merge A function that merges
- * the newVal and oldVal. oldVal is provided only if args.base is present.
- * Otherwise it will be equal to newVal (i.e. merge(key, newVal, newVal)).
- * @returns {WriteOperations} The operations that should be performed.
- */
- Storage.operationsForChanges = function(changes, arg) {
- var base, key, merge, newVal, oldVal, ref, remove, set;
- ref = arg != null ? arg : {}, base = ref.base, merge = ref.merge;
- set = {};
- remove = [];
- for (key in changes) {
- newVal = changes[key];
- oldVal = base != null ? base[key] : newVal;
- if (merge) {
- newVal = merge(key, newVal, oldVal);
- }
- if ((base != null) && newVal === oldVal) {
- continue;
- }
- if (typeof newVal === 'undefined') {
- if (typeof oldVal !== 'undefined' || (base == null)) {
- remove.push(key);
- }
- } else {
- set[key] = newVal;
- }
- }
- return {
- set: set,
- remove: remove
- };
- };
- /**
- * Get the requested values by keys from the storage.
- * @param {(string|string[]|null|Object.<string,{}>)} keys The keys to retrive,
- * or null for all.
- * @returns {Promise<(Object.<string, {}>)>} A map from keys to values
- */
- Storage.prototype.get = function(keys) {
- var i, key, len, map, ref, value;
- Log.method('Storage#get', this, arguments);
- if (!this._items) {
- return Promise.resolve({});
- }
- if (keys == null) {
- keys = this._items;
- }
- map = {};
- if (typeof keys === 'string') {
- map[keys] = this._items[keys];
- } else if (Array.isArray(keys)) {
- for (i = 0, len = keys.length; i < len; i++) {
- key = keys[i];
- map[key] = this._items[key];
- }
- } else if (typeof keys === 'object') {
- for (key in keys) {
- value = keys[key];
- map[key] = (ref = this._items[key]) != null ? ref : value;
- }
- }
- return Promise.resolve(map);
- };
- /**
- * Set multiple values by keys in the storage.
- * @param {(string|Object.<string,{}>)} items A map from key to value to set.
- * @returns {Promise<(Object.<string, {}>)>} A map of key-value pairs just set.
- */
- Storage.prototype.set = function(items) {
- var key, value;
- Log.method('Storage#set', this, arguments);
- if (this._items == null) {
- this._items = {};
- }
- for (key in items) {
- value = items[key];
- this._items[key] = value;
- }
- return Promise.resolve(items);
- };
- /**
- * Remove items by keys from the storage.
- * @param {(string|string[]|null)} keys The keys to remove, or null for all.
- * @returns {Promise} A promise that fulfills on successful removal.
- */
- Storage.prototype.remove = function(keys) {
- var i, key, len;
- Log.method('Storage#remove', this, arguments);
- if (this._items != null) {
- if (keys == null) {
- this._items = {};
- } else if (Array.isArray(keys)) {
- for (i = 0, len = keys.length; i < len; i++) {
- key = keys[i];
- delete this._items[key];
- }
- } else {
- delete this._items[keys];
- }
- }
- return Promise.resolve();
- };
- /**
- * @callback watchCallback
- * @param {Object.<string, {}>} map A map of key-value pairs just changed.
- */
- /**
- * Watch for any changes to the storage.
- * @param {(string|string[]|null)} keys The keys to watch, or null for all.
- * @param {watchCallback} callback Called everytime something changes.
- * @returns {function} Calling the returned function will stop watching.
- */
- Storage.prototype.watch = function(keys, callback) {
- Log.method('Storage#watch', this, arguments);
- return (function() {
- return null;
- });
- };
- /**
- * Apply WriteOperations to the storage.
- * @param {WriteOperations|{changes: Object.<string,{}>}} operations The
- * operations to apply, or the changes to be applied. If changes is provided,
- * the operations are calculated by Storage.operationsForChanges, with extra
- * fields passed through as the second argument.
- * @returns {Promise} A promise that fulfills on operation success.
- */
- Storage.prototype.apply = function(operations) {
- if ('changes' in operations) {
- operations = Storage.operationsForChanges(operations.changes, operations);
- }
- return this.set(operations.set).then((function(_this) {
- return function() {
- return _this.remove(operations.remove);
- };
- })(this))["return"](operations);
- };
- return Storage;
- })();
- module.exports = Storage;
- },{"./log":31,"bluebird":2}],35:[function(require,module,exports){
- exports.Promise = require('bluebird');
- },{"bluebird":2}],"OmegaTarget":[function(require,module,exports){
- var name, ref, ref1, value;
- module.exports = {
- Log: require('./src/log'),
- Storage: require('./src/storage'),
- BrowserStorage: require('./src/browser_storage'),
- Options: require('./src/options'),
- OptionsSync: require('./src/options_sync'),
- OmegaPac: require('omega-pac')
- };
- ref = require('./src/utils.coffee');
- for (name in ref) {
- value = ref[name];
- module.exports[name] = value;
- }
- ref1 = require('./src/errors.coffee');
- for (name in ref1) {
- value = ref1[name];
- module.exports[name] = value;
- }
- },{"./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")
- });
|