mqtt.js 475 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mqtt = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (process,global){(function (){
  3. 'use strict'
  4. /**
  5. * Module dependencies
  6. */
  7. var events = require('events')
  8. var Store = require('./store')
  9. var eos = require('end-of-stream')
  10. var mqttPacket = require('mqtt-packet')
  11. var Writable = require('readable-stream').Writable
  12. var inherits = require('inherits')
  13. var reInterval = require('reinterval')
  14. var validations = require('./validations')
  15. var xtend = require('xtend')
  16. var setImmediate = global.setImmediate || function (callback) {
  17. // works in node v0.8
  18. process.nextTick(callback)
  19. }
  20. var defaultConnectOptions = {
  21. keepalive: 60,
  22. reschedulePings: true,
  23. protocolId: 'MQTT',
  24. protocolVersion: 4,
  25. reconnectPeriod: 1000,
  26. connectTimeout: 30 * 1000,
  27. clean: true,
  28. resubscribe: true
  29. }
  30. function defaultId () {
  31. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  32. }
  33. function sendPacket (client, packet, cb) {
  34. client.emit('packetsend', packet)
  35. var result = mqttPacket.writeToStream(packet, client.stream)
  36. if (!result && cb) {
  37. client.stream.once('drain', cb)
  38. } else if (cb) {
  39. cb()
  40. }
  41. }
  42. function flush (queue) {
  43. if (queue) {
  44. Object.keys(queue).forEach(function (messageId) {
  45. if (typeof queue[messageId] === 'function') {
  46. queue[messageId](new Error('Connection closed'))
  47. delete queue[messageId]
  48. }
  49. })
  50. }
  51. }
  52. function storeAndSend (client, packet, cb) {
  53. client.outgoingStore.put(packet, function storedPacket (err) {
  54. if (err) {
  55. return cb && cb(err)
  56. }
  57. sendPacket(client, packet, cb)
  58. })
  59. }
  60. function nop () {}
  61. /**
  62. * MqttClient constructor
  63. *
  64. * @param {Stream} stream - stream
  65. * @param {Object} [options] - connection options
  66. * (see Connection#connect)
  67. */
  68. function MqttClient (streamBuilder, options) {
  69. var k
  70. var that = this
  71. if (!(this instanceof MqttClient)) {
  72. return new MqttClient(streamBuilder, options)
  73. }
  74. this.options = options || {}
  75. // Defaults
  76. for (k in defaultConnectOptions) {
  77. if (typeof this.options[k] === 'undefined') {
  78. this.options[k] = defaultConnectOptions[k]
  79. } else {
  80. this.options[k] = options[k]
  81. }
  82. }
  83. this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId()
  84. this.streamBuilder = streamBuilder
  85. // Inflight message storages
  86. this.outgoingStore = this.options.outgoingStore || new Store()
  87. this.incomingStore = this.options.incomingStore || new Store()
  88. // Should QoS zero messages be queued when the connection is broken?
  89. this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero
  90. // map of subscribed topics to support reconnection
  91. this._resubscribeTopics = {}
  92. // map of a subscribe messageId and a topic
  93. this.messageIdToTopic = {}
  94. // Ping timer, setup in _setupPingTimer
  95. this.pingTimer = null
  96. // Is the client connected?
  97. this.connected = false
  98. // Are we disconnecting?
  99. this.disconnecting = false
  100. // Packet queue
  101. this.queue = []
  102. // connack timer
  103. this.connackTimer = null
  104. // Reconnect timer
  105. this.reconnectTimer = null
  106. /**
  107. * MessageIDs starting with 1
  108. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  109. */
  110. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  111. // Inflight callbacks
  112. this.outgoing = {}
  113. // Mark connected on connect
  114. this.on('connect', function () {
  115. if (this.disconnected) {
  116. return
  117. }
  118. this.connected = true
  119. var outStore = this.outgoingStore.createStream()
  120. this.once('close', remove)
  121. outStore.on('end', function () {
  122. that.removeListener('close', remove)
  123. })
  124. outStore.on('error', function (err) {
  125. that.removeListener('close', remove)
  126. that.emit('error', err)
  127. })
  128. function remove () {
  129. outStore.destroy()
  130. outStore = null
  131. }
  132. function storeDeliver () {
  133. // edge case, we wrapped this twice
  134. if (!outStore) {
  135. return
  136. }
  137. var packet = outStore.read(1)
  138. var cb
  139. if (!packet) {
  140. // read when data is available in the future
  141. outStore.once('readable', storeDeliver)
  142. return
  143. }
  144. // Avoid unnecessary stream read operations when disconnected
  145. if (!that.disconnecting && !that.reconnectTimer) {
  146. cb = that.outgoing[packet.messageId]
  147. that.outgoing[packet.messageId] = function (err, status) {
  148. // Ensure that the original callback passed in to publish gets invoked
  149. if (cb) {
  150. cb(err, status)
  151. }
  152. storeDeliver()
  153. }
  154. that._sendPacket(packet)
  155. } else if (outStore.destroy) {
  156. outStore.destroy()
  157. }
  158. }
  159. // start flowing
  160. storeDeliver()
  161. })
  162. // Mark disconnected on stream close
  163. this.on('close', function () {
  164. this.connected = false
  165. clearTimeout(this.connackTimer)
  166. })
  167. // Setup ping timer
  168. this.on('connect', this._setupPingTimer)
  169. // Send queued packets
  170. this.on('connect', function () {
  171. var queue = this.queue
  172. function deliver () {
  173. var entry = queue.shift()
  174. var packet = null
  175. if (!entry) {
  176. return
  177. }
  178. packet = entry.packet
  179. that._sendPacket(
  180. packet,
  181. function (err) {
  182. if (entry.cb) {
  183. entry.cb(err)
  184. }
  185. deliver()
  186. }
  187. )
  188. }
  189. deliver()
  190. })
  191. var firstConnection = true
  192. // resubscribe
  193. this.on('connect', function () {
  194. if (!firstConnection &&
  195. this.options.clean &&
  196. Object.keys(this._resubscribeTopics).length > 0) {
  197. if (this.options.resubscribe) {
  198. this._resubscribeTopics.resubscribe = true
  199. this.subscribe(this._resubscribeTopics)
  200. } else {
  201. this._resubscribeTopics = {}
  202. }
  203. }
  204. firstConnection = false
  205. })
  206. // Clear ping timer
  207. this.on('close', function () {
  208. if (that.pingTimer !== null) {
  209. that.pingTimer.clear()
  210. that.pingTimer = null
  211. }
  212. })
  213. // Setup reconnect timer on disconnect
  214. this.on('close', this._setupReconnect)
  215. events.EventEmitter.call(this)
  216. this._setupStream()
  217. }
  218. inherits(MqttClient, events.EventEmitter)
  219. /**
  220. * setup the event handlers in the inner stream.
  221. *
  222. * @api private
  223. */
  224. MqttClient.prototype._setupStream = function () {
  225. var connectPacket
  226. var that = this
  227. var writable = new Writable()
  228. var parser = mqttPacket.parser(this.options)
  229. var completeParse = null
  230. var packets = []
  231. this._clearReconnect()
  232. this.stream = this.streamBuilder(this)
  233. parser.on('packet', function (packet) {
  234. packets.push(packet)
  235. })
  236. function nextTickWork () {
  237. process.nextTick(work)
  238. }
  239. function work () {
  240. var packet = packets.shift()
  241. var done = completeParse
  242. if (packet) {
  243. that._handlePacket(packet, nextTickWork)
  244. } else {
  245. completeParse = null
  246. done()
  247. }
  248. }
  249. writable._write = function (buf, enc, done) {
  250. completeParse = done
  251. parser.parse(buf)
  252. work()
  253. }
  254. this.stream.pipe(writable)
  255. // Suppress connection errors
  256. this.stream.on('error', nop)
  257. // Echo stream close
  258. eos(this.stream, this.emit.bind(this, 'close'))
  259. // Send a connect packet
  260. connectPacket = Object.create(this.options)
  261. connectPacket.cmd = 'connect'
  262. // avoid message queue
  263. sendPacket(this, connectPacket)
  264. // Echo connection errors
  265. parser.on('error', this.emit.bind(this, 'error'))
  266. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  267. this.stream.setMaxListeners(1000)
  268. clearTimeout(this.connackTimer)
  269. this.connackTimer = setTimeout(function () {
  270. that._cleanUp(true)
  271. }, this.options.connectTimeout)
  272. }
  273. MqttClient.prototype._handlePacket = function (packet, done) {
  274. this.emit('packetreceive', packet)
  275. switch (packet.cmd) {
  276. case 'publish':
  277. this._handlePublish(packet, done)
  278. break
  279. case 'puback':
  280. case 'pubrec':
  281. case 'pubcomp':
  282. case 'suback':
  283. case 'unsuback':
  284. this._handleAck(packet)
  285. done()
  286. break
  287. case 'pubrel':
  288. this._handlePubrel(packet, done)
  289. break
  290. case 'connack':
  291. this._handleConnack(packet)
  292. done()
  293. break
  294. case 'pingresp':
  295. this._handlePingresp(packet)
  296. done()
  297. break
  298. default:
  299. // do nothing
  300. // maybe we should do an error handling
  301. // or just log it
  302. break
  303. }
  304. }
  305. MqttClient.prototype._checkDisconnecting = function (callback) {
  306. if (this.disconnecting) {
  307. if (callback) {
  308. callback(new Error('client disconnecting'))
  309. } else {
  310. this.emit('error', new Error('client disconnecting'))
  311. }
  312. }
  313. return this.disconnecting
  314. }
  315. /**
  316. * publish - publish <message> to <topic>
  317. *
  318. * @param {String} topic - topic to publish to
  319. * @param {String, Buffer} message - message to publish
  320. * @param {Object} [opts] - publish options, includes:
  321. * {Number} qos - qos level to publish on
  322. * {Boolean} retain - whether or not to retain the message
  323. * {Boolean} dup - whether or not mark a message as duplicate
  324. * @param {Function} [callback] - function(err){}
  325. * called when publish succeeds or fails
  326. * @returns {MqttClient} this - for chaining
  327. * @api public
  328. *
  329. * @example client.publish('topic', 'message');
  330. * @example
  331. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  332. * @example client.publish('topic', 'message', console.log);
  333. */
  334. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  335. var packet
  336. // .publish(topic, payload, cb);
  337. if (typeof opts === 'function') {
  338. callback = opts
  339. opts = null
  340. }
  341. // default opts
  342. var defaultOpts = {qos: 0, retain: false, dup: false}
  343. opts = xtend(defaultOpts, opts)
  344. if (this._checkDisconnecting(callback)) {
  345. return this
  346. }
  347. packet = {
  348. cmd: 'publish',
  349. topic: topic,
  350. payload: message,
  351. qos: opts.qos,
  352. retain: opts.retain,
  353. messageId: this._nextId(),
  354. dup: opts.dup
  355. }
  356. switch (opts.qos) {
  357. case 1:
  358. case 2:
  359. // Add to callbacks
  360. this.outgoing[packet.messageId] = callback || nop
  361. this._sendPacket(packet)
  362. break
  363. default:
  364. this._sendPacket(packet, callback)
  365. break
  366. }
  367. return this
  368. }
  369. /**
  370. * subscribe - subscribe to <topic>
  371. *
  372. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  373. * @param {Object} [opts] - optional subscription options, includes:
  374. * {Number} qos - subscribe qos level
  375. * @param {Function} [callback] - function(err, granted){} where:
  376. * {Error} err - subscription error (none at the moment!)
  377. * {Array} granted - array of {topic: 't', qos: 0}
  378. * @returns {MqttClient} this - for chaining
  379. * @api public
  380. * @example client.subscribe('topic');
  381. * @example client.subscribe('topic', {qos: 1});
  382. * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
  383. * @example client.subscribe('topic', console.log);
  384. */
  385. MqttClient.prototype.subscribe = function () {
  386. var packet
  387. var args = Array.prototype.slice.call(arguments)
  388. var subs = []
  389. var obj = args.shift()
  390. var resubscribe = obj.resubscribe
  391. var callback = args.pop() || nop
  392. var opts = args.pop()
  393. var invalidTopic
  394. var that = this
  395. delete obj.resubscribe
  396. if (typeof obj === 'string') {
  397. obj = [obj]
  398. }
  399. if (typeof callback !== 'function') {
  400. opts = callback
  401. callback = nop
  402. }
  403. invalidTopic = validations.validateTopics(obj)
  404. if (invalidTopic !== null) {
  405. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  406. return this
  407. }
  408. if (this._checkDisconnecting(callback)) {
  409. return this
  410. }
  411. var defaultOpts = { qos: 0 }
  412. opts = xtend(defaultOpts, opts)
  413. if (Array.isArray(obj)) {
  414. obj.forEach(function (topic) {
  415. if (that._resubscribeTopics[topic] < opts.qos ||
  416. !that._resubscribeTopics.hasOwnProperty(topic) ||
  417. resubscribe) {
  418. subs.push({
  419. topic: topic,
  420. qos: opts.qos
  421. })
  422. }
  423. })
  424. } else {
  425. Object
  426. .keys(obj)
  427. .forEach(function (k) {
  428. if (that._resubscribeTopics[k] < obj[k] ||
  429. !that._resubscribeTopics.hasOwnProperty(k) ||
  430. resubscribe) {
  431. subs.push({
  432. topic: k,
  433. qos: obj[k]
  434. })
  435. }
  436. })
  437. }
  438. packet = {
  439. cmd: 'subscribe',
  440. subscriptions: subs,
  441. qos: 1,
  442. retain: false,
  443. dup: false,
  444. messageId: this._nextId()
  445. }
  446. if (!subs.length) {
  447. callback(null, [])
  448. return
  449. }
  450. // subscriptions to resubscribe to in case of disconnect
  451. if (this.options.resubscribe) {
  452. var topics = []
  453. subs.forEach(function (sub) {
  454. if (that.options.reconnectPeriod > 0) {
  455. that._resubscribeTopics[sub.topic] = sub.qos
  456. topics.push(sub.topic)
  457. }
  458. })
  459. that.messageIdToTopic[packet.messageId] = topics
  460. }
  461. this.outgoing[packet.messageId] = function (err, packet) {
  462. if (!err) {
  463. var granted = packet.granted
  464. for (var i = 0; i < granted.length; i += 1) {
  465. subs[i].qos = granted[i]
  466. }
  467. }
  468. callback(err, subs)
  469. }
  470. this._sendPacket(packet)
  471. return this
  472. }
  473. /**
  474. * unsubscribe - unsubscribe from topic(s)
  475. *
  476. * @param {String, Array} topic - topics to unsubscribe from
  477. * @param {Function} [callback] - callback fired on unsuback
  478. * @returns {MqttClient} this - for chaining
  479. * @api public
  480. * @example client.unsubscribe('topic');
  481. * @example client.unsubscribe('topic', console.log);
  482. */
  483. MqttClient.prototype.unsubscribe = function (topic, callback) {
  484. var packet = {
  485. cmd: 'unsubscribe',
  486. qos: 1,
  487. messageId: this._nextId()
  488. }
  489. var that = this
  490. callback = callback || nop
  491. if (this._checkDisconnecting(callback)) {
  492. return this
  493. }
  494. if (typeof topic === 'string') {
  495. packet.unsubscriptions = [topic]
  496. } else if (typeof topic === 'object' && topic.length) {
  497. packet.unsubscriptions = topic
  498. }
  499. if (this.options.resubscribe) {
  500. packet.unsubscriptions.forEach(function (topic) {
  501. delete that._resubscribeTopics[topic]
  502. })
  503. }
  504. this.outgoing[packet.messageId] = callback
  505. this._sendPacket(packet)
  506. return this
  507. }
  508. /**
  509. * end - close connection
  510. *
  511. * @returns {MqttClient} this - for chaining
  512. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  513. * @param {Function} cb - called when the client has been closed
  514. *
  515. * @api public
  516. */
  517. MqttClient.prototype.end = function (force, cb) {
  518. var that = this
  519. if (typeof force === 'function') {
  520. cb = force
  521. force = false
  522. }
  523. function closeStores () {
  524. that.disconnected = true
  525. that.incomingStore.close(function () {
  526. that.outgoingStore.close(function () {
  527. if (cb) {
  528. cb.apply(null, arguments)
  529. }
  530. that.emit('end')
  531. })
  532. })
  533. if (that._deferredReconnect) {
  534. that._deferredReconnect()
  535. }
  536. }
  537. function finish () {
  538. // defer closesStores of an I/O cycle,
  539. // just to make sure things are
  540. // ok for websockets
  541. that._cleanUp(force, setImmediate.bind(null, closeStores))
  542. }
  543. if (this.disconnecting) {
  544. return this
  545. }
  546. this._clearReconnect()
  547. this.disconnecting = true
  548. if (!force && Object.keys(this.outgoing).length > 0) {
  549. // wait 10ms, just to be sure we received all of it
  550. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  551. } else {
  552. finish()
  553. }
  554. return this
  555. }
  556. /**
  557. * removeOutgoingMessage - remove a message in outgoing store
  558. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  559. *
  560. * @param {Number} mid - messageId to remove message
  561. * @returns {MqttClient} this - for chaining
  562. * @api public
  563. *
  564. * @example client.removeOutgoingMessage(client.getLastMessageId());
  565. */
  566. MqttClient.prototype.removeOutgoingMessage = function (mid) {
  567. var cb = this.outgoing[mid]
  568. delete this.outgoing[mid]
  569. this.outgoingStore.del({messageId: mid}, function () {
  570. cb(new Error('Message removed'))
  571. })
  572. return this
  573. }
  574. /**
  575. * reconnect - connect again using the same options as connect()
  576. *
  577. * @param {Object} [opts] - optional reconnect options, includes:
  578. * {Store} incomingStore - a store for the incoming packets
  579. * {Store} outgoingStore - a store for the outgoing packets
  580. * if opts is not given, current stores are used
  581. * @returns {MqttClient} this - for chaining
  582. *
  583. * @api public
  584. */
  585. MqttClient.prototype.reconnect = function (opts) {
  586. var that = this
  587. var f = function () {
  588. if (opts) {
  589. that.options.incomingStore = opts.incomingStore
  590. that.options.outgoingStore = opts.outgoingStore
  591. } else {
  592. that.options.incomingStore = null
  593. that.options.outgoingStore = null
  594. }
  595. that.incomingStore = that.options.incomingStore || new Store()
  596. that.outgoingStore = that.options.outgoingStore || new Store()
  597. that.disconnecting = false
  598. that.disconnected = false
  599. that._deferredReconnect = null
  600. that._reconnect()
  601. }
  602. if (this.disconnecting && !this.disconnected) {
  603. this._deferredReconnect = f
  604. } else {
  605. f()
  606. }
  607. return this
  608. }
  609. /**
  610. * _reconnect - implement reconnection
  611. * @api privateish
  612. */
  613. MqttClient.prototype._reconnect = function () {
  614. this.emit('reconnect')
  615. this._setupStream()
  616. }
  617. /**
  618. * _setupReconnect - setup reconnect timer
  619. */
  620. MqttClient.prototype._setupReconnect = function () {
  621. var that = this
  622. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  623. if (!this.reconnecting) {
  624. this.emit('offline')
  625. this.reconnecting = true
  626. }
  627. that.reconnectTimer = setInterval(function () {
  628. that._reconnect()
  629. }, that.options.reconnectPeriod)
  630. }
  631. }
  632. /**
  633. * _clearReconnect - clear the reconnect timer
  634. */
  635. MqttClient.prototype._clearReconnect = function () {
  636. if (this.reconnectTimer) {
  637. clearInterval(this.reconnectTimer)
  638. this.reconnectTimer = null
  639. }
  640. }
  641. /**
  642. * _cleanUp - clean up on connection end
  643. * @api private
  644. */
  645. MqttClient.prototype._cleanUp = function (forced, done) {
  646. if (done) {
  647. this.stream.on('close', done)
  648. }
  649. if (forced) {
  650. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  651. flush(this.outgoing)
  652. }
  653. this.stream.destroy()
  654. } else {
  655. this._sendPacket(
  656. { cmd: 'disconnect' },
  657. setImmediate.bind(
  658. null,
  659. this.stream.end.bind(this.stream)
  660. )
  661. )
  662. }
  663. if (!this.disconnecting) {
  664. this._clearReconnect()
  665. this._setupReconnect()
  666. }
  667. if (this.pingTimer !== null) {
  668. this.pingTimer.clear()
  669. this.pingTimer = null
  670. }
  671. if (done && !this.connected) {
  672. this.stream.removeListener('close', done)
  673. done()
  674. }
  675. }
  676. /**
  677. * _sendPacket - send or queue a packet
  678. * @param {String} type - packet type (see `protocol`)
  679. * @param {Object} packet - packet options
  680. * @param {Function} cb - callback when the packet is sent
  681. * @api private
  682. */
  683. MqttClient.prototype._sendPacket = function (packet, cb) {
  684. if (!this.connected) {
  685. if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
  686. this.queue.push({ packet: packet, cb: cb })
  687. } else if (packet.qos > 0) {
  688. cb = this.outgoing[packet.messageId]
  689. this.outgoingStore.put(packet, function (err) {
  690. if (err) {
  691. return cb && cb(err)
  692. }
  693. })
  694. } else if (cb) {
  695. cb(new Error('No connection to broker'))
  696. }
  697. return
  698. }
  699. // When sending a packet, reschedule the ping timer
  700. this._shiftPingInterval()
  701. switch (packet.cmd) {
  702. case 'publish':
  703. break
  704. case 'pubrel':
  705. storeAndSend(this, packet, cb)
  706. return
  707. default:
  708. sendPacket(this, packet, cb)
  709. return
  710. }
  711. switch (packet.qos) {
  712. case 2:
  713. case 1:
  714. storeAndSend(this, packet, cb)
  715. break
  716. /**
  717. * no need of case here since it will be caught by default
  718. * and jshint comply that before default it must be a break
  719. * anyway it will result in -1 evaluation
  720. */
  721. case 0:
  722. /* falls through */
  723. default:
  724. sendPacket(this, packet, cb)
  725. break
  726. }
  727. }
  728. /**
  729. * _setupPingTimer - setup the ping timer
  730. *
  731. * @api private
  732. */
  733. MqttClient.prototype._setupPingTimer = function () {
  734. var that = this
  735. if (!this.pingTimer && this.options.keepalive) {
  736. this.pingResp = true
  737. this.pingTimer = reInterval(function () {
  738. that._checkPing()
  739. }, this.options.keepalive * 1000)
  740. }
  741. }
  742. /**
  743. * _shiftPingInterval - reschedule the ping interval
  744. *
  745. * @api private
  746. */
  747. MqttClient.prototype._shiftPingInterval = function () {
  748. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  749. this.pingTimer.reschedule(this.options.keepalive * 1000)
  750. }
  751. }
  752. /**
  753. * _checkPing - check if a pingresp has come back, and ping the server again
  754. *
  755. * @api private
  756. */
  757. MqttClient.prototype._checkPing = function () {
  758. if (this.pingResp) {
  759. this.pingResp = false
  760. this._sendPacket({ cmd: 'pingreq' })
  761. } else {
  762. // do a forced cleanup since socket will be in bad shape
  763. this._cleanUp(true)
  764. }
  765. }
  766. /**
  767. * _handlePingresp - handle a pingresp
  768. *
  769. * @api private
  770. */
  771. MqttClient.prototype._handlePingresp = function () {
  772. this.pingResp = true
  773. }
  774. /**
  775. * _handleConnack
  776. *
  777. * @param {Object} packet
  778. * @api private
  779. */
  780. MqttClient.prototype._handleConnack = function (packet) {
  781. var rc = packet.returnCode
  782. var errors = [
  783. '',
  784. 'Unacceptable protocol version',
  785. 'Identifier rejected',
  786. 'Server unavailable',
  787. 'Bad username or password',
  788. 'Not authorized'
  789. ]
  790. clearTimeout(this.connackTimer)
  791. if (rc === 0) {
  792. this.reconnecting = false
  793. this.emit('connect', packet)
  794. } else if (rc > 0) {
  795. var err = new Error('Connection refused: ' + errors[rc])
  796. err.code = rc
  797. this.emit('error', err)
  798. }
  799. }
  800. /**
  801. * _handlePublish
  802. *
  803. * @param {Object} packet
  804. * @api private
  805. */
  806. /*
  807. those late 2 case should be rewrite to comply with coding style:
  808. case 1:
  809. case 0:
  810. // do not wait sending a puback
  811. // no callback passed
  812. if (1 === qos) {
  813. this._sendPacket({
  814. cmd: 'puback',
  815. messageId: mid
  816. });
  817. }
  818. // emit the message event for both qos 1 and 0
  819. this.emit('message', topic, message, packet);
  820. this.handleMessage(packet, done);
  821. break;
  822. default:
  823. // do nothing but every switch mus have a default
  824. // log or throw an error about unknown qos
  825. break;
  826. for now i just suppressed the warnings
  827. */
  828. MqttClient.prototype._handlePublish = function (packet, done) {
  829. done = typeof done !== 'undefined' ? done : nop
  830. var topic = packet.topic.toString()
  831. var message = packet.payload
  832. var qos = packet.qos
  833. var mid = packet.messageId
  834. var that = this
  835. switch (qos) {
  836. case 2:
  837. this.incomingStore.put(packet, function (err) {
  838. if (err) {
  839. return done(err)
  840. }
  841. that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
  842. })
  843. break
  844. case 1:
  845. // emit the message event
  846. this.emit('message', topic, message, packet)
  847. this.handleMessage(packet, function (err) {
  848. if (err) {
  849. return done(err)
  850. }
  851. // send 'puback' if the above 'handleMessage' method executed
  852. // successfully.
  853. that._sendPacket({cmd: 'puback', messageId: mid}, done)
  854. })
  855. break
  856. case 0:
  857. // emit the message event
  858. this.emit('message', topic, message, packet)
  859. this.handleMessage(packet, done)
  860. break
  861. default:
  862. // do nothing
  863. // log or throw an error about unknown qos
  864. break
  865. }
  866. }
  867. /**
  868. * Handle messages with backpressure support, one at a time.
  869. * Override at will.
  870. *
  871. * @param Packet packet the packet
  872. * @param Function callback call when finished
  873. * @api public
  874. */
  875. MqttClient.prototype.handleMessage = function (packet, callback) {
  876. callback()
  877. }
  878. /**
  879. * _handleAck
  880. *
  881. * @param {Object} packet
  882. * @api private
  883. */
  884. MqttClient.prototype._handleAck = function (packet) {
  885. /* eslint no-fallthrough: "off" */
  886. var mid = packet.messageId
  887. var type = packet.cmd
  888. var response = null
  889. var cb = this.outgoing[mid]
  890. var that = this
  891. if (!cb) {
  892. // Server sent an ack in error, ignore it.
  893. return
  894. }
  895. // Process
  896. switch (type) {
  897. case 'pubcomp':
  898. // same thing as puback for QoS 2
  899. case 'puback':
  900. // Callback - we're done
  901. delete this.outgoing[mid]
  902. this.outgoingStore.del(packet, cb)
  903. break
  904. case 'pubrec':
  905. response = {
  906. cmd: 'pubrel',
  907. qos: 2,
  908. messageId: mid
  909. }
  910. this._sendPacket(response)
  911. break
  912. case 'suback':
  913. delete this.outgoing[mid]
  914. if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) {
  915. // suback with Failure status
  916. var topics = this.messageIdToTopic[mid]
  917. if (topics) {
  918. topics.forEach(function (topic) {
  919. delete that._resubscribeTopics[topic]
  920. })
  921. }
  922. }
  923. cb(null, packet)
  924. break
  925. case 'unsuback':
  926. delete this.outgoing[mid]
  927. cb(null)
  928. break
  929. default:
  930. that.emit('error', new Error('unrecognized packet type'))
  931. }
  932. if (this.disconnecting &&
  933. Object.keys(this.outgoing).length === 0) {
  934. this.emit('outgoingEmpty')
  935. }
  936. }
  937. /**
  938. * _handlePubrel
  939. *
  940. * @param {Object} packet
  941. * @api private
  942. */
  943. MqttClient.prototype._handlePubrel = function (packet, callback) {
  944. callback = typeof callback !== 'undefined' ? callback : nop
  945. var mid = packet.messageId
  946. var that = this
  947. var comp = {cmd: 'pubcomp', messageId: mid}
  948. that.incomingStore.get(packet, function (err, pub) {
  949. if (!err && pub.cmd !== 'pubrel') {
  950. that.emit('message', pub.topic, pub.payload, pub)
  951. that.incomingStore.put(packet, function (err) {
  952. if (err) {
  953. return callback(err)
  954. }
  955. that.handleMessage(pub, function (err) {
  956. if (err) {
  957. return callback(err)
  958. }
  959. that._sendPacket(comp, callback)
  960. })
  961. })
  962. } else {
  963. that._sendPacket(comp, callback)
  964. }
  965. })
  966. }
  967. /**
  968. * _nextId
  969. * @return unsigned int
  970. */
  971. MqttClient.prototype._nextId = function () {
  972. // id becomes current state of this.nextId and increments afterwards
  973. var id = this.nextId++
  974. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  975. if (this.nextId === 65536) {
  976. this.nextId = 1
  977. }
  978. return id
  979. }
  980. /**
  981. * getLastMessageId
  982. * @return unsigned int
  983. */
  984. MqttClient.prototype.getLastMessageId = function () {
  985. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  986. }
  987. module.exports = MqttClient
  988. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  989. },{"./store":6,"./validations":7,"_process":96,"end-of-stream":16,"events":79,"inherits":84,"mqtt-packet":89,"readable-stream":112,"reinterval":113,"xtend":165}],2:[function(require,module,exports){
  990. 'use strict'
  991. var net = require('net')
  992. /*
  993. variables port and host can be removed since
  994. you have all required information in opts object
  995. */
  996. function buildBuilder (client, opts) {
  997. var port, host
  998. opts.port = opts.port || 1883
  999. opts.hostname = opts.hostname || opts.host || 'localhost'
  1000. port = opts.port
  1001. host = opts.hostname
  1002. return net.createConnection(port, host)
  1003. }
  1004. module.exports = buildBuilder
  1005. },{"net":11}],3:[function(require,module,exports){
  1006. 'use strict'
  1007. var tls = require('tls')
  1008. function buildBuilder (mqttClient, opts) {
  1009. var connection
  1010. opts.port = opts.port || 8883
  1011. opts.host = opts.hostname || opts.host || 'localhost'
  1012. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1013. delete opts.path
  1014. connection = tls.connect(opts)
  1015. /* eslint no-use-before-define: [2, "nofunc"] */
  1016. connection.on('secureConnect', function () {
  1017. if (opts.rejectUnauthorized && !connection.authorized) {
  1018. connection.emit('error', new Error('TLS not authorized'))
  1019. } else {
  1020. connection.removeListener('error', handleTLSerrors)
  1021. }
  1022. })
  1023. function handleTLSerrors (err) {
  1024. // How can I get verify this error is a tls error?
  1025. if (opts.rejectUnauthorized) {
  1026. mqttClient.emit('error', err)
  1027. }
  1028. // close this connection to match the behaviour of net
  1029. // otherwise all we get is an error from the connection
  1030. // and close event doesn't fire. This is a work around
  1031. // to enable the reconnect code to work the same as with
  1032. // net.createConnection
  1033. connection.end()
  1034. }
  1035. connection.on('error', handleTLSerrors)
  1036. return connection
  1037. }
  1038. module.exports = buildBuilder
  1039. },{"tls":11}],4:[function(require,module,exports){
  1040. (function (process){(function (){
  1041. 'use strict'
  1042. var websocket = require('websocket-stream')
  1043. var urlModule = require('url')
  1044. var WSS_OPTIONS = [
  1045. 'rejectUnauthorized',
  1046. 'ca',
  1047. 'cert',
  1048. 'key',
  1049. 'pfx',
  1050. 'passphrase'
  1051. ]
  1052. var IS_BROWSER = process.title === 'browser'
  1053. function buildUrl (opts, client) {
  1054. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1055. if (typeof (opts.transformWsUrl) === 'function') {
  1056. url = opts.transformWsUrl(url, opts, client)
  1057. }
  1058. return url
  1059. }
  1060. function setDefaultOpts (opts) {
  1061. if (!opts.hostname) {
  1062. opts.hostname = 'localhost'
  1063. }
  1064. if (!opts.port) {
  1065. if (opts.protocol === 'wss') {
  1066. opts.port = 443
  1067. } else {
  1068. opts.port = 80
  1069. }
  1070. }
  1071. if (!opts.path) {
  1072. opts.path = '/'
  1073. }
  1074. if (!opts.wsOptions) {
  1075. opts.wsOptions = {}
  1076. }
  1077. if (!IS_BROWSER && opts.protocol === 'wss') {
  1078. // Add cert/key/ca etc options
  1079. WSS_OPTIONS.forEach(function (prop) {
  1080. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  1081. opts.wsOptions[prop] = opts[prop]
  1082. }
  1083. })
  1084. }
  1085. }
  1086. function createWebSocket (client, opts) {
  1087. var websocketSubProtocol =
  1088. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1089. ? 'mqttv3.1'
  1090. : 'mqtt'
  1091. setDefaultOpts(opts)
  1092. var url = buildUrl(opts, client)
  1093. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1094. }
  1095. function buildBuilder (client, opts) {
  1096. return createWebSocket(client, opts)
  1097. }
  1098. function buildBuilderBrowser (client, opts) {
  1099. if (!opts.hostname) {
  1100. opts.hostname = opts.host
  1101. }
  1102. if (!opts.hostname) {
  1103. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1104. // can not determine the `hostname` automatically. If connecting to
  1105. // localhost, please supply the `hostname` as an argument.
  1106. if (typeof (document) === 'undefined') {
  1107. throw new Error('Could not determine host. Specify host manually.')
  1108. }
  1109. var parsed = urlModule.parse(document.URL)
  1110. opts.hostname = parsed.hostname
  1111. if (!opts.port) {
  1112. opts.port = parsed.port
  1113. }
  1114. }
  1115. return createWebSocket(client, opts)
  1116. }
  1117. if (IS_BROWSER) {
  1118. module.exports = buildBuilderBrowser
  1119. } else {
  1120. module.exports = buildBuilder
  1121. }
  1122. }).call(this)}).call(this,require('_process'))
  1123. },{"_process":96,"url":128,"websocket-stream":162}],5:[function(require,module,exports){
  1124. 'use strict'
  1125. /* global wx */
  1126. var socketOpen = false
  1127. var socketMsgQueue = []
  1128. function sendSocketMessage (msg) {
  1129. if (socketOpen) {
  1130. wx.sendSocketMessage({
  1131. data: msg.buffer || msg
  1132. })
  1133. } else {
  1134. socketMsgQueue.push(msg)
  1135. }
  1136. }
  1137. function WebSocket (url, protocols) {
  1138. var ws = {
  1139. OPEN: 1,
  1140. CLOSING: 2,
  1141. CLOSED: 3,
  1142. readyState: socketOpen ? 1 : 0,
  1143. send: sendSocketMessage,
  1144. close: wx.closeSocket,
  1145. onopen: null,
  1146. onmessage: null,
  1147. onclose: null,
  1148. onerror: null
  1149. }
  1150. wx.connectSocket({
  1151. url: url,
  1152. protocols: protocols
  1153. })
  1154. wx.onSocketOpen(function (res) {
  1155. ws.readyState = ws.OPEN
  1156. socketOpen = true
  1157. for (var i = 0; i < socketMsgQueue.length; i++) {
  1158. sendSocketMessage(socketMsgQueue[i])
  1159. }
  1160. socketMsgQueue = []
  1161. ws.onopen && ws.onopen.apply(ws, arguments)
  1162. })
  1163. wx.onSocketMessage(function (res) {
  1164. ws.onmessage && ws.onmessage.apply(ws, arguments)
  1165. })
  1166. wx.onSocketClose(function () {
  1167. ws.onclose && ws.onclose.apply(ws, arguments)
  1168. ws.readyState = ws.CLOSED
  1169. socketOpen = false
  1170. })
  1171. wx.onSocketError(function () {
  1172. ws.onerror && ws.onerror.apply(ws, arguments)
  1173. ws.readyState = ws.CLOSED
  1174. socketOpen = false
  1175. })
  1176. return ws
  1177. }
  1178. var websocket = require('websocket-stream')
  1179. function buildUrl (opts, client) {
  1180. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1181. var url = protocol + '://' + opts.hostname + opts.path
  1182. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1183. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1184. }
  1185. if (typeof (opts.transformWsUrl) === 'function') {
  1186. url = opts.transformWsUrl(url, opts, client)
  1187. }
  1188. return url
  1189. }
  1190. function setDefaultOpts (opts) {
  1191. if (!opts.hostname) {
  1192. opts.hostname = 'localhost'
  1193. }
  1194. if (!opts.path) {
  1195. opts.path = '/'
  1196. }
  1197. if (!opts.wsOptions) {
  1198. opts.wsOptions = {}
  1199. }
  1200. }
  1201. function createWebSocket (client, opts) {
  1202. var websocketSubProtocol =
  1203. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1204. ? 'mqttv3.1'
  1205. : 'mqtt'
  1206. setDefaultOpts(opts)
  1207. var url = buildUrl(opts, client)
  1208. return websocket(WebSocket(url, [websocketSubProtocol]))
  1209. }
  1210. function buildBuilder (client, opts) {
  1211. opts.hostname = opts.hostname || opts.host
  1212. if (!opts.hostname) {
  1213. throw new Error('Could not determine host. Specify host manually.')
  1214. }
  1215. return createWebSocket(client, opts)
  1216. }
  1217. module.exports = buildBuilder
  1218. },{"websocket-stream":162}],6:[function(require,module,exports){
  1219. (function (process){(function (){
  1220. 'use strict'
  1221. /**
  1222. * Module dependencies
  1223. */
  1224. var xtend = require('xtend')
  1225. var Readable = require('readable-stream').Readable
  1226. var streamsOpts = { objectMode: true }
  1227. var defaultStoreOptions = {
  1228. clean: true
  1229. }
  1230. /**
  1231. * es6-map can preserve insertion order even if ES version is older.
  1232. *
  1233. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
  1234. * It should be noted that a Map which is a map of an object, especially
  1235. * a dictionary of dictionaries, will only map to the object's insertion
  1236. * order. In ES2015 this is ordered for objects but for older versions of
  1237. * ES, this may be random and not ordered.
  1238. *
  1239. */
  1240. var Map = require('es6-map')
  1241. /**
  1242. * In-memory implementation of the message store
  1243. * This can actually be saved into files.
  1244. *
  1245. * @param {Object} [options] - store options
  1246. */
  1247. function Store (options) {
  1248. if (!(this instanceof Store)) {
  1249. return new Store(options)
  1250. }
  1251. this.options = options || {}
  1252. // Defaults
  1253. this.options = xtend(defaultStoreOptions, options)
  1254. this._inflights = new Map()
  1255. }
  1256. /**
  1257. * Adds a packet to the store, a packet is
  1258. * anything that has a messageId property.
  1259. *
  1260. */
  1261. Store.prototype.put = function (packet, cb) {
  1262. this._inflights.set(packet.messageId, packet)
  1263. if (cb) {
  1264. cb()
  1265. }
  1266. return this
  1267. }
  1268. /**
  1269. * Creates a stream with all the packets in the store
  1270. *
  1271. */
  1272. Store.prototype.createStream = function () {
  1273. var stream = new Readable(streamsOpts)
  1274. var destroyed = false
  1275. var values = []
  1276. var i = 0
  1277. this._inflights.forEach(function (value, key) {
  1278. values.push(value)
  1279. })
  1280. stream._read = function () {
  1281. if (!destroyed && i < values.length) {
  1282. this.push(values[i++])
  1283. } else {
  1284. this.push(null)
  1285. }
  1286. }
  1287. stream.destroy = function () {
  1288. if (destroyed) {
  1289. return
  1290. }
  1291. var self = this
  1292. destroyed = true
  1293. process.nextTick(function () {
  1294. self.emit('close')
  1295. })
  1296. }
  1297. return stream
  1298. }
  1299. /**
  1300. * deletes a packet from the store.
  1301. */
  1302. Store.prototype.del = function (packet, cb) {
  1303. packet = this._inflights.get(packet.messageId)
  1304. if (packet) {
  1305. this._inflights.delete(packet.messageId)
  1306. cb(null, packet)
  1307. } else if (cb) {
  1308. cb(new Error('missing packet'))
  1309. }
  1310. return this
  1311. }
  1312. /**
  1313. * get a packet from the store.
  1314. */
  1315. Store.prototype.get = function (packet, cb) {
  1316. packet = this._inflights.get(packet.messageId)
  1317. if (packet) {
  1318. cb(null, packet)
  1319. } else if (cb) {
  1320. cb(new Error('missing packet'))
  1321. }
  1322. return this
  1323. }
  1324. /**
  1325. * Close the store
  1326. */
  1327. Store.prototype.close = function (cb) {
  1328. if (this.options.clean) {
  1329. this._inflights = null
  1330. }
  1331. if (cb) {
  1332. cb()
  1333. }
  1334. }
  1335. module.exports = Store
  1336. }).call(this)}).call(this,require('_process'))
  1337. },{"_process":96,"es6-map":64,"readable-stream":112,"xtend":165}],7:[function(require,module,exports){
  1338. 'use strict'
  1339. /**
  1340. * Validate a topic to see if it's valid or not.
  1341. * A topic is valid if it follow below rules:
  1342. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1343. * - Rule #2: Part `#` must be located at the end of the mailbox
  1344. *
  1345. * @param {String} topic - A topic
  1346. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1347. */
  1348. function validateTopic (topic) {
  1349. var parts = topic.split('/')
  1350. for (var i = 0; i < parts.length; i++) {
  1351. if (parts[i] === '+') {
  1352. continue
  1353. }
  1354. if (parts[i] === '#') {
  1355. // for Rule #2
  1356. return i === parts.length - 1
  1357. }
  1358. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1359. return false
  1360. }
  1361. }
  1362. return true
  1363. }
  1364. /**
  1365. * Validate an array of topics to see if any of them is valid or not
  1366. * @param {Array} topics - Array of topics
  1367. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1368. */
  1369. function validateTopics (topics) {
  1370. if (topics.length === 0) {
  1371. return 'empty_topic_list'
  1372. }
  1373. for (var i = 0; i < topics.length; i++) {
  1374. if (!validateTopic(topics[i])) {
  1375. return topics[i]
  1376. }
  1377. }
  1378. return null
  1379. }
  1380. module.exports = {
  1381. validateTopics: validateTopics
  1382. }
  1383. },{}],8:[function(require,module,exports){
  1384. (function (process){(function (){
  1385. 'use strict'
  1386. var MqttClient = require('../client')
  1387. var Store = require('../store')
  1388. var url = require('url')
  1389. var xtend = require('xtend')
  1390. var protocols = {}
  1391. if (process.title !== 'browser') {
  1392. protocols.mqtt = require('./tcp')
  1393. protocols.tcp = require('./tcp')
  1394. protocols.ssl = require('./tls')
  1395. protocols.tls = require('./tls')
  1396. protocols.mqtts = require('./tls')
  1397. } else {
  1398. protocols.wx = require('./wx')
  1399. protocols.wxs = require('./wx')
  1400. }
  1401. protocols.ws = require('./ws')
  1402. protocols.wss = require('./ws')
  1403. /**
  1404. * Parse the auth attribute and merge username and password in the options object.
  1405. *
  1406. * @param {Object} [opts] option object
  1407. */
  1408. function parseAuthOptions (opts) {
  1409. var matches
  1410. if (opts.auth) {
  1411. matches = opts.auth.match(/^(.+):(.+)$/)
  1412. if (matches) {
  1413. opts.username = matches[1]
  1414. opts.password = matches[2]
  1415. } else {
  1416. opts.username = opts.auth
  1417. }
  1418. }
  1419. }
  1420. /**
  1421. * connect - connect to an MQTT broker.
  1422. *
  1423. * @param {String} [brokerUrl] - url of the broker, optional
  1424. * @param {Object} opts - see MqttClient#constructor
  1425. */
  1426. function connect (brokerUrl, opts) {
  1427. if ((typeof brokerUrl === 'object') && !opts) {
  1428. opts = brokerUrl
  1429. brokerUrl = null
  1430. }
  1431. opts = opts || {}
  1432. if (brokerUrl) {
  1433. var parsed = url.parse(brokerUrl, true)
  1434. if (parsed.port != null) {
  1435. parsed.port = Number(parsed.port)
  1436. }
  1437. opts = xtend(parsed, opts)
  1438. if (opts.protocol === null) {
  1439. throw new Error('Missing protocol')
  1440. }
  1441. opts.protocol = opts.protocol.replace(/:$/, '')
  1442. }
  1443. // merge in the auth options if supplied
  1444. parseAuthOptions(opts)
  1445. // support clientId passed in the query string of the url
  1446. if (opts.query && typeof opts.query.clientId === 'string') {
  1447. opts.clientId = opts.query.clientId
  1448. }
  1449. if (opts.cert && opts.key) {
  1450. if (opts.protocol) {
  1451. if (['mqtts', 'wss', 'wxs'].indexOf(opts.protocol) === -1) {
  1452. switch (opts.protocol) {
  1453. case 'mqtt':
  1454. opts.protocol = 'mqtts'
  1455. break
  1456. case 'ws':
  1457. opts.protocol = 'wss'
  1458. break
  1459. case 'wx':
  1460. opts.protocol = 'wxs'
  1461. break
  1462. default:
  1463. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  1464. }
  1465. }
  1466. } else {
  1467. // don't know what protocol he want to use, mqtts or wss
  1468. throw new Error('Missing secure protocol key')
  1469. }
  1470. }
  1471. if (!protocols[opts.protocol]) {
  1472. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  1473. opts.protocol = [
  1474. 'mqtt',
  1475. 'mqtts',
  1476. 'ws',
  1477. 'wss',
  1478. 'wx',
  1479. 'wxs'
  1480. ].filter(function (key, index) {
  1481. if (isSecure && index % 2 === 0) {
  1482. // Skip insecure protocols when requesting a secure one.
  1483. return false
  1484. }
  1485. return (typeof protocols[key] === 'function')
  1486. })[0]
  1487. }
  1488. if (opts.clean === false && !opts.clientId) {
  1489. throw new Error('Missing clientId for unclean clients')
  1490. }
  1491. if (opts.protocol) {
  1492. opts.defaultProtocol = opts.protocol
  1493. }
  1494. function wrapper (client) {
  1495. if (opts.servers) {
  1496. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  1497. client._reconnectCount = 0
  1498. }
  1499. opts.host = opts.servers[client._reconnectCount].host
  1500. opts.port = opts.servers[client._reconnectCount].port
  1501. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  1502. opts.hostname = opts.host
  1503. client._reconnectCount++
  1504. }
  1505. return protocols[opts.protocol](client, opts)
  1506. }
  1507. return new MqttClient(wrapper, opts)
  1508. }
  1509. module.exports = connect
  1510. module.exports.connect = connect
  1511. module.exports.MqttClient = MqttClient
  1512. module.exports.Store = Store
  1513. }).call(this)}).call(this,require('_process'))
  1514. },{"../client":1,"../store":6,"./tcp":2,"./tls":3,"./ws":4,"./wx":5,"_process":96,"url":128,"xtend":165}],9:[function(require,module,exports){
  1515. 'use strict'
  1516. exports.byteLength = byteLength
  1517. exports.toByteArray = toByteArray
  1518. exports.fromByteArray = fromByteArray
  1519. var lookup = []
  1520. var revLookup = []
  1521. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1522. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1523. for (var i = 0, len = code.length; i < len; ++i) {
  1524. lookup[i] = code[i]
  1525. revLookup[code.charCodeAt(i)] = i
  1526. }
  1527. // Support decoding URL-safe base64 strings, as Node.js does.
  1528. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  1529. revLookup['-'.charCodeAt(0)] = 62
  1530. revLookup['_'.charCodeAt(0)] = 63
  1531. function getLens (b64) {
  1532. var len = b64.length
  1533. if (len % 4 > 0) {
  1534. throw new Error('Invalid string. Length must be a multiple of 4')
  1535. }
  1536. // Trim off extra bytes after placeholder bytes are found
  1537. // See: https://github.com/beatgammit/base64-js/issues/42
  1538. var validLen = b64.indexOf('=')
  1539. if (validLen === -1) validLen = len
  1540. var placeHoldersLen = validLen === len
  1541. ? 0
  1542. : 4 - (validLen % 4)
  1543. return [validLen, placeHoldersLen]
  1544. }
  1545. // base64 is 4/3 + up to two characters of the original data
  1546. function byteLength (b64) {
  1547. var lens = getLens(b64)
  1548. var validLen = lens[0]
  1549. var placeHoldersLen = lens[1]
  1550. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1551. }
  1552. function _byteLength (b64, validLen, placeHoldersLen) {
  1553. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1554. }
  1555. function toByteArray (b64) {
  1556. var tmp
  1557. var lens = getLens(b64)
  1558. var validLen = lens[0]
  1559. var placeHoldersLen = lens[1]
  1560. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  1561. var curByte = 0
  1562. // if there are placeholders, only get up to the last complete 4 chars
  1563. var len = placeHoldersLen > 0
  1564. ? validLen - 4
  1565. : validLen
  1566. var i
  1567. for (i = 0; i < len; i += 4) {
  1568. tmp =
  1569. (revLookup[b64.charCodeAt(i)] << 18) |
  1570. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  1571. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  1572. revLookup[b64.charCodeAt(i + 3)]
  1573. arr[curByte++] = (tmp >> 16) & 0xFF
  1574. arr[curByte++] = (tmp >> 8) & 0xFF
  1575. arr[curByte++] = tmp & 0xFF
  1576. }
  1577. if (placeHoldersLen === 2) {
  1578. tmp =
  1579. (revLookup[b64.charCodeAt(i)] << 2) |
  1580. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1581. arr[curByte++] = tmp & 0xFF
  1582. }
  1583. if (placeHoldersLen === 1) {
  1584. tmp =
  1585. (revLookup[b64.charCodeAt(i)] << 10) |
  1586. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  1587. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1588. arr[curByte++] = (tmp >> 8) & 0xFF
  1589. arr[curByte++] = tmp & 0xFF
  1590. }
  1591. return arr
  1592. }
  1593. function tripletToBase64 (num) {
  1594. return lookup[num >> 18 & 0x3F] +
  1595. lookup[num >> 12 & 0x3F] +
  1596. lookup[num >> 6 & 0x3F] +
  1597. lookup[num & 0x3F]
  1598. }
  1599. function encodeChunk (uint8, start, end) {
  1600. var tmp
  1601. var output = []
  1602. for (var i = start; i < end; i += 3) {
  1603. tmp =
  1604. ((uint8[i] << 16) & 0xFF0000) +
  1605. ((uint8[i + 1] << 8) & 0xFF00) +
  1606. (uint8[i + 2] & 0xFF)
  1607. output.push(tripletToBase64(tmp))
  1608. }
  1609. return output.join('')
  1610. }
  1611. function fromByteArray (uint8) {
  1612. var tmp
  1613. var len = uint8.length
  1614. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1615. var parts = []
  1616. var maxChunkLength = 16383 // must be multiple of 3
  1617. // go through the array every three bytes, we'll deal with trailing stuff later
  1618. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1619. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  1620. }
  1621. // pad the end with zeros, but make sure to not forget the extra bytes
  1622. if (extraBytes === 1) {
  1623. tmp = uint8[len - 1]
  1624. parts.push(
  1625. lookup[tmp >> 2] +
  1626. lookup[(tmp << 4) & 0x3F] +
  1627. '=='
  1628. )
  1629. } else if (extraBytes === 2) {
  1630. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  1631. parts.push(
  1632. lookup[tmp >> 10] +
  1633. lookup[(tmp >> 4) & 0x3F] +
  1634. lookup[(tmp << 2) & 0x3F] +
  1635. '='
  1636. )
  1637. }
  1638. return parts.join('')
  1639. }
  1640. },{}],10:[function(require,module,exports){
  1641. var DuplexStream = require('readable-stream/duplex')
  1642. , util = require('util')
  1643. , Buffer = require('safe-buffer').Buffer
  1644. function BufferList (callback) {
  1645. if (!(this instanceof BufferList))
  1646. return new BufferList(callback)
  1647. this._bufs = []
  1648. this.length = 0
  1649. if (typeof callback == 'function') {
  1650. this._callback = callback
  1651. var piper = function piper (err) {
  1652. if (this._callback) {
  1653. this._callback(err)
  1654. this._callback = null
  1655. }
  1656. }.bind(this)
  1657. this.on('pipe', function onPipe (src) {
  1658. src.on('error', piper)
  1659. })
  1660. this.on('unpipe', function onUnpipe (src) {
  1661. src.removeListener('error', piper)
  1662. })
  1663. } else {
  1664. this.append(callback)
  1665. }
  1666. DuplexStream.call(this)
  1667. }
  1668. util.inherits(BufferList, DuplexStream)
  1669. BufferList.prototype._offset = function _offset (offset) {
  1670. var tot = 0, i = 0, _t
  1671. if (offset === 0) return [ 0, 0 ]
  1672. for (; i < this._bufs.length; i++) {
  1673. _t = tot + this._bufs[i].length
  1674. if (offset < _t || i == this._bufs.length - 1)
  1675. return [ i, offset - tot ]
  1676. tot = _t
  1677. }
  1678. }
  1679. BufferList.prototype.append = function append (buf) {
  1680. var i = 0
  1681. if (Buffer.isBuffer(buf)) {
  1682. this._appendBuffer(buf);
  1683. } else if (Array.isArray(buf)) {
  1684. for (; i < buf.length; i++)
  1685. this.append(buf[i])
  1686. } else if (buf instanceof BufferList) {
  1687. // unwrap argument into individual BufferLists
  1688. for (; i < buf._bufs.length; i++)
  1689. this.append(buf._bufs[i])
  1690. } else if (buf != null) {
  1691. // coerce number arguments to strings, since Buffer(number) does
  1692. // uninitialized memory allocation
  1693. if (typeof buf == 'number')
  1694. buf = buf.toString()
  1695. this._appendBuffer(Buffer.from(buf));
  1696. }
  1697. return this
  1698. }
  1699. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  1700. this._bufs.push(buf)
  1701. this.length += buf.length
  1702. }
  1703. BufferList.prototype._write = function _write (buf, encoding, callback) {
  1704. this._appendBuffer(buf)
  1705. if (typeof callback == 'function')
  1706. callback()
  1707. }
  1708. BufferList.prototype._read = function _read (size) {
  1709. if (!this.length)
  1710. return this.push(null)
  1711. size = Math.min(size, this.length)
  1712. this.push(this.slice(0, size))
  1713. this.consume(size)
  1714. }
  1715. BufferList.prototype.end = function end (chunk) {
  1716. DuplexStream.prototype.end.call(this, chunk)
  1717. if (this._callback) {
  1718. this._callback(null, this.slice())
  1719. this._callback = null
  1720. }
  1721. }
  1722. BufferList.prototype.get = function get (index) {
  1723. return this.slice(index, index + 1)[0]
  1724. }
  1725. BufferList.prototype.slice = function slice (start, end) {
  1726. if (typeof start == 'number' && start < 0)
  1727. start += this.length
  1728. if (typeof end == 'number' && end < 0)
  1729. end += this.length
  1730. return this.copy(null, 0, start, end)
  1731. }
  1732. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  1733. if (typeof srcStart != 'number' || srcStart < 0)
  1734. srcStart = 0
  1735. if (typeof srcEnd != 'number' || srcEnd > this.length)
  1736. srcEnd = this.length
  1737. if (srcStart >= this.length)
  1738. return dst || Buffer.alloc(0)
  1739. if (srcEnd <= 0)
  1740. return dst || Buffer.alloc(0)
  1741. var copy = !!dst
  1742. , off = this._offset(srcStart)
  1743. , len = srcEnd - srcStart
  1744. , bytes = len
  1745. , bufoff = (copy && dstStart) || 0
  1746. , start = off[1]
  1747. , l
  1748. , i
  1749. // copy/slice everything
  1750. if (srcStart === 0 && srcEnd == this.length) {
  1751. if (!copy) { // slice, but full concat if multiple buffers
  1752. return this._bufs.length === 1
  1753. ? this._bufs[0]
  1754. : Buffer.concat(this._bufs, this.length)
  1755. }
  1756. // copy, need to copy individual buffers
  1757. for (i = 0; i < this._bufs.length; i++) {
  1758. this._bufs[i].copy(dst, bufoff)
  1759. bufoff += this._bufs[i].length
  1760. }
  1761. return dst
  1762. }
  1763. // easy, cheap case where it's a subset of one of the buffers
  1764. if (bytes <= this._bufs[off[0]].length - start) {
  1765. return copy
  1766. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  1767. : this._bufs[off[0]].slice(start, start + bytes)
  1768. }
  1769. if (!copy) // a slice, we need something to copy in to
  1770. dst = Buffer.allocUnsafe(len)
  1771. for (i = off[0]; i < this._bufs.length; i++) {
  1772. l = this._bufs[i].length - start
  1773. if (bytes > l) {
  1774. this._bufs[i].copy(dst, bufoff, start)
  1775. bufoff += l
  1776. } else {
  1777. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  1778. bufoff += l
  1779. break
  1780. }
  1781. bytes -= l
  1782. if (start)
  1783. start = 0
  1784. }
  1785. // safeguard so that we don't return uninitialized memory
  1786. if (dst.length > bufoff) return dst.slice(0, bufoff)
  1787. return dst
  1788. }
  1789. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  1790. start = start || 0
  1791. end = end || this.length
  1792. if (start < 0)
  1793. start += this.length
  1794. if (end < 0)
  1795. end += this.length
  1796. var startOffset = this._offset(start)
  1797. , endOffset = this._offset(end)
  1798. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  1799. if (endOffset[1] == 0)
  1800. buffers.pop()
  1801. else
  1802. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  1803. if (startOffset[1] != 0)
  1804. buffers[0] = buffers[0].slice(startOffset[1])
  1805. return new BufferList(buffers)
  1806. }
  1807. BufferList.prototype.toString = function toString (encoding, start, end) {
  1808. return this.slice(start, end).toString(encoding)
  1809. }
  1810. BufferList.prototype.consume = function consume (bytes) {
  1811. // first, normalize the argument, in accordance with how Buffer does it
  1812. bytes = Math.trunc(bytes)
  1813. // do nothing if not a positive number
  1814. if (Number.isNaN(bytes) || bytes <= 0) return this
  1815. while (this._bufs.length) {
  1816. if (bytes >= this._bufs[0].length) {
  1817. bytes -= this._bufs[0].length
  1818. this.length -= this._bufs[0].length
  1819. this._bufs.shift()
  1820. } else {
  1821. this._bufs[0] = this._bufs[0].slice(bytes)
  1822. this.length -= bytes
  1823. break
  1824. }
  1825. }
  1826. return this
  1827. }
  1828. BufferList.prototype.duplicate = function duplicate () {
  1829. var i = 0
  1830. , copy = new BufferList()
  1831. for (; i < this._bufs.length; i++)
  1832. copy.append(this._bufs[i])
  1833. return copy
  1834. }
  1835. BufferList.prototype.destroy = function destroy () {
  1836. this._bufs.length = 0
  1837. this.length = 0
  1838. this.push(null)
  1839. }
  1840. ;(function () {
  1841. var methods = {
  1842. 'readDoubleBE' : 8
  1843. , 'readDoubleLE' : 8
  1844. , 'readFloatBE' : 4
  1845. , 'readFloatLE' : 4
  1846. , 'readInt32BE' : 4
  1847. , 'readInt32LE' : 4
  1848. , 'readUInt32BE' : 4
  1849. , 'readUInt32LE' : 4
  1850. , 'readInt16BE' : 2
  1851. , 'readInt16LE' : 2
  1852. , 'readUInt16BE' : 2
  1853. , 'readUInt16LE' : 2
  1854. , 'readInt8' : 1
  1855. , 'readUInt8' : 1
  1856. }
  1857. for (var m in methods) {
  1858. (function (m) {
  1859. BufferList.prototype[m] = function (offset) {
  1860. return this.slice(offset, offset + methods[m])[m](0)
  1861. }
  1862. }(m))
  1863. }
  1864. }())
  1865. module.exports = BufferList
  1866. },{"readable-stream/duplex":101,"safe-buffer":114,"util":133}],11:[function(require,module,exports){
  1867. },{}],12:[function(require,module,exports){
  1868. (function (Buffer){(function (){
  1869. /*!
  1870. * The buffer module from node.js, for the browser.
  1871. *
  1872. * @author Feross Aboukhadijeh <https://feross.org>
  1873. * @license MIT
  1874. */
  1875. /* eslint-disable no-proto */
  1876. 'use strict'
  1877. var base64 = require('base64-js')
  1878. var ieee754 = require('ieee754')
  1879. exports.Buffer = Buffer
  1880. exports.SlowBuffer = SlowBuffer
  1881. exports.INSPECT_MAX_BYTES = 50
  1882. var K_MAX_LENGTH = 0x7fffffff
  1883. exports.kMaxLength = K_MAX_LENGTH
  1884. /**
  1885. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  1886. * === true Use Uint8Array implementation (fastest)
  1887. * === false Print warning and recommend using `buffer` v4.x which has an Object
  1888. * implementation (most compatible, even IE6)
  1889. *
  1890. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  1891. * Opera 11.6+, iOS 4.2+.
  1892. *
  1893. * We report that the browser does not support typed arrays if the are not subclassable
  1894. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  1895. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  1896. * for __proto__ and has a buggy typed array implementation.
  1897. */
  1898. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  1899. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  1900. typeof console.error === 'function') {
  1901. console.error(
  1902. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  1903. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  1904. )
  1905. }
  1906. function typedArraySupport () {
  1907. // Can typed array instances can be augmented?
  1908. try {
  1909. var arr = new Uint8Array(1)
  1910. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  1911. return arr.foo() === 42
  1912. } catch (e) {
  1913. return false
  1914. }
  1915. }
  1916. Object.defineProperty(Buffer.prototype, 'parent', {
  1917. enumerable: true,
  1918. get: function () {
  1919. if (!Buffer.isBuffer(this)) return undefined
  1920. return this.buffer
  1921. }
  1922. })
  1923. Object.defineProperty(Buffer.prototype, 'offset', {
  1924. enumerable: true,
  1925. get: function () {
  1926. if (!Buffer.isBuffer(this)) return undefined
  1927. return this.byteOffset
  1928. }
  1929. })
  1930. function createBuffer (length) {
  1931. if (length > K_MAX_LENGTH) {
  1932. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  1933. }
  1934. // Return an augmented `Uint8Array` instance
  1935. var buf = new Uint8Array(length)
  1936. buf.__proto__ = Buffer.prototype
  1937. return buf
  1938. }
  1939. /**
  1940. * The Buffer constructor returns instances of `Uint8Array` that have their
  1941. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  1942. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  1943. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  1944. * returns a single octet.
  1945. *
  1946. * The `Uint8Array` prototype remains unmodified.
  1947. */
  1948. function Buffer (arg, encodingOrOffset, length) {
  1949. // Common case.
  1950. if (typeof arg === 'number') {
  1951. if (typeof encodingOrOffset === 'string') {
  1952. throw new TypeError(
  1953. 'The "string" argument must be of type string. Received type number'
  1954. )
  1955. }
  1956. return allocUnsafe(arg)
  1957. }
  1958. return from(arg, encodingOrOffset, length)
  1959. }
  1960. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  1961. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  1962. Buffer[Symbol.species] === Buffer) {
  1963. Object.defineProperty(Buffer, Symbol.species, {
  1964. value: null,
  1965. configurable: true,
  1966. enumerable: false,
  1967. writable: false
  1968. })
  1969. }
  1970. Buffer.poolSize = 8192 // not used by this implementation
  1971. function from (value, encodingOrOffset, length) {
  1972. if (typeof value === 'string') {
  1973. return fromString(value, encodingOrOffset)
  1974. }
  1975. if (ArrayBuffer.isView(value)) {
  1976. return fromArrayLike(value)
  1977. }
  1978. if (value == null) {
  1979. throw TypeError(
  1980. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  1981. 'or Array-like Object. Received type ' + (typeof value)
  1982. )
  1983. }
  1984. if (isInstance(value, ArrayBuffer) ||
  1985. (value && isInstance(value.buffer, ArrayBuffer))) {
  1986. return fromArrayBuffer(value, encodingOrOffset, length)
  1987. }
  1988. if (typeof value === 'number') {
  1989. throw new TypeError(
  1990. 'The "value" argument must not be of type number. Received type number'
  1991. )
  1992. }
  1993. var valueOf = value.valueOf && value.valueOf()
  1994. if (valueOf != null && valueOf !== value) {
  1995. return Buffer.from(valueOf, encodingOrOffset, length)
  1996. }
  1997. var b = fromObject(value)
  1998. if (b) return b
  1999. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2000. typeof value[Symbol.toPrimitive] === 'function') {
  2001. return Buffer.from(
  2002. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2003. )
  2004. }
  2005. throw new TypeError(
  2006. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2007. 'or Array-like Object. Received type ' + (typeof value)
  2008. )
  2009. }
  2010. /**
  2011. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2012. * if value is a number.
  2013. * Buffer.from(str[, encoding])
  2014. * Buffer.from(array)
  2015. * Buffer.from(buffer)
  2016. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2017. **/
  2018. Buffer.from = function (value, encodingOrOffset, length) {
  2019. return from(value, encodingOrOffset, length)
  2020. }
  2021. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2022. // https://github.com/feross/buffer/pull/148
  2023. Buffer.prototype.__proto__ = Uint8Array.prototype
  2024. Buffer.__proto__ = Uint8Array
  2025. function assertSize (size) {
  2026. if (typeof size !== 'number') {
  2027. throw new TypeError('"size" argument must be of type number')
  2028. } else if (size < 0) {
  2029. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2030. }
  2031. }
  2032. function alloc (size, fill, encoding) {
  2033. assertSize(size)
  2034. if (size <= 0) {
  2035. return createBuffer(size)
  2036. }
  2037. if (fill !== undefined) {
  2038. // Only pay attention to encoding if it's a string. This
  2039. // prevents accidentally sending in a number that would
  2040. // be interpretted as a start offset.
  2041. return typeof encoding === 'string'
  2042. ? createBuffer(size).fill(fill, encoding)
  2043. : createBuffer(size).fill(fill)
  2044. }
  2045. return createBuffer(size)
  2046. }
  2047. /**
  2048. * Creates a new filled Buffer instance.
  2049. * alloc(size[, fill[, encoding]])
  2050. **/
  2051. Buffer.alloc = function (size, fill, encoding) {
  2052. return alloc(size, fill, encoding)
  2053. }
  2054. function allocUnsafe (size) {
  2055. assertSize(size)
  2056. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2057. }
  2058. /**
  2059. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2060. * */
  2061. Buffer.allocUnsafe = function (size) {
  2062. return allocUnsafe(size)
  2063. }
  2064. /**
  2065. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2066. */
  2067. Buffer.allocUnsafeSlow = function (size) {
  2068. return allocUnsafe(size)
  2069. }
  2070. function fromString (string, encoding) {
  2071. if (typeof encoding !== 'string' || encoding === '') {
  2072. encoding = 'utf8'
  2073. }
  2074. if (!Buffer.isEncoding(encoding)) {
  2075. throw new TypeError('Unknown encoding: ' + encoding)
  2076. }
  2077. var length = byteLength(string, encoding) | 0
  2078. var buf = createBuffer(length)
  2079. var actual = buf.write(string, encoding)
  2080. if (actual !== length) {
  2081. // Writing a hex string, for example, that contains invalid characters will
  2082. // cause everything after the first invalid character to be ignored. (e.g.
  2083. // 'abxxcd' will be treated as 'ab')
  2084. buf = buf.slice(0, actual)
  2085. }
  2086. return buf
  2087. }
  2088. function fromArrayLike (array) {
  2089. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2090. var buf = createBuffer(length)
  2091. for (var i = 0; i < length; i += 1) {
  2092. buf[i] = array[i] & 255
  2093. }
  2094. return buf
  2095. }
  2096. function fromArrayBuffer (array, byteOffset, length) {
  2097. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2098. throw new RangeError('"offset" is outside of buffer bounds')
  2099. }
  2100. if (array.byteLength < byteOffset + (length || 0)) {
  2101. throw new RangeError('"length" is outside of buffer bounds')
  2102. }
  2103. var buf
  2104. if (byteOffset === undefined && length === undefined) {
  2105. buf = new Uint8Array(array)
  2106. } else if (length === undefined) {
  2107. buf = new Uint8Array(array, byteOffset)
  2108. } else {
  2109. buf = new Uint8Array(array, byteOffset, length)
  2110. }
  2111. // Return an augmented `Uint8Array` instance
  2112. buf.__proto__ = Buffer.prototype
  2113. return buf
  2114. }
  2115. function fromObject (obj) {
  2116. if (Buffer.isBuffer(obj)) {
  2117. var len = checked(obj.length) | 0
  2118. var buf = createBuffer(len)
  2119. if (buf.length === 0) {
  2120. return buf
  2121. }
  2122. obj.copy(buf, 0, 0, len)
  2123. return buf
  2124. }
  2125. if (obj.length !== undefined) {
  2126. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2127. return createBuffer(0)
  2128. }
  2129. return fromArrayLike(obj)
  2130. }
  2131. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2132. return fromArrayLike(obj.data)
  2133. }
  2134. }
  2135. function checked (length) {
  2136. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2137. // length is NaN (which is otherwise coerced to zero.)
  2138. if (length >= K_MAX_LENGTH) {
  2139. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2140. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2141. }
  2142. return length | 0
  2143. }
  2144. function SlowBuffer (length) {
  2145. if (+length != length) { // eslint-disable-line eqeqeq
  2146. length = 0
  2147. }
  2148. return Buffer.alloc(+length)
  2149. }
  2150. Buffer.isBuffer = function isBuffer (b) {
  2151. return b != null && b._isBuffer === true &&
  2152. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2153. }
  2154. Buffer.compare = function compare (a, b) {
  2155. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2156. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2157. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2158. throw new TypeError(
  2159. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2160. )
  2161. }
  2162. if (a === b) return 0
  2163. var x = a.length
  2164. var y = b.length
  2165. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2166. if (a[i] !== b[i]) {
  2167. x = a[i]
  2168. y = b[i]
  2169. break
  2170. }
  2171. }
  2172. if (x < y) return -1
  2173. if (y < x) return 1
  2174. return 0
  2175. }
  2176. Buffer.isEncoding = function isEncoding (encoding) {
  2177. switch (String(encoding).toLowerCase()) {
  2178. case 'hex':
  2179. case 'utf8':
  2180. case 'utf-8':
  2181. case 'ascii':
  2182. case 'latin1':
  2183. case 'binary':
  2184. case 'base64':
  2185. case 'ucs2':
  2186. case 'ucs-2':
  2187. case 'utf16le':
  2188. case 'utf-16le':
  2189. return true
  2190. default:
  2191. return false
  2192. }
  2193. }
  2194. Buffer.concat = function concat (list, length) {
  2195. if (!Array.isArray(list)) {
  2196. throw new TypeError('"list" argument must be an Array of Buffers')
  2197. }
  2198. if (list.length === 0) {
  2199. return Buffer.alloc(0)
  2200. }
  2201. var i
  2202. if (length === undefined) {
  2203. length = 0
  2204. for (i = 0; i < list.length; ++i) {
  2205. length += list[i].length
  2206. }
  2207. }
  2208. var buffer = Buffer.allocUnsafe(length)
  2209. var pos = 0
  2210. for (i = 0; i < list.length; ++i) {
  2211. var buf = list[i]
  2212. if (isInstance(buf, Uint8Array)) {
  2213. buf = Buffer.from(buf)
  2214. }
  2215. if (!Buffer.isBuffer(buf)) {
  2216. throw new TypeError('"list" argument must be an Array of Buffers')
  2217. }
  2218. buf.copy(buffer, pos)
  2219. pos += buf.length
  2220. }
  2221. return buffer
  2222. }
  2223. function byteLength (string, encoding) {
  2224. if (Buffer.isBuffer(string)) {
  2225. return string.length
  2226. }
  2227. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2228. return string.byteLength
  2229. }
  2230. if (typeof string !== 'string') {
  2231. throw new TypeError(
  2232. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2233. 'Received type ' + typeof string
  2234. )
  2235. }
  2236. var len = string.length
  2237. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2238. if (!mustMatch && len === 0) return 0
  2239. // Use a for loop to avoid recursion
  2240. var loweredCase = false
  2241. for (;;) {
  2242. switch (encoding) {
  2243. case 'ascii':
  2244. case 'latin1':
  2245. case 'binary':
  2246. return len
  2247. case 'utf8':
  2248. case 'utf-8':
  2249. return utf8ToBytes(string).length
  2250. case 'ucs2':
  2251. case 'ucs-2':
  2252. case 'utf16le':
  2253. case 'utf-16le':
  2254. return len * 2
  2255. case 'hex':
  2256. return len >>> 1
  2257. case 'base64':
  2258. return base64ToBytes(string).length
  2259. default:
  2260. if (loweredCase) {
  2261. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2262. }
  2263. encoding = ('' + encoding).toLowerCase()
  2264. loweredCase = true
  2265. }
  2266. }
  2267. }
  2268. Buffer.byteLength = byteLength
  2269. function slowToString (encoding, start, end) {
  2270. var loweredCase = false
  2271. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2272. // property of a typed array.
  2273. // This behaves neither like String nor Uint8Array in that we set start/end
  2274. // to their upper/lower bounds if the value passed is out of range.
  2275. // undefined is handled specially as per ECMA-262 6th Edition,
  2276. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2277. if (start === undefined || start < 0) {
  2278. start = 0
  2279. }
  2280. // Return early if start > this.length. Done here to prevent potential uint32
  2281. // coercion fail below.
  2282. if (start > this.length) {
  2283. return ''
  2284. }
  2285. if (end === undefined || end > this.length) {
  2286. end = this.length
  2287. }
  2288. if (end <= 0) {
  2289. return ''
  2290. }
  2291. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2292. end >>>= 0
  2293. start >>>= 0
  2294. if (end <= start) {
  2295. return ''
  2296. }
  2297. if (!encoding) encoding = 'utf8'
  2298. while (true) {
  2299. switch (encoding) {
  2300. case 'hex':
  2301. return hexSlice(this, start, end)
  2302. case 'utf8':
  2303. case 'utf-8':
  2304. return utf8Slice(this, start, end)
  2305. case 'ascii':
  2306. return asciiSlice(this, start, end)
  2307. case 'latin1':
  2308. case 'binary':
  2309. return latin1Slice(this, start, end)
  2310. case 'base64':
  2311. return base64Slice(this, start, end)
  2312. case 'ucs2':
  2313. case 'ucs-2':
  2314. case 'utf16le':
  2315. case 'utf-16le':
  2316. return utf16leSlice(this, start, end)
  2317. default:
  2318. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2319. encoding = (encoding + '').toLowerCase()
  2320. loweredCase = true
  2321. }
  2322. }
  2323. }
  2324. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2325. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2326. // reliably in a browserify context because there could be multiple different
  2327. // copies of the 'buffer' package in use. This method works even for Buffer
  2328. // instances that were created from another copy of the `buffer` package.
  2329. // See: https://github.com/feross/buffer/issues/154
  2330. Buffer.prototype._isBuffer = true
  2331. function swap (b, n, m) {
  2332. var i = b[n]
  2333. b[n] = b[m]
  2334. b[m] = i
  2335. }
  2336. Buffer.prototype.swap16 = function swap16 () {
  2337. var len = this.length
  2338. if (len % 2 !== 0) {
  2339. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2340. }
  2341. for (var i = 0; i < len; i += 2) {
  2342. swap(this, i, i + 1)
  2343. }
  2344. return this
  2345. }
  2346. Buffer.prototype.swap32 = function swap32 () {
  2347. var len = this.length
  2348. if (len % 4 !== 0) {
  2349. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2350. }
  2351. for (var i = 0; i < len; i += 4) {
  2352. swap(this, i, i + 3)
  2353. swap(this, i + 1, i + 2)
  2354. }
  2355. return this
  2356. }
  2357. Buffer.prototype.swap64 = function swap64 () {
  2358. var len = this.length
  2359. if (len % 8 !== 0) {
  2360. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2361. }
  2362. for (var i = 0; i < len; i += 8) {
  2363. swap(this, i, i + 7)
  2364. swap(this, i + 1, i + 6)
  2365. swap(this, i + 2, i + 5)
  2366. swap(this, i + 3, i + 4)
  2367. }
  2368. return this
  2369. }
  2370. Buffer.prototype.toString = function toString () {
  2371. var length = this.length
  2372. if (length === 0) return ''
  2373. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2374. return slowToString.apply(this, arguments)
  2375. }
  2376. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2377. Buffer.prototype.equals = function equals (b) {
  2378. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2379. if (this === b) return true
  2380. return Buffer.compare(this, b) === 0
  2381. }
  2382. Buffer.prototype.inspect = function inspect () {
  2383. var str = ''
  2384. var max = exports.INSPECT_MAX_BYTES
  2385. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2386. if (this.length > max) str += ' ... '
  2387. return '<Buffer ' + str + '>'
  2388. }
  2389. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2390. if (isInstance(target, Uint8Array)) {
  2391. target = Buffer.from(target, target.offset, target.byteLength)
  2392. }
  2393. if (!Buffer.isBuffer(target)) {
  2394. throw new TypeError(
  2395. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2396. 'Received type ' + (typeof target)
  2397. )
  2398. }
  2399. if (start === undefined) {
  2400. start = 0
  2401. }
  2402. if (end === undefined) {
  2403. end = target ? target.length : 0
  2404. }
  2405. if (thisStart === undefined) {
  2406. thisStart = 0
  2407. }
  2408. if (thisEnd === undefined) {
  2409. thisEnd = this.length
  2410. }
  2411. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2412. throw new RangeError('out of range index')
  2413. }
  2414. if (thisStart >= thisEnd && start >= end) {
  2415. return 0
  2416. }
  2417. if (thisStart >= thisEnd) {
  2418. return -1
  2419. }
  2420. if (start >= end) {
  2421. return 1
  2422. }
  2423. start >>>= 0
  2424. end >>>= 0
  2425. thisStart >>>= 0
  2426. thisEnd >>>= 0
  2427. if (this === target) return 0
  2428. var x = thisEnd - thisStart
  2429. var y = end - start
  2430. var len = Math.min(x, y)
  2431. var thisCopy = this.slice(thisStart, thisEnd)
  2432. var targetCopy = target.slice(start, end)
  2433. for (var i = 0; i < len; ++i) {
  2434. if (thisCopy[i] !== targetCopy[i]) {
  2435. x = thisCopy[i]
  2436. y = targetCopy[i]
  2437. break
  2438. }
  2439. }
  2440. if (x < y) return -1
  2441. if (y < x) return 1
  2442. return 0
  2443. }
  2444. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2445. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2446. //
  2447. // Arguments:
  2448. // - buffer - a Buffer to search
  2449. // - val - a string, Buffer, or number
  2450. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2451. // - encoding - an optional encoding, relevant is val is a string
  2452. // - dir - true for indexOf, false for lastIndexOf
  2453. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2454. // Empty buffer means no match
  2455. if (buffer.length === 0) return -1
  2456. // Normalize byteOffset
  2457. if (typeof byteOffset === 'string') {
  2458. encoding = byteOffset
  2459. byteOffset = 0
  2460. } else if (byteOffset > 0x7fffffff) {
  2461. byteOffset = 0x7fffffff
  2462. } else if (byteOffset < -0x80000000) {
  2463. byteOffset = -0x80000000
  2464. }
  2465. byteOffset = +byteOffset // Coerce to Number.
  2466. if (numberIsNaN(byteOffset)) {
  2467. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2468. byteOffset = dir ? 0 : (buffer.length - 1)
  2469. }
  2470. // Normalize byteOffset: negative offsets start from the end of the buffer
  2471. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2472. if (byteOffset >= buffer.length) {
  2473. if (dir) return -1
  2474. else byteOffset = buffer.length - 1
  2475. } else if (byteOffset < 0) {
  2476. if (dir) byteOffset = 0
  2477. else return -1
  2478. }
  2479. // Normalize val
  2480. if (typeof val === 'string') {
  2481. val = Buffer.from(val, encoding)
  2482. }
  2483. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2484. if (Buffer.isBuffer(val)) {
  2485. // Special case: looking for empty string/buffer always fails
  2486. if (val.length === 0) {
  2487. return -1
  2488. }
  2489. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2490. } else if (typeof val === 'number') {
  2491. val = val & 0xFF // Search for a byte value [0-255]
  2492. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2493. if (dir) {
  2494. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2495. } else {
  2496. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2497. }
  2498. }
  2499. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2500. }
  2501. throw new TypeError('val must be string, number or Buffer')
  2502. }
  2503. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2504. var indexSize = 1
  2505. var arrLength = arr.length
  2506. var valLength = val.length
  2507. if (encoding !== undefined) {
  2508. encoding = String(encoding).toLowerCase()
  2509. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2510. encoding === 'utf16le' || encoding === 'utf-16le') {
  2511. if (arr.length < 2 || val.length < 2) {
  2512. return -1
  2513. }
  2514. indexSize = 2
  2515. arrLength /= 2
  2516. valLength /= 2
  2517. byteOffset /= 2
  2518. }
  2519. }
  2520. function read (buf, i) {
  2521. if (indexSize === 1) {
  2522. return buf[i]
  2523. } else {
  2524. return buf.readUInt16BE(i * indexSize)
  2525. }
  2526. }
  2527. var i
  2528. if (dir) {
  2529. var foundIndex = -1
  2530. for (i = byteOffset; i < arrLength; i++) {
  2531. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2532. if (foundIndex === -1) foundIndex = i
  2533. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2534. } else {
  2535. if (foundIndex !== -1) i -= i - foundIndex
  2536. foundIndex = -1
  2537. }
  2538. }
  2539. } else {
  2540. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2541. for (i = byteOffset; i >= 0; i--) {
  2542. var found = true
  2543. for (var j = 0; j < valLength; j++) {
  2544. if (read(arr, i + j) !== read(val, j)) {
  2545. found = false
  2546. break
  2547. }
  2548. }
  2549. if (found) return i
  2550. }
  2551. }
  2552. return -1
  2553. }
  2554. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2555. return this.indexOf(val, byteOffset, encoding) !== -1
  2556. }
  2557. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2558. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2559. }
  2560. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2561. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2562. }
  2563. function hexWrite (buf, string, offset, length) {
  2564. offset = Number(offset) || 0
  2565. var remaining = buf.length - offset
  2566. if (!length) {
  2567. length = remaining
  2568. } else {
  2569. length = Number(length)
  2570. if (length > remaining) {
  2571. length = remaining
  2572. }
  2573. }
  2574. var strLen = string.length
  2575. if (length > strLen / 2) {
  2576. length = strLen / 2
  2577. }
  2578. for (var i = 0; i < length; ++i) {
  2579. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2580. if (numberIsNaN(parsed)) return i
  2581. buf[offset + i] = parsed
  2582. }
  2583. return i
  2584. }
  2585. function utf8Write (buf, string, offset, length) {
  2586. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2587. }
  2588. function asciiWrite (buf, string, offset, length) {
  2589. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2590. }
  2591. function latin1Write (buf, string, offset, length) {
  2592. return asciiWrite(buf, string, offset, length)
  2593. }
  2594. function base64Write (buf, string, offset, length) {
  2595. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2596. }
  2597. function ucs2Write (buf, string, offset, length) {
  2598. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2599. }
  2600. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2601. // Buffer#write(string)
  2602. if (offset === undefined) {
  2603. encoding = 'utf8'
  2604. length = this.length
  2605. offset = 0
  2606. // Buffer#write(string, encoding)
  2607. } else if (length === undefined && typeof offset === 'string') {
  2608. encoding = offset
  2609. length = this.length
  2610. offset = 0
  2611. // Buffer#write(string, offset[, length][, encoding])
  2612. } else if (isFinite(offset)) {
  2613. offset = offset >>> 0
  2614. if (isFinite(length)) {
  2615. length = length >>> 0
  2616. if (encoding === undefined) encoding = 'utf8'
  2617. } else {
  2618. encoding = length
  2619. length = undefined
  2620. }
  2621. } else {
  2622. throw new Error(
  2623. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2624. )
  2625. }
  2626. var remaining = this.length - offset
  2627. if (length === undefined || length > remaining) length = remaining
  2628. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2629. throw new RangeError('Attempt to write outside buffer bounds')
  2630. }
  2631. if (!encoding) encoding = 'utf8'
  2632. var loweredCase = false
  2633. for (;;) {
  2634. switch (encoding) {
  2635. case 'hex':
  2636. return hexWrite(this, string, offset, length)
  2637. case 'utf8':
  2638. case 'utf-8':
  2639. return utf8Write(this, string, offset, length)
  2640. case 'ascii':
  2641. return asciiWrite(this, string, offset, length)
  2642. case 'latin1':
  2643. case 'binary':
  2644. return latin1Write(this, string, offset, length)
  2645. case 'base64':
  2646. // Warning: maxLength not taken into account in base64Write
  2647. return base64Write(this, string, offset, length)
  2648. case 'ucs2':
  2649. case 'ucs-2':
  2650. case 'utf16le':
  2651. case 'utf-16le':
  2652. return ucs2Write(this, string, offset, length)
  2653. default:
  2654. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2655. encoding = ('' + encoding).toLowerCase()
  2656. loweredCase = true
  2657. }
  2658. }
  2659. }
  2660. Buffer.prototype.toJSON = function toJSON () {
  2661. return {
  2662. type: 'Buffer',
  2663. data: Array.prototype.slice.call(this._arr || this, 0)
  2664. }
  2665. }
  2666. function base64Slice (buf, start, end) {
  2667. if (start === 0 && end === buf.length) {
  2668. return base64.fromByteArray(buf)
  2669. } else {
  2670. return base64.fromByteArray(buf.slice(start, end))
  2671. }
  2672. }
  2673. function utf8Slice (buf, start, end) {
  2674. end = Math.min(buf.length, end)
  2675. var res = []
  2676. var i = start
  2677. while (i < end) {
  2678. var firstByte = buf[i]
  2679. var codePoint = null
  2680. var bytesPerSequence = (firstByte > 0xEF) ? 4
  2681. : (firstByte > 0xDF) ? 3
  2682. : (firstByte > 0xBF) ? 2
  2683. : 1
  2684. if (i + bytesPerSequence <= end) {
  2685. var secondByte, thirdByte, fourthByte, tempCodePoint
  2686. switch (bytesPerSequence) {
  2687. case 1:
  2688. if (firstByte < 0x80) {
  2689. codePoint = firstByte
  2690. }
  2691. break
  2692. case 2:
  2693. secondByte = buf[i + 1]
  2694. if ((secondByte & 0xC0) === 0x80) {
  2695. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  2696. if (tempCodePoint > 0x7F) {
  2697. codePoint = tempCodePoint
  2698. }
  2699. }
  2700. break
  2701. case 3:
  2702. secondByte = buf[i + 1]
  2703. thirdByte = buf[i + 2]
  2704. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  2705. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  2706. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  2707. codePoint = tempCodePoint
  2708. }
  2709. }
  2710. break
  2711. case 4:
  2712. secondByte = buf[i + 1]
  2713. thirdByte = buf[i + 2]
  2714. fourthByte = buf[i + 3]
  2715. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  2716. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  2717. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  2718. codePoint = tempCodePoint
  2719. }
  2720. }
  2721. }
  2722. }
  2723. if (codePoint === null) {
  2724. // we did not generate a valid codePoint so insert a
  2725. // replacement char (U+FFFD) and advance only 1 byte
  2726. codePoint = 0xFFFD
  2727. bytesPerSequence = 1
  2728. } else if (codePoint > 0xFFFF) {
  2729. // encode to utf16 (surrogate pair dance)
  2730. codePoint -= 0x10000
  2731. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  2732. codePoint = 0xDC00 | codePoint & 0x3FF
  2733. }
  2734. res.push(codePoint)
  2735. i += bytesPerSequence
  2736. }
  2737. return decodeCodePointsArray(res)
  2738. }
  2739. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  2740. // the lowest limit is Chrome, with 0x10000 args.
  2741. // We go 1 magnitude less, for safety
  2742. var MAX_ARGUMENTS_LENGTH = 0x1000
  2743. function decodeCodePointsArray (codePoints) {
  2744. var len = codePoints.length
  2745. if (len <= MAX_ARGUMENTS_LENGTH) {
  2746. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  2747. }
  2748. // Decode in chunks to avoid "call stack size exceeded".
  2749. var res = ''
  2750. var i = 0
  2751. while (i < len) {
  2752. res += String.fromCharCode.apply(
  2753. String,
  2754. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  2755. )
  2756. }
  2757. return res
  2758. }
  2759. function asciiSlice (buf, start, end) {
  2760. var ret = ''
  2761. end = Math.min(buf.length, end)
  2762. for (var i = start; i < end; ++i) {
  2763. ret += String.fromCharCode(buf[i] & 0x7F)
  2764. }
  2765. return ret
  2766. }
  2767. function latin1Slice (buf, start, end) {
  2768. var ret = ''
  2769. end = Math.min(buf.length, end)
  2770. for (var i = start; i < end; ++i) {
  2771. ret += String.fromCharCode(buf[i])
  2772. }
  2773. return ret
  2774. }
  2775. function hexSlice (buf, start, end) {
  2776. var len = buf.length
  2777. if (!start || start < 0) start = 0
  2778. if (!end || end < 0 || end > len) end = len
  2779. var out = ''
  2780. for (var i = start; i < end; ++i) {
  2781. out += toHex(buf[i])
  2782. }
  2783. return out
  2784. }
  2785. function utf16leSlice (buf, start, end) {
  2786. var bytes = buf.slice(start, end)
  2787. var res = ''
  2788. for (var i = 0; i < bytes.length; i += 2) {
  2789. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  2790. }
  2791. return res
  2792. }
  2793. Buffer.prototype.slice = function slice (start, end) {
  2794. var len = this.length
  2795. start = ~~start
  2796. end = end === undefined ? len : ~~end
  2797. if (start < 0) {
  2798. start += len
  2799. if (start < 0) start = 0
  2800. } else if (start > len) {
  2801. start = len
  2802. }
  2803. if (end < 0) {
  2804. end += len
  2805. if (end < 0) end = 0
  2806. } else if (end > len) {
  2807. end = len
  2808. }
  2809. if (end < start) end = start
  2810. var newBuf = this.subarray(start, end)
  2811. // Return an augmented `Uint8Array` instance
  2812. newBuf.__proto__ = Buffer.prototype
  2813. return newBuf
  2814. }
  2815. /*
  2816. * Need to make sure that buffer isn't trying to write out of bounds.
  2817. */
  2818. function checkOffset (offset, ext, length) {
  2819. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  2820. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  2821. }
  2822. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  2823. offset = offset >>> 0
  2824. byteLength = byteLength >>> 0
  2825. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2826. var val = this[offset]
  2827. var mul = 1
  2828. var i = 0
  2829. while (++i < byteLength && (mul *= 0x100)) {
  2830. val += this[offset + i] * mul
  2831. }
  2832. return val
  2833. }
  2834. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  2835. offset = offset >>> 0
  2836. byteLength = byteLength >>> 0
  2837. if (!noAssert) {
  2838. checkOffset(offset, byteLength, this.length)
  2839. }
  2840. var val = this[offset + --byteLength]
  2841. var mul = 1
  2842. while (byteLength > 0 && (mul *= 0x100)) {
  2843. val += this[offset + --byteLength] * mul
  2844. }
  2845. return val
  2846. }
  2847. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  2848. offset = offset >>> 0
  2849. if (!noAssert) checkOffset(offset, 1, this.length)
  2850. return this[offset]
  2851. }
  2852. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  2853. offset = offset >>> 0
  2854. if (!noAssert) checkOffset(offset, 2, this.length)
  2855. return this[offset] | (this[offset + 1] << 8)
  2856. }
  2857. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  2858. offset = offset >>> 0
  2859. if (!noAssert) checkOffset(offset, 2, this.length)
  2860. return (this[offset] << 8) | this[offset + 1]
  2861. }
  2862. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  2863. offset = offset >>> 0
  2864. if (!noAssert) checkOffset(offset, 4, this.length)
  2865. return ((this[offset]) |
  2866. (this[offset + 1] << 8) |
  2867. (this[offset + 2] << 16)) +
  2868. (this[offset + 3] * 0x1000000)
  2869. }
  2870. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  2871. offset = offset >>> 0
  2872. if (!noAssert) checkOffset(offset, 4, this.length)
  2873. return (this[offset] * 0x1000000) +
  2874. ((this[offset + 1] << 16) |
  2875. (this[offset + 2] << 8) |
  2876. this[offset + 3])
  2877. }
  2878. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  2879. offset = offset >>> 0
  2880. byteLength = byteLength >>> 0
  2881. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2882. var val = this[offset]
  2883. var mul = 1
  2884. var i = 0
  2885. while (++i < byteLength && (mul *= 0x100)) {
  2886. val += this[offset + i] * mul
  2887. }
  2888. mul *= 0x80
  2889. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  2890. return val
  2891. }
  2892. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  2893. offset = offset >>> 0
  2894. byteLength = byteLength >>> 0
  2895. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2896. var i = byteLength
  2897. var mul = 1
  2898. var val = this[offset + --i]
  2899. while (i > 0 && (mul *= 0x100)) {
  2900. val += this[offset + --i] * mul
  2901. }
  2902. mul *= 0x80
  2903. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  2904. return val
  2905. }
  2906. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  2907. offset = offset >>> 0
  2908. if (!noAssert) checkOffset(offset, 1, this.length)
  2909. if (!(this[offset] & 0x80)) return (this[offset])
  2910. return ((0xff - this[offset] + 1) * -1)
  2911. }
  2912. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  2913. offset = offset >>> 0
  2914. if (!noAssert) checkOffset(offset, 2, this.length)
  2915. var val = this[offset] | (this[offset + 1] << 8)
  2916. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2917. }
  2918. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  2919. offset = offset >>> 0
  2920. if (!noAssert) checkOffset(offset, 2, this.length)
  2921. var val = this[offset + 1] | (this[offset] << 8)
  2922. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2923. }
  2924. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  2925. offset = offset >>> 0
  2926. if (!noAssert) checkOffset(offset, 4, this.length)
  2927. return (this[offset]) |
  2928. (this[offset + 1] << 8) |
  2929. (this[offset + 2] << 16) |
  2930. (this[offset + 3] << 24)
  2931. }
  2932. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  2933. offset = offset >>> 0
  2934. if (!noAssert) checkOffset(offset, 4, this.length)
  2935. return (this[offset] << 24) |
  2936. (this[offset + 1] << 16) |
  2937. (this[offset + 2] << 8) |
  2938. (this[offset + 3])
  2939. }
  2940. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  2941. offset = offset >>> 0
  2942. if (!noAssert) checkOffset(offset, 4, this.length)
  2943. return ieee754.read(this, offset, true, 23, 4)
  2944. }
  2945. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  2946. offset = offset >>> 0
  2947. if (!noAssert) checkOffset(offset, 4, this.length)
  2948. return ieee754.read(this, offset, false, 23, 4)
  2949. }
  2950. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  2951. offset = offset >>> 0
  2952. if (!noAssert) checkOffset(offset, 8, this.length)
  2953. return ieee754.read(this, offset, true, 52, 8)
  2954. }
  2955. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  2956. offset = offset >>> 0
  2957. if (!noAssert) checkOffset(offset, 8, this.length)
  2958. return ieee754.read(this, offset, false, 52, 8)
  2959. }
  2960. function checkInt (buf, value, offset, ext, max, min) {
  2961. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  2962. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  2963. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2964. }
  2965. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  2966. value = +value
  2967. offset = offset >>> 0
  2968. byteLength = byteLength >>> 0
  2969. if (!noAssert) {
  2970. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  2971. checkInt(this, value, offset, byteLength, maxBytes, 0)
  2972. }
  2973. var mul = 1
  2974. var i = 0
  2975. this[offset] = value & 0xFF
  2976. while (++i < byteLength && (mul *= 0x100)) {
  2977. this[offset + i] = (value / mul) & 0xFF
  2978. }
  2979. return offset + byteLength
  2980. }
  2981. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  2982. value = +value
  2983. offset = offset >>> 0
  2984. byteLength = byteLength >>> 0
  2985. if (!noAssert) {
  2986. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  2987. checkInt(this, value, offset, byteLength, maxBytes, 0)
  2988. }
  2989. var i = byteLength - 1
  2990. var mul = 1
  2991. this[offset + i] = value & 0xFF
  2992. while (--i >= 0 && (mul *= 0x100)) {
  2993. this[offset + i] = (value / mul) & 0xFF
  2994. }
  2995. return offset + byteLength
  2996. }
  2997. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  2998. value = +value
  2999. offset = offset >>> 0
  3000. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3001. this[offset] = (value & 0xff)
  3002. return offset + 1
  3003. }
  3004. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3005. value = +value
  3006. offset = offset >>> 0
  3007. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3008. this[offset] = (value & 0xff)
  3009. this[offset + 1] = (value >>> 8)
  3010. return offset + 2
  3011. }
  3012. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3013. value = +value
  3014. offset = offset >>> 0
  3015. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3016. this[offset] = (value >>> 8)
  3017. this[offset + 1] = (value & 0xff)
  3018. return offset + 2
  3019. }
  3020. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3021. value = +value
  3022. offset = offset >>> 0
  3023. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3024. this[offset + 3] = (value >>> 24)
  3025. this[offset + 2] = (value >>> 16)
  3026. this[offset + 1] = (value >>> 8)
  3027. this[offset] = (value & 0xff)
  3028. return offset + 4
  3029. }
  3030. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3031. value = +value
  3032. offset = offset >>> 0
  3033. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3034. this[offset] = (value >>> 24)
  3035. this[offset + 1] = (value >>> 16)
  3036. this[offset + 2] = (value >>> 8)
  3037. this[offset + 3] = (value & 0xff)
  3038. return offset + 4
  3039. }
  3040. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3041. value = +value
  3042. offset = offset >>> 0
  3043. if (!noAssert) {
  3044. var limit = Math.pow(2, (8 * byteLength) - 1)
  3045. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3046. }
  3047. var i = 0
  3048. var mul = 1
  3049. var sub = 0
  3050. this[offset] = value & 0xFF
  3051. while (++i < byteLength && (mul *= 0x100)) {
  3052. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3053. sub = 1
  3054. }
  3055. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3056. }
  3057. return offset + byteLength
  3058. }
  3059. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3060. value = +value
  3061. offset = offset >>> 0
  3062. if (!noAssert) {
  3063. var limit = Math.pow(2, (8 * byteLength) - 1)
  3064. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3065. }
  3066. var i = byteLength - 1
  3067. var mul = 1
  3068. var sub = 0
  3069. this[offset + i] = value & 0xFF
  3070. while (--i >= 0 && (mul *= 0x100)) {
  3071. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3072. sub = 1
  3073. }
  3074. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3075. }
  3076. return offset + byteLength
  3077. }
  3078. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3079. value = +value
  3080. offset = offset >>> 0
  3081. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3082. if (value < 0) value = 0xff + value + 1
  3083. this[offset] = (value & 0xff)
  3084. return offset + 1
  3085. }
  3086. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3087. value = +value
  3088. offset = offset >>> 0
  3089. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3090. this[offset] = (value & 0xff)
  3091. this[offset + 1] = (value >>> 8)
  3092. return offset + 2
  3093. }
  3094. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3095. value = +value
  3096. offset = offset >>> 0
  3097. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3098. this[offset] = (value >>> 8)
  3099. this[offset + 1] = (value & 0xff)
  3100. return offset + 2
  3101. }
  3102. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3103. value = +value
  3104. offset = offset >>> 0
  3105. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3106. this[offset] = (value & 0xff)
  3107. this[offset + 1] = (value >>> 8)
  3108. this[offset + 2] = (value >>> 16)
  3109. this[offset + 3] = (value >>> 24)
  3110. return offset + 4
  3111. }
  3112. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3113. value = +value
  3114. offset = offset >>> 0
  3115. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3116. if (value < 0) value = 0xffffffff + value + 1
  3117. this[offset] = (value >>> 24)
  3118. this[offset + 1] = (value >>> 16)
  3119. this[offset + 2] = (value >>> 8)
  3120. this[offset + 3] = (value & 0xff)
  3121. return offset + 4
  3122. }
  3123. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3124. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3125. if (offset < 0) throw new RangeError('Index out of range')
  3126. }
  3127. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3128. value = +value
  3129. offset = offset >>> 0
  3130. if (!noAssert) {
  3131. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3132. }
  3133. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3134. return offset + 4
  3135. }
  3136. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3137. return writeFloat(this, value, offset, true, noAssert)
  3138. }
  3139. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3140. return writeFloat(this, value, offset, false, noAssert)
  3141. }
  3142. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3143. value = +value
  3144. offset = offset >>> 0
  3145. if (!noAssert) {
  3146. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3147. }
  3148. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3149. return offset + 8
  3150. }
  3151. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3152. return writeDouble(this, value, offset, true, noAssert)
  3153. }
  3154. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3155. return writeDouble(this, value, offset, false, noAssert)
  3156. }
  3157. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3158. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3159. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3160. if (!start) start = 0
  3161. if (!end && end !== 0) end = this.length
  3162. if (targetStart >= target.length) targetStart = target.length
  3163. if (!targetStart) targetStart = 0
  3164. if (end > 0 && end < start) end = start
  3165. // Copy 0 bytes; we're done
  3166. if (end === start) return 0
  3167. if (target.length === 0 || this.length === 0) return 0
  3168. // Fatal error conditions
  3169. if (targetStart < 0) {
  3170. throw new RangeError('targetStart out of bounds')
  3171. }
  3172. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3173. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3174. // Are we oob?
  3175. if (end > this.length) end = this.length
  3176. if (target.length - targetStart < end - start) {
  3177. end = target.length - targetStart + start
  3178. }
  3179. var len = end - start
  3180. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3181. // Use built-in when available, missing from IE11
  3182. this.copyWithin(targetStart, start, end)
  3183. } else if (this === target && start < targetStart && targetStart < end) {
  3184. // descending copy from end
  3185. for (var i = len - 1; i >= 0; --i) {
  3186. target[i + targetStart] = this[i + start]
  3187. }
  3188. } else {
  3189. Uint8Array.prototype.set.call(
  3190. target,
  3191. this.subarray(start, end),
  3192. targetStart
  3193. )
  3194. }
  3195. return len
  3196. }
  3197. // Usage:
  3198. // buffer.fill(number[, offset[, end]])
  3199. // buffer.fill(buffer[, offset[, end]])
  3200. // buffer.fill(string[, offset[, end]][, encoding])
  3201. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3202. // Handle string cases:
  3203. if (typeof val === 'string') {
  3204. if (typeof start === 'string') {
  3205. encoding = start
  3206. start = 0
  3207. end = this.length
  3208. } else if (typeof end === 'string') {
  3209. encoding = end
  3210. end = this.length
  3211. }
  3212. if (encoding !== undefined && typeof encoding !== 'string') {
  3213. throw new TypeError('encoding must be a string')
  3214. }
  3215. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3216. throw new TypeError('Unknown encoding: ' + encoding)
  3217. }
  3218. if (val.length === 1) {
  3219. var code = val.charCodeAt(0)
  3220. if ((encoding === 'utf8' && code < 128) ||
  3221. encoding === 'latin1') {
  3222. // Fast path: If `val` fits into a single byte, use that numeric value.
  3223. val = code
  3224. }
  3225. }
  3226. } else if (typeof val === 'number') {
  3227. val = val & 255
  3228. }
  3229. // Invalid ranges are not set to a default, so can range check early.
  3230. if (start < 0 || this.length < start || this.length < end) {
  3231. throw new RangeError('Out of range index')
  3232. }
  3233. if (end <= start) {
  3234. return this
  3235. }
  3236. start = start >>> 0
  3237. end = end === undefined ? this.length : end >>> 0
  3238. if (!val) val = 0
  3239. var i
  3240. if (typeof val === 'number') {
  3241. for (i = start; i < end; ++i) {
  3242. this[i] = val
  3243. }
  3244. } else {
  3245. var bytes = Buffer.isBuffer(val)
  3246. ? val
  3247. : Buffer.from(val, encoding)
  3248. var len = bytes.length
  3249. if (len === 0) {
  3250. throw new TypeError('The value "' + val +
  3251. '" is invalid for argument "value"')
  3252. }
  3253. for (i = 0; i < end - start; ++i) {
  3254. this[i + start] = bytes[i % len]
  3255. }
  3256. }
  3257. return this
  3258. }
  3259. // HELPER FUNCTIONS
  3260. // ================
  3261. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3262. function base64clean (str) {
  3263. // Node takes equal signs as end of the Base64 encoding
  3264. str = str.split('=')[0]
  3265. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3266. str = str.trim().replace(INVALID_BASE64_RE, '')
  3267. // Node converts strings with length < 2 to ''
  3268. if (str.length < 2) return ''
  3269. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3270. while (str.length % 4 !== 0) {
  3271. str = str + '='
  3272. }
  3273. return str
  3274. }
  3275. function toHex (n) {
  3276. if (n < 16) return '0' + n.toString(16)
  3277. return n.toString(16)
  3278. }
  3279. function utf8ToBytes (string, units) {
  3280. units = units || Infinity
  3281. var codePoint
  3282. var length = string.length
  3283. var leadSurrogate = null
  3284. var bytes = []
  3285. for (var i = 0; i < length; ++i) {
  3286. codePoint = string.charCodeAt(i)
  3287. // is surrogate component
  3288. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3289. // last char was a lead
  3290. if (!leadSurrogate) {
  3291. // no lead yet
  3292. if (codePoint > 0xDBFF) {
  3293. // unexpected trail
  3294. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3295. continue
  3296. } else if (i + 1 === length) {
  3297. // unpaired lead
  3298. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3299. continue
  3300. }
  3301. // valid lead
  3302. leadSurrogate = codePoint
  3303. continue
  3304. }
  3305. // 2 leads in a row
  3306. if (codePoint < 0xDC00) {
  3307. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3308. leadSurrogate = codePoint
  3309. continue
  3310. }
  3311. // valid surrogate pair
  3312. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3313. } else if (leadSurrogate) {
  3314. // valid bmp char, but last char was a lead
  3315. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3316. }
  3317. leadSurrogate = null
  3318. // encode utf8
  3319. if (codePoint < 0x80) {
  3320. if ((units -= 1) < 0) break
  3321. bytes.push(codePoint)
  3322. } else if (codePoint < 0x800) {
  3323. if ((units -= 2) < 0) break
  3324. bytes.push(
  3325. codePoint >> 0x6 | 0xC0,
  3326. codePoint & 0x3F | 0x80
  3327. )
  3328. } else if (codePoint < 0x10000) {
  3329. if ((units -= 3) < 0) break
  3330. bytes.push(
  3331. codePoint >> 0xC | 0xE0,
  3332. codePoint >> 0x6 & 0x3F | 0x80,
  3333. codePoint & 0x3F | 0x80
  3334. )
  3335. } else if (codePoint < 0x110000) {
  3336. if ((units -= 4) < 0) break
  3337. bytes.push(
  3338. codePoint >> 0x12 | 0xF0,
  3339. codePoint >> 0xC & 0x3F | 0x80,
  3340. codePoint >> 0x6 & 0x3F | 0x80,
  3341. codePoint & 0x3F | 0x80
  3342. )
  3343. } else {
  3344. throw new Error('Invalid code point')
  3345. }
  3346. }
  3347. return bytes
  3348. }
  3349. function asciiToBytes (str) {
  3350. var byteArray = []
  3351. for (var i = 0; i < str.length; ++i) {
  3352. // Node's code seems to be doing this and not & 0x7F..
  3353. byteArray.push(str.charCodeAt(i) & 0xFF)
  3354. }
  3355. return byteArray
  3356. }
  3357. function utf16leToBytes (str, units) {
  3358. var c, hi, lo
  3359. var byteArray = []
  3360. for (var i = 0; i < str.length; ++i) {
  3361. if ((units -= 2) < 0) break
  3362. c = str.charCodeAt(i)
  3363. hi = c >> 8
  3364. lo = c % 256
  3365. byteArray.push(lo)
  3366. byteArray.push(hi)
  3367. }
  3368. return byteArray
  3369. }
  3370. function base64ToBytes (str) {
  3371. return base64.toByteArray(base64clean(str))
  3372. }
  3373. function blitBuffer (src, dst, offset, length) {
  3374. for (var i = 0; i < length; ++i) {
  3375. if ((i + offset >= dst.length) || (i >= src.length)) break
  3376. dst[i + offset] = src[i]
  3377. }
  3378. return i
  3379. }
  3380. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3381. // the `instanceof` check but they should be treated as of that type.
  3382. // See: https://github.com/feross/buffer/issues/166
  3383. function isInstance (obj, type) {
  3384. return obj instanceof type ||
  3385. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3386. obj.constructor.name === type.name)
  3387. }
  3388. function numberIsNaN (obj) {
  3389. // For IE11 support
  3390. return obj !== obj // eslint-disable-line no-self-compare
  3391. }
  3392. }).call(this)}).call(this,require("buffer").Buffer)
  3393. },{"base64-js":9,"buffer":12,"ieee754":83}],13:[function(require,module,exports){
  3394. (function (Buffer){(function (){
  3395. // Copyright Joyent, Inc. and other Node contributors.
  3396. //
  3397. // Permission is hereby granted, free of charge, to any person obtaining a
  3398. // copy of this software and associated documentation files (the
  3399. // "Software"), to deal in the Software without restriction, including
  3400. // without limitation the rights to use, copy, modify, merge, publish,
  3401. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3402. // persons to whom the Software is furnished to do so, subject to the
  3403. // following conditions:
  3404. //
  3405. // The above copyright notice and this permission notice shall be included
  3406. // in all copies or substantial portions of the Software.
  3407. //
  3408. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3409. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3410. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3411. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3412. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3413. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3414. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3415. // NOTE: These type checking functions intentionally don't use `instanceof`
  3416. // because it is fragile and can be easily faked with `Object.create()`.
  3417. function isArray(arg) {
  3418. if (Array.isArray) {
  3419. return Array.isArray(arg);
  3420. }
  3421. return objectToString(arg) === '[object Array]';
  3422. }
  3423. exports.isArray = isArray;
  3424. function isBoolean(arg) {
  3425. return typeof arg === 'boolean';
  3426. }
  3427. exports.isBoolean = isBoolean;
  3428. function isNull(arg) {
  3429. return arg === null;
  3430. }
  3431. exports.isNull = isNull;
  3432. function isNullOrUndefined(arg) {
  3433. return arg == null;
  3434. }
  3435. exports.isNullOrUndefined = isNullOrUndefined;
  3436. function isNumber(arg) {
  3437. return typeof arg === 'number';
  3438. }
  3439. exports.isNumber = isNumber;
  3440. function isString(arg) {
  3441. return typeof arg === 'string';
  3442. }
  3443. exports.isString = isString;
  3444. function isSymbol(arg) {
  3445. return typeof arg === 'symbol';
  3446. }
  3447. exports.isSymbol = isSymbol;
  3448. function isUndefined(arg) {
  3449. return arg === void 0;
  3450. }
  3451. exports.isUndefined = isUndefined;
  3452. function isRegExp(re) {
  3453. return objectToString(re) === '[object RegExp]';
  3454. }
  3455. exports.isRegExp = isRegExp;
  3456. function isObject(arg) {
  3457. return typeof arg === 'object' && arg !== null;
  3458. }
  3459. exports.isObject = isObject;
  3460. function isDate(d) {
  3461. return objectToString(d) === '[object Date]';
  3462. }
  3463. exports.isDate = isDate;
  3464. function isError(e) {
  3465. return (objectToString(e) === '[object Error]' || e instanceof Error);
  3466. }
  3467. exports.isError = isError;
  3468. function isFunction(arg) {
  3469. return typeof arg === 'function';
  3470. }
  3471. exports.isFunction = isFunction;
  3472. function isPrimitive(arg) {
  3473. return arg === null ||
  3474. typeof arg === 'boolean' ||
  3475. typeof arg === 'number' ||
  3476. typeof arg === 'string' ||
  3477. typeof arg === 'symbol' || // ES6 symbol
  3478. typeof arg === 'undefined';
  3479. }
  3480. exports.isPrimitive = isPrimitive;
  3481. exports.isBuffer = Buffer.isBuffer;
  3482. function objectToString(o) {
  3483. return Object.prototype.toString.call(o);
  3484. }
  3485. }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  3486. },{"../../is-buffer/index.js":85}],14:[function(require,module,exports){
  3487. "use strict";
  3488. var isValue = require("type/value/is")
  3489. , ensureValue = require("type/value/ensure")
  3490. , ensurePlainFunction = require("type/plain-function/ensure")
  3491. , copy = require("es5-ext/object/copy")
  3492. , normalizeOptions = require("es5-ext/object/normalize-options")
  3493. , map = require("es5-ext/object/map");
  3494. var bind = Function.prototype.bind
  3495. , defineProperty = Object.defineProperty
  3496. , hasOwnProperty = Object.prototype.hasOwnProperty
  3497. , define;
  3498. define = function (name, desc, options) {
  3499. var value = ensureValue(desc) && ensurePlainFunction(desc.value), dgs;
  3500. dgs = copy(desc);
  3501. delete dgs.writable;
  3502. delete dgs.value;
  3503. dgs.get = function () {
  3504. if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
  3505. desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
  3506. defineProperty(this, name, desc);
  3507. return this[name];
  3508. };
  3509. return dgs;
  3510. };
  3511. module.exports = function (props/*, options*/) {
  3512. var options = normalizeOptions(arguments[1]);
  3513. if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext);
  3514. return map(props, function (desc, name) { return define(name, desc, options); });
  3515. };
  3516. },{"es5-ext/object/copy":37,"es5-ext/object/map":45,"es5-ext/object/normalize-options":46,"type/plain-function/ensure":122,"type/value/ensure":126,"type/value/is":127}],15:[function(require,module,exports){
  3517. "use strict";
  3518. var isValue = require("type/value/is")
  3519. , isPlainFunction = require("type/plain-function/is")
  3520. , assign = require("es5-ext/object/assign")
  3521. , normalizeOpts = require("es5-ext/object/normalize-options")
  3522. , contains = require("es5-ext/string/#/contains");
  3523. var d = (module.exports = function (dscr, value/*, options*/) {
  3524. var c, e, w, options, desc;
  3525. if (arguments.length < 2 || typeof dscr !== "string") {
  3526. options = value;
  3527. value = dscr;
  3528. dscr = null;
  3529. } else {
  3530. options = arguments[2];
  3531. }
  3532. if (isValue(dscr)) {
  3533. c = contains.call(dscr, "c");
  3534. e = contains.call(dscr, "e");
  3535. w = contains.call(dscr, "w");
  3536. } else {
  3537. c = w = true;
  3538. e = false;
  3539. }
  3540. desc = { value: value, configurable: c, enumerable: e, writable: w };
  3541. return !options ? desc : assign(normalizeOpts(options), desc);
  3542. });
  3543. d.gs = function (dscr, get, set/*, options*/) {
  3544. var c, e, options, desc;
  3545. if (typeof dscr !== "string") {
  3546. options = set;
  3547. set = get;
  3548. get = dscr;
  3549. dscr = null;
  3550. } else {
  3551. options = arguments[3];
  3552. }
  3553. if (!isValue(get)) {
  3554. get = undefined;
  3555. } else if (!isPlainFunction(get)) {
  3556. options = get;
  3557. get = set = undefined;
  3558. } else if (!isValue(set)) {
  3559. set = undefined;
  3560. } else if (!isPlainFunction(set)) {
  3561. options = set;
  3562. set = undefined;
  3563. }
  3564. if (isValue(dscr)) {
  3565. c = contains.call(dscr, "c");
  3566. e = contains.call(dscr, "e");
  3567. } else {
  3568. c = true;
  3569. e = false;
  3570. }
  3571. desc = { get: get, set: set, configurable: c, enumerable: e };
  3572. return !options ? desc : assign(normalizeOpts(options), desc);
  3573. };
  3574. },{"es5-ext/object/assign":34,"es5-ext/object/normalize-options":46,"es5-ext/string/#/contains":53,"type/plain-function/is":123,"type/value/is":127}],16:[function(require,module,exports){
  3575. (function (process){(function (){
  3576. var once = require('once');
  3577. var noop = function() {};
  3578. var isRequest = function(stream) {
  3579. return stream.setHeader && typeof stream.abort === 'function';
  3580. };
  3581. var isChildProcess = function(stream) {
  3582. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  3583. };
  3584. var eos = function(stream, opts, callback) {
  3585. if (typeof opts === 'function') return eos(stream, null, opts);
  3586. if (!opts) opts = {};
  3587. callback = once(callback || noop);
  3588. var ws = stream._writableState;
  3589. var rs = stream._readableState;
  3590. var readable = opts.readable || (opts.readable !== false && stream.readable);
  3591. var writable = opts.writable || (opts.writable !== false && stream.writable);
  3592. var cancelled = false;
  3593. var onlegacyfinish = function() {
  3594. if (!stream.writable) onfinish();
  3595. };
  3596. var onfinish = function() {
  3597. writable = false;
  3598. if (!readable) callback.call(stream);
  3599. };
  3600. var onend = function() {
  3601. readable = false;
  3602. if (!writable) callback.call(stream);
  3603. };
  3604. var onexit = function(exitCode) {
  3605. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  3606. };
  3607. var onerror = function(err) {
  3608. callback.call(stream, err);
  3609. };
  3610. var onclose = function() {
  3611. process.nextTick(onclosenexttick);
  3612. };
  3613. var onclosenexttick = function() {
  3614. if (cancelled) return;
  3615. if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
  3616. if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
  3617. };
  3618. var onrequest = function() {
  3619. stream.req.on('finish', onfinish);
  3620. };
  3621. if (isRequest(stream)) {
  3622. stream.on('complete', onfinish);
  3623. stream.on('abort', onclose);
  3624. if (stream.req) onrequest();
  3625. else stream.on('request', onrequest);
  3626. } else if (writable && !ws) { // legacy streams
  3627. stream.on('end', onlegacyfinish);
  3628. stream.on('close', onlegacyfinish);
  3629. }
  3630. if (isChildProcess(stream)) stream.on('exit', onexit);
  3631. stream.on('end', onend);
  3632. stream.on('finish', onfinish);
  3633. if (opts.error !== false) stream.on('error', onerror);
  3634. stream.on('close', onclose);
  3635. return function() {
  3636. cancelled = true;
  3637. stream.removeListener('complete', onfinish);
  3638. stream.removeListener('abort', onclose);
  3639. stream.removeListener('request', onrequest);
  3640. if (stream.req) stream.req.removeListener('finish', onfinish);
  3641. stream.removeListener('end', onlegacyfinish);
  3642. stream.removeListener('close', onlegacyfinish);
  3643. stream.removeListener('finish', onfinish);
  3644. stream.removeListener('exit', onexit);
  3645. stream.removeListener('end', onend);
  3646. stream.removeListener('error', onerror);
  3647. stream.removeListener('close', onclose);
  3648. };
  3649. };
  3650. module.exports = eos;
  3651. }).call(this)}).call(this,require('_process'))
  3652. },{"_process":96,"once":94}],17:[function(require,module,exports){
  3653. // Inspired by Google Closure:
  3654. // http://closure-library.googlecode.com/svn/docs/
  3655. // closure_goog_array_array.js.html#goog.array.clear
  3656. "use strict";
  3657. var value = require("../../object/valid-value");
  3658. module.exports = function () {
  3659. value(this).length = 0;
  3660. return this;
  3661. };
  3662. },{"../../object/valid-value":52}],18:[function(require,module,exports){
  3663. "use strict";
  3664. var numberIsNaN = require("../../number/is-nan")
  3665. , toPosInt = require("../../number/to-pos-integer")
  3666. , value = require("../../object/valid-value")
  3667. , indexOf = Array.prototype.indexOf
  3668. , objHasOwnProperty = Object.prototype.hasOwnProperty
  3669. , abs = Math.abs
  3670. , floor = Math.floor;
  3671. module.exports = function (searchElement/*, fromIndex*/) {
  3672. var i, length, fromIndex, val;
  3673. if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
  3674. length = toPosInt(value(this).length);
  3675. fromIndex = arguments[1];
  3676. if (isNaN(fromIndex)) fromIndex = 0;
  3677. else if (fromIndex >= 0) fromIndex = floor(fromIndex);
  3678. else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
  3679. for (i = fromIndex; i < length; ++i) {
  3680. if (objHasOwnProperty.call(this, i)) {
  3681. val = this[i];
  3682. if (numberIsNaN(val)) return i; // Jslint: ignore
  3683. }
  3684. }
  3685. return -1;
  3686. };
  3687. },{"../../number/is-nan":28,"../../number/to-pos-integer":32,"../../object/valid-value":52}],19:[function(require,module,exports){
  3688. "use strict";
  3689. module.exports = require("./is-implemented")() ? Array.from : require("./shim");
  3690. },{"./is-implemented":20,"./shim":21}],20:[function(require,module,exports){
  3691. "use strict";
  3692. module.exports = function () {
  3693. var from = Array.from, arr, result;
  3694. if (typeof from !== "function") return false;
  3695. arr = ["raz", "dwa"];
  3696. result = from(arr);
  3697. return Boolean(result && result !== arr && result[1] === "dwa");
  3698. };
  3699. },{}],21:[function(require,module,exports){
  3700. "use strict";
  3701. var iteratorSymbol = require("es6-symbol").iterator
  3702. , isArguments = require("../../function/is-arguments")
  3703. , isFunction = require("../../function/is-function")
  3704. , toPosInt = require("../../number/to-pos-integer")
  3705. , callable = require("../../object/valid-callable")
  3706. , validValue = require("../../object/valid-value")
  3707. , isValue = require("../../object/is-value")
  3708. , isString = require("../../string/is-string")
  3709. , isArray = Array.isArray
  3710. , call = Function.prototype.call
  3711. , desc = { configurable: true, enumerable: true, writable: true, value: null }
  3712. , defineProperty = Object.defineProperty;
  3713. // eslint-disable-next-line complexity, max-lines-per-function
  3714. module.exports = function (arrayLike/*, mapFn, thisArg*/) {
  3715. var mapFn = arguments[1]
  3716. , thisArg = arguments[2]
  3717. , Context
  3718. , i
  3719. , j
  3720. , arr
  3721. , length
  3722. , code
  3723. , iterator
  3724. , result
  3725. , getIterator
  3726. , value;
  3727. arrayLike = Object(validValue(arrayLike));
  3728. if (isValue(mapFn)) callable(mapFn);
  3729. if (!this || this === Array || !isFunction(this)) {
  3730. // Result: Plain array
  3731. if (!mapFn) {
  3732. if (isArguments(arrayLike)) {
  3733. // Source: Arguments
  3734. length = arrayLike.length;
  3735. if (length !== 1) return Array.apply(null, arrayLike);
  3736. arr = new Array(1);
  3737. arr[0] = arrayLike[0];
  3738. return arr;
  3739. }
  3740. if (isArray(arrayLike)) {
  3741. // Source: Array
  3742. arr = new Array((length = arrayLike.length));
  3743. for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
  3744. return arr;
  3745. }
  3746. }
  3747. arr = [];
  3748. } else {
  3749. // Result: Non plain array
  3750. Context = this;
  3751. }
  3752. if (!isArray(arrayLike)) {
  3753. if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
  3754. // Source: Iterator
  3755. iterator = callable(getIterator).call(arrayLike);
  3756. if (Context) arr = new Context();
  3757. result = iterator.next();
  3758. i = 0;
  3759. while (!result.done) {
  3760. value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
  3761. if (Context) {
  3762. desc.value = value;
  3763. defineProperty(arr, i, desc);
  3764. } else {
  3765. arr[i] = value;
  3766. }
  3767. result = iterator.next();
  3768. ++i;
  3769. }
  3770. length = i;
  3771. } else if (isString(arrayLike)) {
  3772. // Source: String
  3773. length = arrayLike.length;
  3774. if (Context) arr = new Context();
  3775. for (i = 0, j = 0; i < length; ++i) {
  3776. value = arrayLike[i];
  3777. if (i + 1 < length) {
  3778. code = value.charCodeAt(0);
  3779. // eslint-disable-next-line max-depth
  3780. if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
  3781. }
  3782. value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
  3783. if (Context) {
  3784. desc.value = value;
  3785. defineProperty(arr, j, desc);
  3786. } else {
  3787. arr[j] = value;
  3788. }
  3789. ++j;
  3790. }
  3791. length = j;
  3792. }
  3793. }
  3794. if (length === undefined) {
  3795. // Source: array or array-like
  3796. length = toPosInt(arrayLike.length);
  3797. if (Context) arr = new Context(length);
  3798. for (i = 0; i < length; ++i) {
  3799. value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
  3800. if (Context) {
  3801. desc.value = value;
  3802. defineProperty(arr, i, desc);
  3803. } else {
  3804. arr[i] = value;
  3805. }
  3806. }
  3807. }
  3808. if (Context) {
  3809. desc.value = null;
  3810. arr.length = length;
  3811. }
  3812. return arr;
  3813. };
  3814. },{"../../function/is-arguments":22,"../../function/is-function":23,"../../number/to-pos-integer":32,"../../object/is-value":41,"../../object/valid-callable":51,"../../object/valid-value":52,"../../string/is-string":56,"es6-symbol":70}],22:[function(require,module,exports){
  3815. "use strict";
  3816. var objToString = Object.prototype.toString
  3817. , id = objToString.call((function () { return arguments; })());
  3818. module.exports = function (value) { return objToString.call(value) === id; };
  3819. },{}],23:[function(require,module,exports){
  3820. "use strict";
  3821. var objToString = Object.prototype.toString
  3822. , isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);
  3823. module.exports = function (value) {
  3824. return typeof value === "function" && isFunctionStringTag(objToString.call(value));
  3825. };
  3826. },{}],24:[function(require,module,exports){
  3827. "use strict";
  3828. // eslint-disable-next-line no-empty-function
  3829. module.exports = function () {};
  3830. },{}],25:[function(require,module,exports){
  3831. "use strict";
  3832. module.exports = require("./is-implemented")() ? Math.sign : require("./shim");
  3833. },{"./is-implemented":26,"./shim":27}],26:[function(require,module,exports){
  3834. "use strict";
  3835. module.exports = function () {
  3836. var sign = Math.sign;
  3837. if (typeof sign !== "function") return false;
  3838. return sign(10) === 1 && sign(-20) === -1;
  3839. };
  3840. },{}],27:[function(require,module,exports){
  3841. "use strict";
  3842. module.exports = function (value) {
  3843. value = Number(value);
  3844. if (isNaN(value) || value === 0) return value;
  3845. return value > 0 ? 1 : -1;
  3846. };
  3847. },{}],28:[function(require,module,exports){
  3848. "use strict";
  3849. module.exports = require("./is-implemented")() ? Number.isNaN : require("./shim");
  3850. },{"./is-implemented":29,"./shim":30}],29:[function(require,module,exports){
  3851. "use strict";
  3852. module.exports = function () {
  3853. var numberIsNaN = Number.isNaN;
  3854. if (typeof numberIsNaN !== "function") return false;
  3855. return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
  3856. };
  3857. },{}],30:[function(require,module,exports){
  3858. "use strict";
  3859. module.exports = function (value) {
  3860. // eslint-disable-next-line no-self-compare
  3861. return value !== value;
  3862. };
  3863. },{}],31:[function(require,module,exports){
  3864. "use strict";
  3865. var sign = require("../math/sign")
  3866. , abs = Math.abs
  3867. , floor = Math.floor;
  3868. module.exports = function (value) {
  3869. if (isNaN(value)) return 0;
  3870. value = Number(value);
  3871. if (value === 0 || !isFinite(value)) return value;
  3872. return sign(value) * floor(abs(value));
  3873. };
  3874. },{"../math/sign":25}],32:[function(require,module,exports){
  3875. "use strict";
  3876. var toInteger = require("./to-integer")
  3877. , max = Math.max;
  3878. module.exports = function (value) { return max(0, toInteger(value)); };
  3879. },{"./to-integer":31}],33:[function(require,module,exports){
  3880. // Internal method, used by iteration functions.
  3881. // Calls a function for each key-value pair found in object
  3882. // Optionally takes compareFn to iterate object in specific order
  3883. "use strict";
  3884. var callable = require("./valid-callable")
  3885. , value = require("./valid-value")
  3886. , bind = Function.prototype.bind
  3887. , call = Function.prototype.call
  3888. , keys = Object.keys
  3889. , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
  3890. module.exports = function (method, defVal) {
  3891. return function (obj, cb/*, thisArg, compareFn*/) {
  3892. var list, thisArg = arguments[2], compareFn = arguments[3];
  3893. obj = Object(value(obj));
  3894. callable(cb);
  3895. list = keys(obj);
  3896. if (compareFn) {
  3897. list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
  3898. }
  3899. if (typeof method !== "function") method = list[method];
  3900. return call.call(method, list, function (key, index) {
  3901. if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
  3902. return call.call(cb, thisArg, obj[key], key, obj, index);
  3903. });
  3904. };
  3905. };
  3906. },{"./valid-callable":51,"./valid-value":52}],34:[function(require,module,exports){
  3907. "use strict";
  3908. module.exports = require("./is-implemented")() ? Object.assign : require("./shim");
  3909. },{"./is-implemented":35,"./shim":36}],35:[function(require,module,exports){
  3910. "use strict";
  3911. module.exports = function () {
  3912. var assign = Object.assign, obj;
  3913. if (typeof assign !== "function") return false;
  3914. obj = { foo: "raz" };
  3915. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  3916. return obj.foo + obj.bar + obj.trzy === "razdwatrzy";
  3917. };
  3918. },{}],36:[function(require,module,exports){
  3919. "use strict";
  3920. var keys = require("../keys")
  3921. , value = require("../valid-value")
  3922. , max = Math.max;
  3923. module.exports = function (dest, src/*, …srcn*/) {
  3924. var error, i, length = max(arguments.length, 2), assign;
  3925. dest = Object(value(dest));
  3926. assign = function (key) {
  3927. try {
  3928. dest[key] = src[key];
  3929. } catch (e) {
  3930. if (!error) error = e;
  3931. }
  3932. };
  3933. for (i = 1; i < length; ++i) {
  3934. src = arguments[i];
  3935. keys(src).forEach(assign);
  3936. }
  3937. if (error !== undefined) throw error;
  3938. return dest;
  3939. };
  3940. },{"../keys":42,"../valid-value":52}],37:[function(require,module,exports){
  3941. "use strict";
  3942. var aFrom = require("../array/from")
  3943. , assign = require("./assign")
  3944. , value = require("./valid-value");
  3945. module.exports = function (obj/*, propertyNames, options*/) {
  3946. var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
  3947. if (copy !== obj && !propertyNames) return copy;
  3948. var result = {};
  3949. if (propertyNames) {
  3950. aFrom(propertyNames, function (propertyName) {
  3951. if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
  3952. });
  3953. } else {
  3954. assign(result, obj);
  3955. }
  3956. return result;
  3957. };
  3958. },{"../array/from":19,"./assign":34,"./valid-value":52}],38:[function(require,module,exports){
  3959. // Workaround for http://code.google.com/p/v8/issues/detail?id=2804
  3960. "use strict";
  3961. var create = Object.create, shim;
  3962. if (!require("./set-prototype-of/is-implemented")()) {
  3963. shim = require("./set-prototype-of/shim");
  3964. }
  3965. module.exports = (function () {
  3966. var nullObject, polyProps, desc;
  3967. if (!shim) return create;
  3968. if (shim.level !== 1) return create;
  3969. nullObject = {};
  3970. polyProps = {};
  3971. desc = { configurable: false, enumerable: false, writable: true, value: undefined };
  3972. Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
  3973. if (name === "__proto__") {
  3974. polyProps[name] = {
  3975. configurable: true,
  3976. enumerable: false,
  3977. writable: true,
  3978. value: undefined
  3979. };
  3980. return;
  3981. }
  3982. polyProps[name] = desc;
  3983. });
  3984. Object.defineProperties(nullObject, polyProps);
  3985. Object.defineProperty(shim, "nullPolyfill", {
  3986. configurable: false,
  3987. enumerable: false,
  3988. writable: false,
  3989. value: nullObject
  3990. });
  3991. return function (prototype, props) {
  3992. return create(prototype === null ? nullObject : prototype, props);
  3993. };
  3994. })();
  3995. },{"./set-prototype-of/is-implemented":49,"./set-prototype-of/shim":50}],39:[function(require,module,exports){
  3996. "use strict";
  3997. module.exports = require("./_iterate")("forEach");
  3998. },{"./_iterate":33}],40:[function(require,module,exports){
  3999. "use strict";
  4000. var isValue = require("./is-value");
  4001. var map = { function: true, object: true };
  4002. module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; };
  4003. },{"./is-value":41}],41:[function(require,module,exports){
  4004. "use strict";
  4005. var _undefined = require("../function/noop")(); // Support ES3 engines
  4006. module.exports = function (val) { return val !== _undefined && val !== null; };
  4007. },{"../function/noop":24}],42:[function(require,module,exports){
  4008. "use strict";
  4009. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  4010. },{"./is-implemented":43,"./shim":44}],43:[function(require,module,exports){
  4011. "use strict";
  4012. module.exports = function () {
  4013. try {
  4014. Object.keys("primitive");
  4015. return true;
  4016. } catch (e) {
  4017. return false;
  4018. }
  4019. };
  4020. },{}],44:[function(require,module,exports){
  4021. "use strict";
  4022. var isValue = require("../is-value");
  4023. var keys = Object.keys;
  4024. module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
  4025. },{"../is-value":41}],45:[function(require,module,exports){
  4026. "use strict";
  4027. var callable = require("./valid-callable")
  4028. , forEach = require("./for-each")
  4029. , call = Function.prototype.call;
  4030. module.exports = function (obj, cb/*, thisArg*/) {
  4031. var result = {}, thisArg = arguments[2];
  4032. callable(cb);
  4033. forEach(obj, function (value, key, targetObj, index) {
  4034. result[key] = call.call(cb, thisArg, value, key, targetObj, index);
  4035. });
  4036. return result;
  4037. };
  4038. },{"./for-each":39,"./valid-callable":51}],46:[function(require,module,exports){
  4039. "use strict";
  4040. var isValue = require("./is-value");
  4041. var forEach = Array.prototype.forEach, create = Object.create;
  4042. var process = function (src, obj) {
  4043. var key;
  4044. for (key in src) obj[key] = src[key];
  4045. };
  4046. // eslint-disable-next-line no-unused-vars
  4047. module.exports = function (opts1/*, …options*/) {
  4048. var result = create(null);
  4049. forEach.call(arguments, function (options) {
  4050. if (!isValue(options)) return;
  4051. process(Object(options), result);
  4052. });
  4053. return result;
  4054. };
  4055. },{"./is-value":41}],47:[function(require,module,exports){
  4056. "use strict";
  4057. var forEach = Array.prototype.forEach, create = Object.create;
  4058. // eslint-disable-next-line no-unused-vars
  4059. module.exports = function (arg/*, …args*/) {
  4060. var set = create(null);
  4061. forEach.call(arguments, function (name) { set[name] = true; });
  4062. return set;
  4063. };
  4064. },{}],48:[function(require,module,exports){
  4065. "use strict";
  4066. module.exports = require("./is-implemented")() ? Object.setPrototypeOf : require("./shim");
  4067. },{"./is-implemented":49,"./shim":50}],49:[function(require,module,exports){
  4068. "use strict";
  4069. var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
  4070. module.exports = function (/* CustomCreate*/) {
  4071. var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
  4072. if (typeof setPrototypeOf !== "function") return false;
  4073. return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
  4074. };
  4075. },{}],50:[function(require,module,exports){
  4076. /* eslint no-proto: "off" */
  4077. // Big thanks to @WebReflection for sorting this out
  4078. // https://gist.github.com/WebReflection/5593554
  4079. "use strict";
  4080. var isObject = require("../is-object")
  4081. , value = require("../valid-value")
  4082. , objIsPrototypeOf = Object.prototype.isPrototypeOf
  4083. , defineProperty = Object.defineProperty
  4084. , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined }
  4085. , validate;
  4086. validate = function (obj, prototype) {
  4087. value(obj);
  4088. if (prototype === null || isObject(prototype)) return obj;
  4089. throw new TypeError("Prototype must be null or an object");
  4090. };
  4091. module.exports = (function (status) {
  4092. var fn, set;
  4093. if (!status) return null;
  4094. if (status.level === 2) {
  4095. if (status.set) {
  4096. set = status.set;
  4097. fn = function (obj, prototype) {
  4098. set.call(validate(obj, prototype), prototype);
  4099. return obj;
  4100. };
  4101. } else {
  4102. fn = function (obj, prototype) {
  4103. validate(obj, prototype).__proto__ = prototype;
  4104. return obj;
  4105. };
  4106. }
  4107. } else {
  4108. fn = function self(obj, prototype) {
  4109. var isNullBase;
  4110. validate(obj, prototype);
  4111. isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
  4112. if (isNullBase) delete self.nullPolyfill.__proto__;
  4113. if (prototype === null) prototype = self.nullPolyfill;
  4114. obj.__proto__ = prototype;
  4115. if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
  4116. return obj;
  4117. };
  4118. }
  4119. return Object.defineProperty(fn, "level", {
  4120. configurable: false,
  4121. enumerable: false,
  4122. writable: false,
  4123. value: status.level
  4124. });
  4125. })(
  4126. (function () {
  4127. var tmpObj1 = Object.create(null)
  4128. , tmpObj2 = {}
  4129. , set
  4130. , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
  4131. if (desc) {
  4132. try {
  4133. set = desc.set; // Opera crashes at this point
  4134. set.call(tmpObj1, tmpObj2);
  4135. } catch (ignore) {}
  4136. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
  4137. }
  4138. tmpObj1.__proto__ = tmpObj2;
  4139. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
  4140. tmpObj1 = {};
  4141. tmpObj1.__proto__ = tmpObj2;
  4142. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
  4143. return false;
  4144. })()
  4145. );
  4146. require("../create");
  4147. },{"../create":38,"../is-object":40,"../valid-value":52}],51:[function(require,module,exports){
  4148. "use strict";
  4149. module.exports = function (fn) {
  4150. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  4151. return fn;
  4152. };
  4153. },{}],52:[function(require,module,exports){
  4154. "use strict";
  4155. var isValue = require("./is-value");
  4156. module.exports = function (value) {
  4157. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  4158. return value;
  4159. };
  4160. },{"./is-value":41}],53:[function(require,module,exports){
  4161. "use strict";
  4162. module.exports = require("./is-implemented")() ? String.prototype.contains : require("./shim");
  4163. },{"./is-implemented":54,"./shim":55}],54:[function(require,module,exports){
  4164. "use strict";
  4165. var str = "razdwatrzy";
  4166. module.exports = function () {
  4167. if (typeof str.contains !== "function") return false;
  4168. return str.contains("dwa") === true && str.contains("foo") === false;
  4169. };
  4170. },{}],55:[function(require,module,exports){
  4171. "use strict";
  4172. var indexOf = String.prototype.indexOf;
  4173. module.exports = function (searchString/*, position*/) {
  4174. return indexOf.call(this, searchString, arguments[1]) > -1;
  4175. };
  4176. },{}],56:[function(require,module,exports){
  4177. "use strict";
  4178. var objToString = Object.prototype.toString, id = objToString.call("");
  4179. module.exports = function (value) {
  4180. return (
  4181. typeof value === "string" ||
  4182. (value &&
  4183. typeof value === "object" &&
  4184. (value instanceof String || objToString.call(value) === id)) ||
  4185. false
  4186. );
  4187. };
  4188. },{}],57:[function(require,module,exports){
  4189. "use strict";
  4190. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  4191. , contains = require("es5-ext/string/#/contains")
  4192. , d = require("d")
  4193. , Symbol = require("es6-symbol")
  4194. , Iterator = require("./");
  4195. var defineProperty = Object.defineProperty, ArrayIterator;
  4196. ArrayIterator = module.exports = function (arr, kind) {
  4197. if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
  4198. Iterator.call(this, arr);
  4199. if (!kind) kind = "value";
  4200. else if (contains.call(kind, "key+value")) kind = "key+value";
  4201. else if (contains.call(kind, "key")) kind = "key";
  4202. else kind = "value";
  4203. defineProperty(this, "__kind__", d("", kind));
  4204. };
  4205. if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
  4206. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  4207. delete ArrayIterator.prototype.constructor;
  4208. ArrayIterator.prototype = Object.create(Iterator.prototype, {
  4209. _resolve: d(function (i) {
  4210. if (this.__kind__ === "value") return this.__list__[i];
  4211. if (this.__kind__ === "key+value") return [i, this.__list__[i]];
  4212. return i;
  4213. })
  4214. });
  4215. defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
  4216. },{"./":60,"d":15,"es5-ext/object/set-prototype-of":48,"es5-ext/string/#/contains":53,"es6-symbol":70}],58:[function(require,module,exports){
  4217. "use strict";
  4218. var isArguments = require("es5-ext/function/is-arguments")
  4219. , callable = require("es5-ext/object/valid-callable")
  4220. , isString = require("es5-ext/string/is-string")
  4221. , get = require("./get");
  4222. var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
  4223. module.exports = function (iterable, cb /*, thisArg*/) {
  4224. var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
  4225. if (isArray(iterable) || isArguments(iterable)) mode = "array";
  4226. else if (isString(iterable)) mode = "string";
  4227. else iterable = get(iterable);
  4228. callable(cb);
  4229. doBreak = function () {
  4230. broken = true;
  4231. };
  4232. if (mode === "array") {
  4233. some.call(iterable, function (value) {
  4234. call.call(cb, thisArg, value, doBreak);
  4235. return broken;
  4236. });
  4237. return;
  4238. }
  4239. if (mode === "string") {
  4240. length = iterable.length;
  4241. for (i = 0; i < length; ++i) {
  4242. char = iterable[i];
  4243. if (i + 1 < length) {
  4244. code = char.charCodeAt(0);
  4245. if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
  4246. }
  4247. call.call(cb, thisArg, char, doBreak);
  4248. if (broken) break;
  4249. }
  4250. return;
  4251. }
  4252. result = iterable.next();
  4253. while (!result.done) {
  4254. call.call(cb, thisArg, result.value, doBreak);
  4255. if (broken) return;
  4256. result = iterable.next();
  4257. }
  4258. };
  4259. },{"./get":59,"es5-ext/function/is-arguments":22,"es5-ext/object/valid-callable":51,"es5-ext/string/is-string":56}],59:[function(require,module,exports){
  4260. "use strict";
  4261. var isArguments = require("es5-ext/function/is-arguments")
  4262. , isString = require("es5-ext/string/is-string")
  4263. , ArrayIterator = require("./array")
  4264. , StringIterator = require("./string")
  4265. , iterable = require("./valid-iterable")
  4266. , iteratorSymbol = require("es6-symbol").iterator;
  4267. module.exports = function (obj) {
  4268. if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
  4269. if (isArguments(obj)) return new ArrayIterator(obj);
  4270. if (isString(obj)) return new StringIterator(obj);
  4271. return new ArrayIterator(obj);
  4272. };
  4273. },{"./array":57,"./string":62,"./valid-iterable":63,"es5-ext/function/is-arguments":22,"es5-ext/string/is-string":56,"es6-symbol":70}],60:[function(require,module,exports){
  4274. "use strict";
  4275. var clear = require("es5-ext/array/#/clear")
  4276. , assign = require("es5-ext/object/assign")
  4277. , callable = require("es5-ext/object/valid-callable")
  4278. , value = require("es5-ext/object/valid-value")
  4279. , d = require("d")
  4280. , autoBind = require("d/auto-bind")
  4281. , Symbol = require("es6-symbol");
  4282. var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
  4283. module.exports = Iterator = function (list, context) {
  4284. if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
  4285. defineProperties(this, {
  4286. __list__: d("w", value(list)),
  4287. __context__: d("w", context),
  4288. __nextIndex__: d("w", 0)
  4289. });
  4290. if (!context) return;
  4291. callable(context.on);
  4292. context.on("_add", this._onAdd);
  4293. context.on("_delete", this._onDelete);
  4294. context.on("_clear", this._onClear);
  4295. };
  4296. // Internal %IteratorPrototype% doesn't expose its constructor
  4297. delete Iterator.prototype.constructor;
  4298. defineProperties(
  4299. Iterator.prototype,
  4300. assign(
  4301. {
  4302. _next: d(function () {
  4303. var i;
  4304. if (!this.__list__) return undefined;
  4305. if (this.__redo__) {
  4306. i = this.__redo__.shift();
  4307. if (i !== undefined) return i;
  4308. }
  4309. if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
  4310. this._unBind();
  4311. return undefined;
  4312. }),
  4313. next: d(function () {
  4314. return this._createResult(this._next());
  4315. }),
  4316. _createResult: d(function (i) {
  4317. if (i === undefined) return { done: true, value: undefined };
  4318. return { done: false, value: this._resolve(i) };
  4319. }),
  4320. _resolve: d(function (i) {
  4321. return this.__list__[i];
  4322. }),
  4323. _unBind: d(function () {
  4324. this.__list__ = null;
  4325. delete this.__redo__;
  4326. if (!this.__context__) return;
  4327. this.__context__.off("_add", this._onAdd);
  4328. this.__context__.off("_delete", this._onDelete);
  4329. this.__context__.off("_clear", this._onClear);
  4330. this.__context__ = null;
  4331. }),
  4332. toString: d(function () {
  4333. return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
  4334. })
  4335. },
  4336. autoBind({
  4337. _onAdd: d(function (index) {
  4338. if (index >= this.__nextIndex__) return;
  4339. ++this.__nextIndex__;
  4340. if (!this.__redo__) {
  4341. defineProperty(this, "__redo__", d("c", [index]));
  4342. return;
  4343. }
  4344. this.__redo__.forEach(function (redo, i) {
  4345. if (redo >= index) this.__redo__[i] = ++redo;
  4346. }, this);
  4347. this.__redo__.push(index);
  4348. }),
  4349. _onDelete: d(function (index) {
  4350. var i;
  4351. if (index >= this.__nextIndex__) return;
  4352. --this.__nextIndex__;
  4353. if (!this.__redo__) return;
  4354. i = this.__redo__.indexOf(index);
  4355. if (i !== -1) this.__redo__.splice(i, 1);
  4356. this.__redo__.forEach(function (redo, j) {
  4357. if (redo > index) this.__redo__[j] = --redo;
  4358. }, this);
  4359. }),
  4360. _onClear: d(function () {
  4361. if (this.__redo__) clear.call(this.__redo__);
  4362. this.__nextIndex__ = 0;
  4363. })
  4364. })
  4365. )
  4366. );
  4367. defineProperty(
  4368. Iterator.prototype,
  4369. Symbol.iterator,
  4370. d(function () {
  4371. return this;
  4372. })
  4373. );
  4374. },{"d":15,"d/auto-bind":14,"es5-ext/array/#/clear":17,"es5-ext/object/assign":34,"es5-ext/object/valid-callable":51,"es5-ext/object/valid-value":52,"es6-symbol":70}],61:[function(require,module,exports){
  4375. "use strict";
  4376. var isArguments = require("es5-ext/function/is-arguments")
  4377. , isValue = require("es5-ext/object/is-value")
  4378. , isString = require("es5-ext/string/is-string");
  4379. var iteratorSymbol = require("es6-symbol").iterator
  4380. , isArray = Array.isArray;
  4381. module.exports = function (value) {
  4382. if (!isValue(value)) return false;
  4383. if (isArray(value)) return true;
  4384. if (isString(value)) return true;
  4385. if (isArguments(value)) return true;
  4386. return typeof value[iteratorSymbol] === "function";
  4387. };
  4388. },{"es5-ext/function/is-arguments":22,"es5-ext/object/is-value":41,"es5-ext/string/is-string":56,"es6-symbol":70}],62:[function(require,module,exports){
  4389. // Thanks @mathiasbynens
  4390. // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
  4391. "use strict";
  4392. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  4393. , d = require("d")
  4394. , Symbol = require("es6-symbol")
  4395. , Iterator = require("./");
  4396. var defineProperty = Object.defineProperty, StringIterator;
  4397. StringIterator = module.exports = function (str) {
  4398. if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
  4399. str = String(str);
  4400. Iterator.call(this, str);
  4401. defineProperty(this, "__length__", d("", str.length));
  4402. };
  4403. if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
  4404. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  4405. delete StringIterator.prototype.constructor;
  4406. StringIterator.prototype = Object.create(Iterator.prototype, {
  4407. _next: d(function () {
  4408. if (!this.__list__) return undefined;
  4409. if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
  4410. this._unBind();
  4411. return undefined;
  4412. }),
  4413. _resolve: d(function (i) {
  4414. var char = this.__list__[i], code;
  4415. if (this.__nextIndex__ === this.__length__) return char;
  4416. code = char.charCodeAt(0);
  4417. if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
  4418. return char;
  4419. })
  4420. });
  4421. defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
  4422. },{"./":60,"d":15,"es5-ext/object/set-prototype-of":48,"es6-symbol":70}],63:[function(require,module,exports){
  4423. "use strict";
  4424. var isIterable = require("./is-iterable");
  4425. module.exports = function (value) {
  4426. if (!isIterable(value)) throw new TypeError(value + " is not iterable");
  4427. return value;
  4428. };
  4429. },{"./is-iterable":61}],64:[function(require,module,exports){
  4430. 'use strict';
  4431. module.exports = require('./is-implemented')() ? Map : require('./polyfill');
  4432. },{"./is-implemented":65,"./polyfill":69}],65:[function(require,module,exports){
  4433. 'use strict';
  4434. module.exports = function () {
  4435. var map, iterator, result;
  4436. if (typeof Map !== 'function') return false;
  4437. try {
  4438. // WebKit doesn't support arguments and crashes
  4439. map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
  4440. } catch (e) {
  4441. return false;
  4442. }
  4443. if (String(map) !== '[object Map]') return false;
  4444. if (map.size !== 3) return false;
  4445. if (typeof map.clear !== 'function') return false;
  4446. if (typeof map.delete !== 'function') return false;
  4447. if (typeof map.entries !== 'function') return false;
  4448. if (typeof map.forEach !== 'function') return false;
  4449. if (typeof map.get !== 'function') return false;
  4450. if (typeof map.has !== 'function') return false;
  4451. if (typeof map.keys !== 'function') return false;
  4452. if (typeof map.set !== 'function') return false;
  4453. if (typeof map.values !== 'function') return false;
  4454. iterator = map.entries();
  4455. result = iterator.next();
  4456. if (result.done !== false) return false;
  4457. if (!result.value) return false;
  4458. if (result.value[0] !== 'raz') return false;
  4459. if (result.value[1] !== 'one') return false;
  4460. return true;
  4461. };
  4462. },{}],66:[function(require,module,exports){
  4463. // Exports true if environment provides native `Map` implementation,
  4464. // whatever that is.
  4465. 'use strict';
  4466. module.exports = (function () {
  4467. if (typeof Map === 'undefined') return false;
  4468. return (Object.prototype.toString.call(new Map()) === '[object Map]');
  4469. }());
  4470. },{}],67:[function(require,module,exports){
  4471. 'use strict';
  4472. module.exports = require('es5-ext/object/primitive-set')('key',
  4473. 'value', 'key+value');
  4474. },{"es5-ext/object/primitive-set":47}],68:[function(require,module,exports){
  4475. 'use strict';
  4476. var setPrototypeOf = require('es5-ext/object/set-prototype-of')
  4477. , d = require('d')
  4478. , Iterator = require('es6-iterator')
  4479. , toStringTagSymbol = require('es6-symbol').toStringTag
  4480. , kinds = require('./iterator-kinds')
  4481. , defineProperties = Object.defineProperties
  4482. , unBind = Iterator.prototype._unBind
  4483. , MapIterator;
  4484. MapIterator = module.exports = function (map, kind) {
  4485. if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
  4486. Iterator.call(this, map.__mapKeysData__, map);
  4487. if (!kind || !kinds[kind]) kind = 'key+value';
  4488. defineProperties(this, {
  4489. __kind__: d('', kind),
  4490. __values__: d('w', map.__mapValuesData__)
  4491. });
  4492. };
  4493. if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
  4494. MapIterator.prototype = Object.create(Iterator.prototype, {
  4495. constructor: d(MapIterator),
  4496. _resolve: d(function (i) {
  4497. if (this.__kind__ === 'value') return this.__values__[i];
  4498. if (this.__kind__ === 'key') return this.__list__[i];
  4499. return [this.__list__[i], this.__values__[i]];
  4500. }),
  4501. _unBind: d(function () {
  4502. this.__values__ = null;
  4503. unBind.call(this);
  4504. }),
  4505. toString: d(function () { return '[object Map Iterator]'; })
  4506. });
  4507. Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
  4508. d('c', 'Map Iterator'));
  4509. },{"./iterator-kinds":67,"d":15,"es5-ext/object/set-prototype-of":48,"es6-iterator":60,"es6-symbol":70}],69:[function(require,module,exports){
  4510. 'use strict';
  4511. var clear = require('es5-ext/array/#/clear')
  4512. , eIndexOf = require('es5-ext/array/#/e-index-of')
  4513. , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  4514. , callable = require('es5-ext/object/valid-callable')
  4515. , validValue = require('es5-ext/object/valid-value')
  4516. , d = require('d')
  4517. , ee = require('event-emitter')
  4518. , Symbol = require('es6-symbol')
  4519. , iterator = require('es6-iterator/valid-iterable')
  4520. , forOf = require('es6-iterator/for-of')
  4521. , Iterator = require('./lib/iterator')
  4522. , isNative = require('./is-native-implemented')
  4523. , call = Function.prototype.call
  4524. , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf
  4525. , MapPoly;
  4526. module.exports = MapPoly = function (/*iterable*/) {
  4527. var iterable = arguments[0], keys, values, self;
  4528. if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\'');
  4529. if (isNative && setPrototypeOf && (Map !== MapPoly)) {
  4530. self = setPrototypeOf(new Map(), getPrototypeOf(this));
  4531. } else {
  4532. self = this;
  4533. }
  4534. if (iterable != null) iterator(iterable);
  4535. defineProperties(self, {
  4536. __mapKeysData__: d('c', keys = []),
  4537. __mapValuesData__: d('c', values = [])
  4538. });
  4539. if (!iterable) return self;
  4540. forOf(iterable, function (value) {
  4541. var key = validValue(value)[0];
  4542. value = value[1];
  4543. if (eIndexOf.call(keys, key) !== -1) return;
  4544. keys.push(key);
  4545. values.push(value);
  4546. }, self);
  4547. return self;
  4548. };
  4549. if (isNative) {
  4550. if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
  4551. MapPoly.prototype = Object.create(Map.prototype, {
  4552. constructor: d(MapPoly)
  4553. });
  4554. }
  4555. ee(defineProperties(MapPoly.prototype, {
  4556. clear: d(function () {
  4557. if (!this.__mapKeysData__.length) return;
  4558. clear.call(this.__mapKeysData__);
  4559. clear.call(this.__mapValuesData__);
  4560. this.emit('_clear');
  4561. }),
  4562. delete: d(function (key) {
  4563. var index = eIndexOf.call(this.__mapKeysData__, key);
  4564. if (index === -1) return false;
  4565. this.__mapKeysData__.splice(index, 1);
  4566. this.__mapValuesData__.splice(index, 1);
  4567. this.emit('_delete', index, key);
  4568. return true;
  4569. }),
  4570. entries: d(function () { return new Iterator(this, 'key+value'); }),
  4571. forEach: d(function (cb/*, thisArg*/) {
  4572. var thisArg = arguments[1], iterator, result;
  4573. callable(cb);
  4574. iterator = this.entries();
  4575. result = iterator._next();
  4576. while (result !== undefined) {
  4577. call.call(cb, thisArg, this.__mapValuesData__[result],
  4578. this.__mapKeysData__[result], this);
  4579. result = iterator._next();
  4580. }
  4581. }),
  4582. get: d(function (key) {
  4583. var index = eIndexOf.call(this.__mapKeysData__, key);
  4584. if (index === -1) return;
  4585. return this.__mapValuesData__[index];
  4586. }),
  4587. has: d(function (key) {
  4588. return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
  4589. }),
  4590. keys: d(function () { return new Iterator(this, 'key'); }),
  4591. set: d(function (key, value) {
  4592. var index = eIndexOf.call(this.__mapKeysData__, key), emit;
  4593. if (index === -1) {
  4594. index = this.__mapKeysData__.push(key) - 1;
  4595. emit = true;
  4596. }
  4597. this.__mapValuesData__[index] = value;
  4598. if (emit) this.emit('_add', index, key);
  4599. return this;
  4600. }),
  4601. size: d.gs(function () { return this.__mapKeysData__.length; }),
  4602. values: d(function () { return new Iterator(this, 'value'); }),
  4603. toString: d(function () { return '[object Map]'; })
  4604. }));
  4605. Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
  4606. return this.entries();
  4607. }));
  4608. Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
  4609. },{"./is-native-implemented":66,"./lib/iterator":68,"d":15,"es5-ext/array/#/clear":17,"es5-ext/array/#/e-index-of":18,"es5-ext/object/set-prototype-of":48,"es5-ext/object/valid-callable":51,"es5-ext/object/valid-value":52,"es6-iterator/for-of":58,"es6-iterator/valid-iterable":63,"es6-symbol":70,"event-emitter":78}],70:[function(require,module,exports){
  4610. "use strict";
  4611. module.exports = require("./is-implemented")()
  4612. ? require("ext/global-this").Symbol
  4613. : require("./polyfill");
  4614. },{"./is-implemented":71,"./polyfill":76,"ext/global-this":81}],71:[function(require,module,exports){
  4615. "use strict";
  4616. var global = require("ext/global-this")
  4617. , validTypes = { object: true, symbol: true };
  4618. module.exports = function () {
  4619. var Symbol = global.Symbol;
  4620. var symbol;
  4621. if (typeof Symbol !== "function") return false;
  4622. symbol = Symbol("test symbol");
  4623. try { String(symbol); }
  4624. catch (e) { return false; }
  4625. // Return 'true' also for polyfills
  4626. if (!validTypes[typeof Symbol.iterator]) return false;
  4627. if (!validTypes[typeof Symbol.toPrimitive]) return false;
  4628. if (!validTypes[typeof Symbol.toStringTag]) return false;
  4629. return true;
  4630. };
  4631. },{"ext/global-this":81}],72:[function(require,module,exports){
  4632. "use strict";
  4633. module.exports = function (value) {
  4634. if (!value) return false;
  4635. if (typeof value === "symbol") return true;
  4636. if (!value.constructor) return false;
  4637. if (value.constructor.name !== "Symbol") return false;
  4638. return value[value.constructor.toStringTag] === "Symbol";
  4639. };
  4640. },{}],73:[function(require,module,exports){
  4641. "use strict";
  4642. var d = require("d");
  4643. var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype;
  4644. var created = create(null);
  4645. module.exports = function (desc) {
  4646. var postfix = 0, name, ie11BugWorkaround;
  4647. while (created[desc + (postfix || "")]) ++postfix;
  4648. desc += postfix || "";
  4649. created[desc] = true;
  4650. name = "@@" + desc;
  4651. defineProperty(
  4652. objPrototype,
  4653. name,
  4654. d.gs(null, function (value) {
  4655. // For IE11 issue see:
  4656. // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
  4657. // ie11-broken-getters-on-dom-objects
  4658. // https://github.com/medikoo/es6-symbol/issues/12
  4659. if (ie11BugWorkaround) return;
  4660. ie11BugWorkaround = true;
  4661. defineProperty(this, name, d(value));
  4662. ie11BugWorkaround = false;
  4663. })
  4664. );
  4665. return name;
  4666. };
  4667. },{"d":15}],74:[function(require,module,exports){
  4668. "use strict";
  4669. var d = require("d")
  4670. , NativeSymbol = require("ext/global-this").Symbol;
  4671. module.exports = function (SymbolPolyfill) {
  4672. return Object.defineProperties(SymbolPolyfill, {
  4673. // To ensure proper interoperability with other native functions (e.g. Array.from)
  4674. // fallback to eventual native implementation of given symbol
  4675. hasInstance: d(
  4676. "", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance")
  4677. ),
  4678. isConcatSpreadable: d(
  4679. "",
  4680. (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
  4681. SymbolPolyfill("isConcatSpreadable")
  4682. ),
  4683. iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")),
  4684. match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")),
  4685. replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")),
  4686. search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")),
  4687. species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")),
  4688. split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")),
  4689. toPrimitive: d(
  4690. "", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive")
  4691. ),
  4692. toStringTag: d(
  4693. "", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag")
  4694. ),
  4695. unscopables: d(
  4696. "", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables")
  4697. )
  4698. });
  4699. };
  4700. },{"d":15,"ext/global-this":81}],75:[function(require,module,exports){
  4701. "use strict";
  4702. var d = require("d")
  4703. , validateSymbol = require("../../../validate-symbol");
  4704. var registry = Object.create(null);
  4705. module.exports = function (SymbolPolyfill) {
  4706. return Object.defineProperties(SymbolPolyfill, {
  4707. for: d(function (key) {
  4708. if (registry[key]) return registry[key];
  4709. return (registry[key] = SymbolPolyfill(String(key)));
  4710. }),
  4711. keyFor: d(function (symbol) {
  4712. var key;
  4713. validateSymbol(symbol);
  4714. for (key in registry) {
  4715. if (registry[key] === symbol) return key;
  4716. }
  4717. return undefined;
  4718. })
  4719. });
  4720. };
  4721. },{"../../../validate-symbol":77,"d":15}],76:[function(require,module,exports){
  4722. // ES2015 Symbol polyfill for environments that do not (or partially) support it
  4723. "use strict";
  4724. var d = require("d")
  4725. , validateSymbol = require("./validate-symbol")
  4726. , NativeSymbol = require("ext/global-this").Symbol
  4727. , generateName = require("./lib/private/generate-name")
  4728. , setupStandardSymbols = require("./lib/private/setup/standard-symbols")
  4729. , setupSymbolRegistry = require("./lib/private/setup/symbol-registry");
  4730. var create = Object.create
  4731. , defineProperties = Object.defineProperties
  4732. , defineProperty = Object.defineProperty;
  4733. var SymbolPolyfill, HiddenSymbol, isNativeSafe;
  4734. if (typeof NativeSymbol === "function") {
  4735. try {
  4736. String(NativeSymbol());
  4737. isNativeSafe = true;
  4738. } catch (ignore) {}
  4739. } else {
  4740. NativeSymbol = null;
  4741. }
  4742. // Internal constructor (not one exposed) for creating Symbol instances.
  4743. // This one is used to ensure that `someSymbol instanceof Symbol` always return false
  4744. HiddenSymbol = function Symbol(description) {
  4745. if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor");
  4746. return SymbolPolyfill(description);
  4747. };
  4748. // Exposed `Symbol` constructor
  4749. // (returns instances of HiddenSymbol)
  4750. module.exports = SymbolPolyfill = function Symbol(description) {
  4751. var symbol;
  4752. if (this instanceof Symbol) throw new TypeError("Symbol is not a constructor");
  4753. if (isNativeSafe) return NativeSymbol(description);
  4754. symbol = create(HiddenSymbol.prototype);
  4755. description = description === undefined ? "" : String(description);
  4756. return defineProperties(symbol, {
  4757. __description__: d("", description),
  4758. __name__: d("", generateName(description))
  4759. });
  4760. };
  4761. setupStandardSymbols(SymbolPolyfill);
  4762. setupSymbolRegistry(SymbolPolyfill);
  4763. // Internal tweaks for real symbol producer
  4764. defineProperties(HiddenSymbol.prototype, {
  4765. constructor: d(SymbolPolyfill),
  4766. toString: d("", function () { return this.__name__; })
  4767. });
  4768. // Proper implementation of methods exposed on Symbol.prototype
  4769. // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
  4770. defineProperties(SymbolPolyfill.prototype, {
  4771. toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }),
  4772. valueOf: d(function () { return validateSymbol(this); })
  4773. });
  4774. defineProperty(
  4775. SymbolPolyfill.prototype,
  4776. SymbolPolyfill.toPrimitive,
  4777. d("", function () {
  4778. var symbol = validateSymbol(this);
  4779. if (typeof symbol === "symbol") return symbol;
  4780. return symbol.toString();
  4781. })
  4782. );
  4783. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol"));
  4784. // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
  4785. defineProperty(
  4786. HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
  4787. d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])
  4788. );
  4789. // Note: It's important to define `toPrimitive` as last one, as some implementations
  4790. // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
  4791. // And that may invoke error in definition flow:
  4792. // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
  4793. defineProperty(
  4794. HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
  4795. d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])
  4796. );
  4797. },{"./lib/private/generate-name":73,"./lib/private/setup/standard-symbols":74,"./lib/private/setup/symbol-registry":75,"./validate-symbol":77,"d":15,"ext/global-this":81}],77:[function(require,module,exports){
  4798. "use strict";
  4799. var isSymbol = require("./is-symbol");
  4800. module.exports = function (value) {
  4801. if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
  4802. return value;
  4803. };
  4804. },{"./is-symbol":72}],78:[function(require,module,exports){
  4805. 'use strict';
  4806. var d = require('d')
  4807. , callable = require('es5-ext/object/valid-callable')
  4808. , apply = Function.prototype.apply, call = Function.prototype.call
  4809. , create = Object.create, defineProperty = Object.defineProperty
  4810. , defineProperties = Object.defineProperties
  4811. , hasOwnProperty = Object.prototype.hasOwnProperty
  4812. , descriptor = { configurable: true, enumerable: false, writable: true }
  4813. , on, once, off, emit, methods, descriptors, base;
  4814. on = function (type, listener) {
  4815. var data;
  4816. callable(listener);
  4817. if (!hasOwnProperty.call(this, '__ee__')) {
  4818. data = descriptor.value = create(null);
  4819. defineProperty(this, '__ee__', descriptor);
  4820. descriptor.value = null;
  4821. } else {
  4822. data = this.__ee__;
  4823. }
  4824. if (!data[type]) data[type] = listener;
  4825. else if (typeof data[type] === 'object') data[type].push(listener);
  4826. else data[type] = [data[type], listener];
  4827. return this;
  4828. };
  4829. once = function (type, listener) {
  4830. var once, self;
  4831. callable(listener);
  4832. self = this;
  4833. on.call(this, type, once = function () {
  4834. off.call(self, type, once);
  4835. apply.call(listener, this, arguments);
  4836. });
  4837. once.__eeOnceListener__ = listener;
  4838. return this;
  4839. };
  4840. off = function (type, listener) {
  4841. var data, listeners, candidate, i;
  4842. callable(listener);
  4843. if (!hasOwnProperty.call(this, '__ee__')) return this;
  4844. data = this.__ee__;
  4845. if (!data[type]) return this;
  4846. listeners = data[type];
  4847. if (typeof listeners === 'object') {
  4848. for (i = 0; (candidate = listeners[i]); ++i) {
  4849. if ((candidate === listener) ||
  4850. (candidate.__eeOnceListener__ === listener)) {
  4851. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  4852. else listeners.splice(i, 1);
  4853. }
  4854. }
  4855. } else {
  4856. if ((listeners === listener) ||
  4857. (listeners.__eeOnceListener__ === listener)) {
  4858. delete data[type];
  4859. }
  4860. }
  4861. return this;
  4862. };
  4863. emit = function (type) {
  4864. var i, l, listener, listeners, args;
  4865. if (!hasOwnProperty.call(this, '__ee__')) return;
  4866. listeners = this.__ee__[type];
  4867. if (!listeners) return;
  4868. if (typeof listeners === 'object') {
  4869. l = arguments.length;
  4870. args = new Array(l - 1);
  4871. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  4872. listeners = listeners.slice();
  4873. for (i = 0; (listener = listeners[i]); ++i) {
  4874. apply.call(listener, this, args);
  4875. }
  4876. } else {
  4877. switch (arguments.length) {
  4878. case 1:
  4879. call.call(listeners, this);
  4880. break;
  4881. case 2:
  4882. call.call(listeners, this, arguments[1]);
  4883. break;
  4884. case 3:
  4885. call.call(listeners, this, arguments[1], arguments[2]);
  4886. break;
  4887. default:
  4888. l = arguments.length;
  4889. args = new Array(l - 1);
  4890. for (i = 1; i < l; ++i) {
  4891. args[i - 1] = arguments[i];
  4892. }
  4893. apply.call(listeners, this, args);
  4894. }
  4895. }
  4896. };
  4897. methods = {
  4898. on: on,
  4899. once: once,
  4900. off: off,
  4901. emit: emit
  4902. };
  4903. descriptors = {
  4904. on: d(on),
  4905. once: d(once),
  4906. off: d(off),
  4907. emit: d(emit)
  4908. };
  4909. base = defineProperties({}, descriptors);
  4910. module.exports = exports = function (o) {
  4911. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  4912. };
  4913. exports.methods = methods;
  4914. },{"d":15,"es5-ext/object/valid-callable":51}],79:[function(require,module,exports){
  4915. // Copyright Joyent, Inc. and other Node contributors.
  4916. //
  4917. // Permission is hereby granted, free of charge, to any person obtaining a
  4918. // copy of this software and associated documentation files (the
  4919. // "Software"), to deal in the Software without restriction, including
  4920. // without limitation the rights to use, copy, modify, merge, publish,
  4921. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4922. // persons to whom the Software is furnished to do so, subject to the
  4923. // following conditions:
  4924. //
  4925. // The above copyright notice and this permission notice shall be included
  4926. // in all copies or substantial portions of the Software.
  4927. //
  4928. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4929. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4930. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4931. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4932. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4933. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4934. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4935. var objectCreate = Object.create || objectCreatePolyfill
  4936. var objectKeys = Object.keys || objectKeysPolyfill
  4937. var bind = Function.prototype.bind || functionBindPolyfill
  4938. function EventEmitter() {
  4939. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  4940. this._events = objectCreate(null);
  4941. this._eventsCount = 0;
  4942. }
  4943. this._maxListeners = this._maxListeners || undefined;
  4944. }
  4945. module.exports = EventEmitter;
  4946. // Backwards-compat with node 0.10.x
  4947. EventEmitter.EventEmitter = EventEmitter;
  4948. EventEmitter.prototype._events = undefined;
  4949. EventEmitter.prototype._maxListeners = undefined;
  4950. // By default EventEmitters will print a warning if more than 10 listeners are
  4951. // added to it. This is a useful default which helps finding memory leaks.
  4952. var defaultMaxListeners = 10;
  4953. var hasDefineProperty;
  4954. try {
  4955. var o = {};
  4956. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  4957. hasDefineProperty = o.x === 0;
  4958. } catch (err) { hasDefineProperty = false }
  4959. if (hasDefineProperty) {
  4960. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  4961. enumerable: true,
  4962. get: function() {
  4963. return defaultMaxListeners;
  4964. },
  4965. set: function(arg) {
  4966. // check whether the input is a positive number (whose value is zero or
  4967. // greater and not a NaN).
  4968. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  4969. throw new TypeError('"defaultMaxListeners" must be a positive number');
  4970. defaultMaxListeners = arg;
  4971. }
  4972. });
  4973. } else {
  4974. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  4975. }
  4976. // Obviously not all Emitters should be limited to 10. This function allows
  4977. // that to be increased. Set to zero for unlimited.
  4978. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  4979. if (typeof n !== 'number' || n < 0 || isNaN(n))
  4980. throw new TypeError('"n" argument must be a positive number');
  4981. this._maxListeners = n;
  4982. return this;
  4983. };
  4984. function $getMaxListeners(that) {
  4985. if (that._maxListeners === undefined)
  4986. return EventEmitter.defaultMaxListeners;
  4987. return that._maxListeners;
  4988. }
  4989. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  4990. return $getMaxListeners(this);
  4991. };
  4992. // These standalone emit* functions are used to optimize calling of event
  4993. // handlers for fast cases because emit() itself often has a variable number of
  4994. // arguments and can be deoptimized because of that. These functions always have
  4995. // the same number of arguments and thus do not get deoptimized, so the code
  4996. // inside them can execute faster.
  4997. function emitNone(handler, isFn, self) {
  4998. if (isFn)
  4999. handler.call(self);
  5000. else {
  5001. var len = handler.length;
  5002. var listeners = arrayClone(handler, len);
  5003. for (var i = 0; i < len; ++i)
  5004. listeners[i].call(self);
  5005. }
  5006. }
  5007. function emitOne(handler, isFn, self, arg1) {
  5008. if (isFn)
  5009. handler.call(self, arg1);
  5010. else {
  5011. var len = handler.length;
  5012. var listeners = arrayClone(handler, len);
  5013. for (var i = 0; i < len; ++i)
  5014. listeners[i].call(self, arg1);
  5015. }
  5016. }
  5017. function emitTwo(handler, isFn, self, arg1, arg2) {
  5018. if (isFn)
  5019. handler.call(self, arg1, arg2);
  5020. else {
  5021. var len = handler.length;
  5022. var listeners = arrayClone(handler, len);
  5023. for (var i = 0; i < len; ++i)
  5024. listeners[i].call(self, arg1, arg2);
  5025. }
  5026. }
  5027. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  5028. if (isFn)
  5029. handler.call(self, arg1, arg2, arg3);
  5030. else {
  5031. var len = handler.length;
  5032. var listeners = arrayClone(handler, len);
  5033. for (var i = 0; i < len; ++i)
  5034. listeners[i].call(self, arg1, arg2, arg3);
  5035. }
  5036. }
  5037. function emitMany(handler, isFn, self, args) {
  5038. if (isFn)
  5039. handler.apply(self, args);
  5040. else {
  5041. var len = handler.length;
  5042. var listeners = arrayClone(handler, len);
  5043. for (var i = 0; i < len; ++i)
  5044. listeners[i].apply(self, args);
  5045. }
  5046. }
  5047. EventEmitter.prototype.emit = function emit(type) {
  5048. var er, handler, len, args, i, events;
  5049. var doError = (type === 'error');
  5050. events = this._events;
  5051. if (events)
  5052. doError = (doError && events.error == null);
  5053. else if (!doError)
  5054. return false;
  5055. // If there is no 'error' event listener then throw.
  5056. if (doError) {
  5057. if (arguments.length > 1)
  5058. er = arguments[1];
  5059. if (er instanceof Error) {
  5060. throw er; // Unhandled 'error' event
  5061. } else {
  5062. // At least give some kind of context to the user
  5063. var err = new Error('Unhandled "error" event. (' + er + ')');
  5064. err.context = er;
  5065. throw err;
  5066. }
  5067. return false;
  5068. }
  5069. handler = events[type];
  5070. if (!handler)
  5071. return false;
  5072. var isFn = typeof handler === 'function';
  5073. len = arguments.length;
  5074. switch (len) {
  5075. // fast cases
  5076. case 1:
  5077. emitNone(handler, isFn, this);
  5078. break;
  5079. case 2:
  5080. emitOne(handler, isFn, this, arguments[1]);
  5081. break;
  5082. case 3:
  5083. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  5084. break;
  5085. case 4:
  5086. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  5087. break;
  5088. // slower
  5089. default:
  5090. args = new Array(len - 1);
  5091. for (i = 1; i < len; i++)
  5092. args[i - 1] = arguments[i];
  5093. emitMany(handler, isFn, this, args);
  5094. }
  5095. return true;
  5096. };
  5097. function _addListener(target, type, listener, prepend) {
  5098. var m;
  5099. var events;
  5100. var existing;
  5101. if (typeof listener !== 'function')
  5102. throw new TypeError('"listener" argument must be a function');
  5103. events = target._events;
  5104. if (!events) {
  5105. events = target._events = objectCreate(null);
  5106. target._eventsCount = 0;
  5107. } else {
  5108. // To avoid recursion in the case that type === "newListener"! Before
  5109. // adding it to the listeners, first emit "newListener".
  5110. if (events.newListener) {
  5111. target.emit('newListener', type,
  5112. listener.listener ? listener.listener : listener);
  5113. // Re-assign `events` because a newListener handler could have caused the
  5114. // this._events to be assigned to a new object
  5115. events = target._events;
  5116. }
  5117. existing = events[type];
  5118. }
  5119. if (!existing) {
  5120. // Optimize the case of one listener. Don't need the extra array object.
  5121. existing = events[type] = listener;
  5122. ++target._eventsCount;
  5123. } else {
  5124. if (typeof existing === 'function') {
  5125. // Adding the second element, need to change to array.
  5126. existing = events[type] =
  5127. prepend ? [listener, existing] : [existing, listener];
  5128. } else {
  5129. // If we've already got an array, just append.
  5130. if (prepend) {
  5131. existing.unshift(listener);
  5132. } else {
  5133. existing.push(listener);
  5134. }
  5135. }
  5136. // Check for listener leak
  5137. if (!existing.warned) {
  5138. m = $getMaxListeners(target);
  5139. if (m && m > 0 && existing.length > m) {
  5140. existing.warned = true;
  5141. var w = new Error('Possible EventEmitter memory leak detected. ' +
  5142. existing.length + ' "' + String(type) + '" listeners ' +
  5143. 'added. Use emitter.setMaxListeners() to ' +
  5144. 'increase limit.');
  5145. w.name = 'MaxListenersExceededWarning';
  5146. w.emitter = target;
  5147. w.type = type;
  5148. w.count = existing.length;
  5149. if (typeof console === 'object' && console.warn) {
  5150. console.warn('%s: %s', w.name, w.message);
  5151. }
  5152. }
  5153. }
  5154. }
  5155. return target;
  5156. }
  5157. EventEmitter.prototype.addListener = function addListener(type, listener) {
  5158. return _addListener(this, type, listener, false);
  5159. };
  5160. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  5161. EventEmitter.prototype.prependListener =
  5162. function prependListener(type, listener) {
  5163. return _addListener(this, type, listener, true);
  5164. };
  5165. function onceWrapper() {
  5166. if (!this.fired) {
  5167. this.target.removeListener(this.type, this.wrapFn);
  5168. this.fired = true;
  5169. switch (arguments.length) {
  5170. case 0:
  5171. return this.listener.call(this.target);
  5172. case 1:
  5173. return this.listener.call(this.target, arguments[0]);
  5174. case 2:
  5175. return this.listener.call(this.target, arguments[0], arguments[1]);
  5176. case 3:
  5177. return this.listener.call(this.target, arguments[0], arguments[1],
  5178. arguments[2]);
  5179. default:
  5180. var args = new Array(arguments.length);
  5181. for (var i = 0; i < args.length; ++i)
  5182. args[i] = arguments[i];
  5183. this.listener.apply(this.target, args);
  5184. }
  5185. }
  5186. }
  5187. function _onceWrap(target, type, listener) {
  5188. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  5189. var wrapped = bind.call(onceWrapper, state);
  5190. wrapped.listener = listener;
  5191. state.wrapFn = wrapped;
  5192. return wrapped;
  5193. }
  5194. EventEmitter.prototype.once = function once(type, listener) {
  5195. if (typeof listener !== 'function')
  5196. throw new TypeError('"listener" argument must be a function');
  5197. this.on(type, _onceWrap(this, type, listener));
  5198. return this;
  5199. };
  5200. EventEmitter.prototype.prependOnceListener =
  5201. function prependOnceListener(type, listener) {
  5202. if (typeof listener !== 'function')
  5203. throw new TypeError('"listener" argument must be a function');
  5204. this.prependListener(type, _onceWrap(this, type, listener));
  5205. return this;
  5206. };
  5207. // Emits a 'removeListener' event if and only if the listener was removed.
  5208. EventEmitter.prototype.removeListener =
  5209. function removeListener(type, listener) {
  5210. var list, events, position, i, originalListener;
  5211. if (typeof listener !== 'function')
  5212. throw new TypeError('"listener" argument must be a function');
  5213. events = this._events;
  5214. if (!events)
  5215. return this;
  5216. list = events[type];
  5217. if (!list)
  5218. return this;
  5219. if (list === listener || list.listener === listener) {
  5220. if (--this._eventsCount === 0)
  5221. this._events = objectCreate(null);
  5222. else {
  5223. delete events[type];
  5224. if (events.removeListener)
  5225. this.emit('removeListener', type, list.listener || listener);
  5226. }
  5227. } else if (typeof list !== 'function') {
  5228. position = -1;
  5229. for (i = list.length - 1; i >= 0; i--) {
  5230. if (list[i] === listener || list[i].listener === listener) {
  5231. originalListener = list[i].listener;
  5232. position = i;
  5233. break;
  5234. }
  5235. }
  5236. if (position < 0)
  5237. return this;
  5238. if (position === 0)
  5239. list.shift();
  5240. else
  5241. spliceOne(list, position);
  5242. if (list.length === 1)
  5243. events[type] = list[0];
  5244. if (events.removeListener)
  5245. this.emit('removeListener', type, originalListener || listener);
  5246. }
  5247. return this;
  5248. };
  5249. EventEmitter.prototype.removeAllListeners =
  5250. function removeAllListeners(type) {
  5251. var listeners, events, i;
  5252. events = this._events;
  5253. if (!events)
  5254. return this;
  5255. // not listening for removeListener, no need to emit
  5256. if (!events.removeListener) {
  5257. if (arguments.length === 0) {
  5258. this._events = objectCreate(null);
  5259. this._eventsCount = 0;
  5260. } else if (events[type]) {
  5261. if (--this._eventsCount === 0)
  5262. this._events = objectCreate(null);
  5263. else
  5264. delete events[type];
  5265. }
  5266. return this;
  5267. }
  5268. // emit removeListener for all listeners on all events
  5269. if (arguments.length === 0) {
  5270. var keys = objectKeys(events);
  5271. var key;
  5272. for (i = 0; i < keys.length; ++i) {
  5273. key = keys[i];
  5274. if (key === 'removeListener') continue;
  5275. this.removeAllListeners(key);
  5276. }
  5277. this.removeAllListeners('removeListener');
  5278. this._events = objectCreate(null);
  5279. this._eventsCount = 0;
  5280. return this;
  5281. }
  5282. listeners = events[type];
  5283. if (typeof listeners === 'function') {
  5284. this.removeListener(type, listeners);
  5285. } else if (listeners) {
  5286. // LIFO order
  5287. for (i = listeners.length - 1; i >= 0; i--) {
  5288. this.removeListener(type, listeners[i]);
  5289. }
  5290. }
  5291. return this;
  5292. };
  5293. function _listeners(target, type, unwrap) {
  5294. var events = target._events;
  5295. if (!events)
  5296. return [];
  5297. var evlistener = events[type];
  5298. if (!evlistener)
  5299. return [];
  5300. if (typeof evlistener === 'function')
  5301. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  5302. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  5303. }
  5304. EventEmitter.prototype.listeners = function listeners(type) {
  5305. return _listeners(this, type, true);
  5306. };
  5307. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  5308. return _listeners(this, type, false);
  5309. };
  5310. EventEmitter.listenerCount = function(emitter, type) {
  5311. if (typeof emitter.listenerCount === 'function') {
  5312. return emitter.listenerCount(type);
  5313. } else {
  5314. return listenerCount.call(emitter, type);
  5315. }
  5316. };
  5317. EventEmitter.prototype.listenerCount = listenerCount;
  5318. function listenerCount(type) {
  5319. var events = this._events;
  5320. if (events) {
  5321. var evlistener = events[type];
  5322. if (typeof evlistener === 'function') {
  5323. return 1;
  5324. } else if (evlistener) {
  5325. return evlistener.length;
  5326. }
  5327. }
  5328. return 0;
  5329. }
  5330. EventEmitter.prototype.eventNames = function eventNames() {
  5331. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  5332. };
  5333. // About 1.5x faster than the two-arg version of Array#splice().
  5334. function spliceOne(list, index) {
  5335. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  5336. list[i] = list[k];
  5337. list.pop();
  5338. }
  5339. function arrayClone(arr, n) {
  5340. var copy = new Array(n);
  5341. for (var i = 0; i < n; ++i)
  5342. copy[i] = arr[i];
  5343. return copy;
  5344. }
  5345. function unwrapListeners(arr) {
  5346. var ret = new Array(arr.length);
  5347. for (var i = 0; i < ret.length; ++i) {
  5348. ret[i] = arr[i].listener || arr[i];
  5349. }
  5350. return ret;
  5351. }
  5352. function objectCreatePolyfill(proto) {
  5353. var F = function() {};
  5354. F.prototype = proto;
  5355. return new F;
  5356. }
  5357. function objectKeysPolyfill(obj) {
  5358. var keys = [];
  5359. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  5360. keys.push(k);
  5361. }
  5362. return k;
  5363. }
  5364. function functionBindPolyfill(context) {
  5365. var fn = this;
  5366. return function () {
  5367. return fn.apply(context, arguments);
  5368. };
  5369. }
  5370. },{}],80:[function(require,module,exports){
  5371. var naiveFallback = function () {
  5372. if (typeof self === "object" && self) return self;
  5373. if (typeof window === "object" && window) return window;
  5374. throw new Error("Unable to resolve global `this`");
  5375. };
  5376. module.exports = (function () {
  5377. if (this) return this;
  5378. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  5379. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  5380. // In all ES5+ engines global object inherits from Object.prototype
  5381. // (if you approached one that doesn't please report)
  5382. try {
  5383. Object.defineProperty(Object.prototype, "__global__", {
  5384. get: function () { return this; },
  5385. configurable: true
  5386. });
  5387. } catch (error) {
  5388. // Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze)
  5389. return naiveFallback();
  5390. }
  5391. try {
  5392. // Safari case (window.__global__ is resolved with global context, but __global__ does not)
  5393. if (!__global__) return naiveFallback();
  5394. return __global__;
  5395. } finally {
  5396. delete Object.prototype.__global__;
  5397. }
  5398. })();
  5399. },{}],81:[function(require,module,exports){
  5400. "use strict";
  5401. module.exports = require("./is-implemented")() ? globalThis : require("./implementation");
  5402. },{"./implementation":80,"./is-implemented":82}],82:[function(require,module,exports){
  5403. "use strict";
  5404. module.exports = function () {
  5405. if (typeof globalThis !== "object") return false;
  5406. if (!globalThis) return false;
  5407. return globalThis.Array === Array;
  5408. };
  5409. },{}],83:[function(require,module,exports){
  5410. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  5411. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5412. var e, m
  5413. var eLen = (nBytes * 8) - mLen - 1
  5414. var eMax = (1 << eLen) - 1
  5415. var eBias = eMax >> 1
  5416. var nBits = -7
  5417. var i = isLE ? (nBytes - 1) : 0
  5418. var d = isLE ? -1 : 1
  5419. var s = buffer[offset + i]
  5420. i += d
  5421. e = s & ((1 << (-nBits)) - 1)
  5422. s >>= (-nBits)
  5423. nBits += eLen
  5424. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5425. m = e & ((1 << (-nBits)) - 1)
  5426. e >>= (-nBits)
  5427. nBits += mLen
  5428. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5429. if (e === 0) {
  5430. e = 1 - eBias
  5431. } else if (e === eMax) {
  5432. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5433. } else {
  5434. m = m + Math.pow(2, mLen)
  5435. e = e - eBias
  5436. }
  5437. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5438. }
  5439. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5440. var e, m, c
  5441. var eLen = (nBytes * 8) - mLen - 1
  5442. var eMax = (1 << eLen) - 1
  5443. var eBias = eMax >> 1
  5444. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5445. var i = isLE ? 0 : (nBytes - 1)
  5446. var d = isLE ? 1 : -1
  5447. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5448. value = Math.abs(value)
  5449. if (isNaN(value) || value === Infinity) {
  5450. m = isNaN(value) ? 1 : 0
  5451. e = eMax
  5452. } else {
  5453. e = Math.floor(Math.log(value) / Math.LN2)
  5454. if (value * (c = Math.pow(2, -e)) < 1) {
  5455. e--
  5456. c *= 2
  5457. }
  5458. if (e + eBias >= 1) {
  5459. value += rt / c
  5460. } else {
  5461. value += rt * Math.pow(2, 1 - eBias)
  5462. }
  5463. if (value * c >= 2) {
  5464. e++
  5465. c /= 2
  5466. }
  5467. if (e + eBias >= eMax) {
  5468. m = 0
  5469. e = eMax
  5470. } else if (e + eBias >= 1) {
  5471. m = ((value * c) - 1) * Math.pow(2, mLen)
  5472. e = e + eBias
  5473. } else {
  5474. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5475. e = 0
  5476. }
  5477. }
  5478. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5479. e = (e << mLen) | m
  5480. eLen += mLen
  5481. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5482. buffer[offset + i - d] |= s * 128
  5483. }
  5484. },{}],84:[function(require,module,exports){
  5485. if (typeof Object.create === 'function') {
  5486. // implementation from standard node.js 'util' module
  5487. module.exports = function inherits(ctor, superCtor) {
  5488. if (superCtor) {
  5489. ctor.super_ = superCtor
  5490. ctor.prototype = Object.create(superCtor.prototype, {
  5491. constructor: {
  5492. value: ctor,
  5493. enumerable: false,
  5494. writable: true,
  5495. configurable: true
  5496. }
  5497. })
  5498. }
  5499. };
  5500. } else {
  5501. // old school shim for old browsers
  5502. module.exports = function inherits(ctor, superCtor) {
  5503. if (superCtor) {
  5504. ctor.super_ = superCtor
  5505. var TempCtor = function () {}
  5506. TempCtor.prototype = superCtor.prototype
  5507. ctor.prototype = new TempCtor()
  5508. ctor.prototype.constructor = ctor
  5509. }
  5510. }
  5511. }
  5512. },{}],85:[function(require,module,exports){
  5513. /*!
  5514. * Determine if an object is a Buffer
  5515. *
  5516. * @author Feross Aboukhadijeh <https://feross.org>
  5517. * @license MIT
  5518. */
  5519. // The _isBuffer check is for Safari 5-7 support, because it's missing
  5520. // Object.prototype.constructor. Remove this eventually
  5521. module.exports = function (obj) {
  5522. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  5523. }
  5524. function isBuffer (obj) {
  5525. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  5526. }
  5527. // For Node v0.10 support. Remove this eventually.
  5528. function isSlowBuffer (obj) {
  5529. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  5530. }
  5531. },{}],86:[function(require,module,exports){
  5532. var toString = {}.toString;
  5533. module.exports = Array.isArray || function (arr) {
  5534. return toString.call(arr) == '[object Array]';
  5535. };
  5536. },{}],87:[function(require,module,exports){
  5537. 'use strict'
  5538. var Buffer = require('safe-buffer').Buffer
  5539. /* Protocol - protocol constants */
  5540. var protocol = module.exports
  5541. /* Command code => mnemonic */
  5542. protocol.types = {
  5543. 0: 'reserved',
  5544. 1: 'connect',
  5545. 2: 'connack',
  5546. 3: 'publish',
  5547. 4: 'puback',
  5548. 5: 'pubrec',
  5549. 6: 'pubrel',
  5550. 7: 'pubcomp',
  5551. 8: 'subscribe',
  5552. 9: 'suback',
  5553. 10: 'unsubscribe',
  5554. 11: 'unsuback',
  5555. 12: 'pingreq',
  5556. 13: 'pingresp',
  5557. 14: 'disconnect',
  5558. 15: 'reserved'
  5559. }
  5560. /* Mnemonic => Command code */
  5561. protocol.codes = {}
  5562. for (var k in protocol.types) {
  5563. var v = protocol.types[k]
  5564. protocol.codes[v] = k
  5565. }
  5566. /* Header */
  5567. protocol.CMD_SHIFT = 4
  5568. protocol.CMD_MASK = 0xF0
  5569. protocol.DUP_MASK = 0x08
  5570. protocol.QOS_MASK = 0x03
  5571. protocol.QOS_SHIFT = 1
  5572. protocol.RETAIN_MASK = 0x01
  5573. /* Length */
  5574. protocol.LENGTH_MASK = 0x7F
  5575. protocol.LENGTH_FIN_MASK = 0x80
  5576. /* Connack */
  5577. protocol.SESSIONPRESENT_MASK = 0x01
  5578. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  5579. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  5580. /* Connect */
  5581. protocol.USERNAME_MASK = 0x80
  5582. protocol.PASSWORD_MASK = 0x40
  5583. protocol.WILL_RETAIN_MASK = 0x20
  5584. protocol.WILL_QOS_MASK = 0x18
  5585. protocol.WILL_QOS_SHIFT = 3
  5586. protocol.WILL_FLAG_MASK = 0x04
  5587. protocol.CLEAN_SESSION_MASK = 0x02
  5588. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  5589. function genHeader (type) {
  5590. return [0, 1, 2].map(function (qos) {
  5591. return [0, 1].map(function (dup) {
  5592. return [0, 1].map(function (retain) {
  5593. var buf = new Buffer(1)
  5594. buf.writeUInt8(
  5595. protocol.codes[type] << protocol.CMD_SHIFT |
  5596. (dup ? protocol.DUP_MASK : 0) |
  5597. qos << protocol.QOS_SHIFT | retain, 0, true)
  5598. return buf
  5599. })
  5600. })
  5601. })
  5602. }
  5603. /* Publish */
  5604. protocol.PUBLISH_HEADER = genHeader('publish')
  5605. /* Subscribe */
  5606. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  5607. /* Unsubscribe */
  5608. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  5609. /* Confirmations */
  5610. protocol.ACKS = {
  5611. unsuback: genHeader('unsuback'),
  5612. puback: genHeader('puback'),
  5613. pubcomp: genHeader('pubcomp'),
  5614. pubrel: genHeader('pubrel'),
  5615. pubrec: genHeader('pubrec')
  5616. }
  5617. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  5618. /* Protocol versions */
  5619. protocol.VERSION3 = Buffer.from([3])
  5620. protocol.VERSION4 = Buffer.from([4])
  5621. /* QoS */
  5622. protocol.QOS = [0, 1, 2].map(function (qos) {
  5623. return Buffer.from([qos])
  5624. })
  5625. /* Empty packets */
  5626. protocol.EMPTY = {
  5627. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  5628. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  5629. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  5630. }
  5631. },{"safe-buffer":114}],88:[function(require,module,exports){
  5632. 'use strict'
  5633. var Buffer = require('safe-buffer').Buffer
  5634. var writeToStream = require('./writeToStream')
  5635. var EE = require('events').EventEmitter
  5636. var inherits = require('inherits')
  5637. function generate (packet) {
  5638. var stream = new Accumulator()
  5639. writeToStream(packet, stream)
  5640. return stream.concat()
  5641. }
  5642. function Accumulator () {
  5643. this._array = new Array(20)
  5644. this._i = 0
  5645. }
  5646. inherits(Accumulator, EE)
  5647. Accumulator.prototype.write = function (chunk) {
  5648. this._array[this._i++] = chunk
  5649. return true
  5650. }
  5651. Accumulator.prototype.concat = function () {
  5652. var length = 0
  5653. var lengths = new Array(this._array.length)
  5654. var list = this._array
  5655. var pos = 0
  5656. var i
  5657. var result
  5658. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  5659. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  5660. else lengths[i] = Buffer.byteLength(list[i])
  5661. length += lengths[i]
  5662. }
  5663. result = Buffer.allocUnsafe(length)
  5664. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  5665. if (typeof list[i] !== 'string') {
  5666. list[i].copy(result, pos)
  5667. pos += lengths[i]
  5668. } else {
  5669. result.write(list[i], pos)
  5670. pos += lengths[i]
  5671. }
  5672. }
  5673. return result
  5674. }
  5675. module.exports = generate
  5676. },{"./writeToStream":93,"events":79,"inherits":84,"safe-buffer":114}],89:[function(require,module,exports){
  5677. 'use strict'
  5678. exports.parser = require('./parser')
  5679. exports.generate = require('./generate')
  5680. exports.writeToStream = require('./writeToStream')
  5681. },{"./generate":88,"./parser":92,"./writeToStream":93}],90:[function(require,module,exports){
  5682. 'use strict'
  5683. var Buffer = require('safe-buffer').Buffer
  5684. var max = 65536
  5685. var cache = {}
  5686. function generateBuffer (i) {
  5687. var buffer = Buffer.allocUnsafe(2)
  5688. buffer.writeUInt8(i >> 8, 0)
  5689. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  5690. return buffer
  5691. }
  5692. function generateCache () {
  5693. for (var i = 0; i < max; i++) {
  5694. cache[i] = generateBuffer(i)
  5695. }
  5696. }
  5697. module.exports = {
  5698. cache: cache,
  5699. generateCache: generateCache,
  5700. generateNumber: generateBuffer
  5701. }
  5702. },{"safe-buffer":114}],91:[function(require,module,exports){
  5703. function Packet () {
  5704. this.cmd = null
  5705. this.retain = false
  5706. this.qos = 0
  5707. this.dup = false
  5708. this.length = -1
  5709. this.topic = null
  5710. this.payload = null
  5711. }
  5712. module.exports = Packet
  5713. },{}],92:[function(require,module,exports){
  5714. 'use strict'
  5715. var bl = require('bl')
  5716. var inherits = require('inherits')
  5717. var EE = require('events').EventEmitter
  5718. var Packet = require('./packet')
  5719. var constants = require('./constants')
  5720. function Parser () {
  5721. if (!(this instanceof Parser)) return new Parser()
  5722. this._states = [
  5723. '_parseHeader',
  5724. '_parseLength',
  5725. '_parsePayload',
  5726. '_newPacket'
  5727. ]
  5728. this._resetState()
  5729. }
  5730. inherits(Parser, EE)
  5731. Parser.prototype._resetState = function () {
  5732. this.packet = new Packet()
  5733. this.error = null
  5734. this._list = bl()
  5735. this._stateCounter = 0
  5736. }
  5737. Parser.prototype.parse = function (buf) {
  5738. if (this.error) this._resetState()
  5739. this._list.append(buf)
  5740. while ((this.packet.length !== -1 || this._list.length > 0) &&
  5741. this[this._states[this._stateCounter]]() &&
  5742. !this.error) {
  5743. this._stateCounter++
  5744. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  5745. }
  5746. return this._list.length
  5747. }
  5748. Parser.prototype._parseHeader = function () {
  5749. // There is at least one byte in the buffer
  5750. var zero = this._list.readUInt8(0)
  5751. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  5752. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  5753. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  5754. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  5755. this._list.consume(1)
  5756. return true
  5757. }
  5758. Parser.prototype._parseLength = function () {
  5759. // There is at least one byte in the list
  5760. var bytes = 0
  5761. var mul = 1
  5762. var length = 0
  5763. var result = true
  5764. var current
  5765. while (bytes < 5) {
  5766. current = this._list.readUInt8(bytes++)
  5767. length += mul * (current & constants.LENGTH_MASK)
  5768. mul *= 0x80
  5769. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  5770. if (this._list.length <= bytes) {
  5771. result = false
  5772. break
  5773. }
  5774. }
  5775. if (result) {
  5776. this.packet.length = length
  5777. this._list.consume(bytes)
  5778. }
  5779. return result
  5780. }
  5781. Parser.prototype._parsePayload = function () {
  5782. var result = false
  5783. // Do we have a payload? Do we have enough data to complete the payload?
  5784. // PINGs have no payload
  5785. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  5786. this._pos = 0
  5787. switch (this.packet.cmd) {
  5788. case 'connect':
  5789. this._parseConnect()
  5790. break
  5791. case 'connack':
  5792. this._parseConnack()
  5793. break
  5794. case 'publish':
  5795. this._parsePublish()
  5796. break
  5797. case 'puback':
  5798. case 'pubrec':
  5799. case 'pubrel':
  5800. case 'pubcomp':
  5801. this._parseMessageId()
  5802. break
  5803. case 'subscribe':
  5804. this._parseSubscribe()
  5805. break
  5806. case 'suback':
  5807. this._parseSuback()
  5808. break
  5809. case 'unsubscribe':
  5810. this._parseUnsubscribe()
  5811. break
  5812. case 'unsuback':
  5813. this._parseUnsuback()
  5814. break
  5815. case 'pingreq':
  5816. case 'pingresp':
  5817. case 'disconnect':
  5818. // These are empty, nothing to do
  5819. break
  5820. default:
  5821. this._emitError(new Error('Not supported'))
  5822. }
  5823. result = true
  5824. }
  5825. return result
  5826. }
  5827. Parser.prototype._parseConnect = function () {
  5828. var protocolId // Protocol ID
  5829. var clientId // Client ID
  5830. var topic // Will topic
  5831. var payload // Will payload
  5832. var password // Password
  5833. var username // Username
  5834. var flags = {}
  5835. var packet = this.packet
  5836. // Parse protocolId
  5837. protocolId = this._parseString()
  5838. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  5839. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  5840. return this._emitError(new Error('Invalid protocolId'))
  5841. }
  5842. packet.protocolId = protocolId
  5843. // Parse constants version number
  5844. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  5845. packet.protocolVersion = this._list.readUInt8(this._pos)
  5846. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4) {
  5847. return this._emitError(new Error('Invalid protocol version'))
  5848. }
  5849. this._pos++
  5850. if (this._pos >= this._list.length) {
  5851. return this._emitError(new Error('Packet too short'))
  5852. }
  5853. // Parse connect flags
  5854. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  5855. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  5856. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  5857. if (flags.will) {
  5858. packet.will = {}
  5859. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  5860. packet.will.qos = (this._list.readUInt8(this._pos) &
  5861. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  5862. }
  5863. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  5864. this._pos++
  5865. // Parse keepalive
  5866. packet.keepalive = this._parseNum()
  5867. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  5868. // Parse clientId
  5869. clientId = this._parseString()
  5870. if (clientId === null) return this._emitError(new Error('Packet too short'))
  5871. packet.clientId = clientId
  5872. if (flags.will) {
  5873. // Parse will topic
  5874. topic = this._parseString()
  5875. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  5876. packet.will.topic = topic
  5877. // Parse will payload
  5878. payload = this._parseBuffer()
  5879. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  5880. packet.will.payload = payload
  5881. }
  5882. // Parse username
  5883. if (flags.username) {
  5884. username = this._parseString()
  5885. if (username === null) return this._emitError(new Error('Cannot parse username'))
  5886. packet.username = username
  5887. }
  5888. // Parse password
  5889. if (flags.password) {
  5890. password = this._parseBuffer()
  5891. if (password === null) return this._emitError(new Error('Cannot parse password'))
  5892. packet.password = password
  5893. }
  5894. return packet
  5895. }
  5896. Parser.prototype._parseConnack = function () {
  5897. var packet = this.packet
  5898. if (this._list.length < 2) return null
  5899. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  5900. packet.returnCode = this._list.readUInt8(this._pos)
  5901. if (packet.returnCode === -1) return this._emitError(new Error('Cannot parse return code'))
  5902. }
  5903. Parser.prototype._parsePublish = function () {
  5904. var packet = this.packet
  5905. packet.topic = this._parseString()
  5906. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  5907. // Parse messageId
  5908. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  5909. packet.payload = this._list.slice(this._pos, packet.length)
  5910. }
  5911. Parser.prototype._parseSubscribe = function () {
  5912. var packet = this.packet
  5913. var topic
  5914. var qos
  5915. if (packet.qos !== 1) {
  5916. return this._emitError(new Error('Wrong subscribe header'))
  5917. }
  5918. packet.subscriptions = []
  5919. if (!this._parseMessageId()) { return }
  5920. while (this._pos < packet.length) {
  5921. // Parse topic
  5922. topic = this._parseString()
  5923. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  5924. if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload'))
  5925. qos = this._list.readUInt8(this._pos++)
  5926. // Push pair to subscriptions
  5927. packet.subscriptions.push({ topic: topic, qos: qos })
  5928. }
  5929. }
  5930. Parser.prototype._parseSuback = function () {
  5931. this.packet.granted = []
  5932. if (!this._parseMessageId()) { return }
  5933. // Parse granted QoSes
  5934. while (this._pos < this.packet.length) {
  5935. this.packet.granted.push(this._list.readUInt8(this._pos++))
  5936. }
  5937. }
  5938. Parser.prototype._parseUnsubscribe = function () {
  5939. var packet = this.packet
  5940. packet.unsubscriptions = []
  5941. // Parse messageId
  5942. if (!this._parseMessageId()) { return }
  5943. while (this._pos < packet.length) {
  5944. var topic
  5945. // Parse topic
  5946. topic = this._parseString()
  5947. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  5948. // Push topic to unsubscriptions
  5949. packet.unsubscriptions.push(topic)
  5950. }
  5951. }
  5952. Parser.prototype._parseUnsuback = function () {
  5953. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  5954. }
  5955. Parser.prototype._parseMessageId = function () {
  5956. var packet = this.packet
  5957. packet.messageId = this._parseNum()
  5958. if (packet.messageId === null) {
  5959. this._emitError(new Error('Cannot parse messageId'))
  5960. return false
  5961. }
  5962. return true
  5963. }
  5964. Parser.prototype._parseString = function (maybeBuffer) {
  5965. var length = this._parseNum()
  5966. var result
  5967. var end = length + this._pos
  5968. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  5969. result = this._list.toString('utf8', this._pos, end)
  5970. this._pos += length
  5971. return result
  5972. }
  5973. Parser.prototype._parseBuffer = function () {
  5974. var length = this._parseNum()
  5975. var result
  5976. var end = length + this._pos
  5977. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  5978. result = this._list.slice(this._pos, end)
  5979. this._pos += length
  5980. return result
  5981. }
  5982. Parser.prototype._parseNum = function () {
  5983. if (this._list.length - this._pos < 2) return -1
  5984. var result = this._list.readUInt16BE(this._pos)
  5985. this._pos += 2
  5986. return result
  5987. }
  5988. Parser.prototype._newPacket = function () {
  5989. if (this.packet) {
  5990. this._list.consume(this.packet.length)
  5991. this.emit('packet', this.packet)
  5992. }
  5993. this.packet = new Packet()
  5994. return true
  5995. }
  5996. Parser.prototype._emitError = function (err) {
  5997. this.error = err
  5998. this.emit('error', err)
  5999. }
  6000. module.exports = Parser
  6001. },{"./constants":87,"./packet":91,"bl":10,"events":79,"inherits":84}],93:[function(require,module,exports){
  6002. 'use strict'
  6003. var protocol = require('./constants')
  6004. var Buffer = require('safe-buffer').Buffer
  6005. var empty = Buffer.allocUnsafe(0)
  6006. var zeroBuf = Buffer.from([0])
  6007. var numbers = require('./numbers')
  6008. var nextTick = require('process-nextick-args').nextTick
  6009. var numCache = numbers.cache
  6010. var generateNumber = numbers.generateNumber
  6011. var generateCache = numbers.generateCache
  6012. var writeNumber = writeNumberCached
  6013. var toGenerate = true
  6014. function generate (packet, stream) {
  6015. if (stream.cork) {
  6016. stream.cork()
  6017. nextTick(uncork, stream)
  6018. }
  6019. if (toGenerate) {
  6020. toGenerate = false
  6021. generateCache()
  6022. }
  6023. switch (packet.cmd) {
  6024. case 'connect':
  6025. return connect(packet, stream)
  6026. case 'connack':
  6027. return connack(packet, stream)
  6028. case 'publish':
  6029. return publish(packet, stream)
  6030. case 'puback':
  6031. case 'pubrec':
  6032. case 'pubrel':
  6033. case 'pubcomp':
  6034. case 'unsuback':
  6035. return confirmation(packet, stream)
  6036. case 'subscribe':
  6037. return subscribe(packet, stream)
  6038. case 'suback':
  6039. return suback(packet, stream)
  6040. case 'unsubscribe':
  6041. return unsubscribe(packet, stream)
  6042. case 'pingreq':
  6043. case 'pingresp':
  6044. case 'disconnect':
  6045. return emptyPacket(packet, stream)
  6046. default:
  6047. stream.emit('error', new Error('Unknown command'))
  6048. return false
  6049. }
  6050. }
  6051. /**
  6052. * Controls numbers cache.
  6053. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  6054. */
  6055. Object.defineProperty(generate, 'cacheNumbers', {
  6056. get: function () {
  6057. return writeNumber === writeNumberCached
  6058. },
  6059. set: function (value) {
  6060. if (value) {
  6061. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  6062. writeNumber = writeNumberCached
  6063. } else {
  6064. toGenerate = false
  6065. writeNumber = writeNumberGenerated
  6066. }
  6067. }
  6068. })
  6069. function uncork (stream) {
  6070. stream.uncork()
  6071. }
  6072. function connect (opts, stream) {
  6073. var settings = opts || {}
  6074. var protocolId = settings.protocolId || 'MQTT'
  6075. var protocolVersion = settings.protocolVersion || 4
  6076. var will = settings.will
  6077. var clean = settings.clean
  6078. var keepalive = settings.keepalive || 0
  6079. var clientId = settings.clientId || ''
  6080. var username = settings.username
  6081. var password = settings.password
  6082. if (clean === undefined) clean = true
  6083. var length = 0
  6084. // Must be a string and non-falsy
  6085. if (!protocolId ||
  6086. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  6087. stream.emit('error', new Error('Invalid protocolId'))
  6088. return false
  6089. } else length += protocolId.length + 2
  6090. // Must be 3 or 4
  6091. if (protocolVersion !== 3 && protocolVersion !== 4) {
  6092. stream.emit('error', new Error('Invalid protocol version'))
  6093. return false
  6094. } else length += 1
  6095. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  6096. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  6097. (clientId || protocolVersion === 4) && (clientId || clean)) {
  6098. length += clientId.length + 2
  6099. } else {
  6100. if (protocolVersion < 4) {
  6101. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  6102. return false
  6103. }
  6104. if ((clean * 1) === 0) {
  6105. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  6106. return false
  6107. }
  6108. }
  6109. // Must be a two byte number
  6110. if (typeof keepalive !== 'number' ||
  6111. keepalive < 0 ||
  6112. keepalive > 65535 ||
  6113. keepalive % 1 !== 0) {
  6114. stream.emit('error', new Error('Invalid keepalive'))
  6115. return false
  6116. } else length += 2
  6117. // Connect flags
  6118. length += 1
  6119. // If will exists...
  6120. if (will) {
  6121. // It must be an object
  6122. if (typeof will !== 'object') {
  6123. stream.emit('error', new Error('Invalid will'))
  6124. return false
  6125. }
  6126. // It must have topic typeof string
  6127. if (!will.topic || typeof will.topic !== 'string') {
  6128. stream.emit('error', new Error('Invalid will topic'))
  6129. return false
  6130. } else {
  6131. length += Buffer.byteLength(will.topic) + 2
  6132. }
  6133. // Payload
  6134. if (will.payload && will.payload) {
  6135. if (will.payload.length >= 0) {
  6136. if (typeof will.payload === 'string') {
  6137. length += Buffer.byteLength(will.payload) + 2
  6138. } else {
  6139. length += will.payload.length + 2
  6140. }
  6141. } else {
  6142. stream.emit('error', new Error('Invalid will payload'))
  6143. return false
  6144. }
  6145. } else {
  6146. length += 2
  6147. }
  6148. }
  6149. // Username
  6150. var providedUsername = false
  6151. if (username != null) {
  6152. if (isStringOrBuffer(username)) {
  6153. providedUsername = true
  6154. length += Buffer.byteLength(username) + 2
  6155. } else {
  6156. stream.emit('error', new Error('Invalid username'))
  6157. return false
  6158. }
  6159. }
  6160. // Password
  6161. if (password != null) {
  6162. if (!providedUsername) {
  6163. stream.emit('error', new Error('Username is required to use password'))
  6164. return false
  6165. }
  6166. if (isStringOrBuffer(password)) {
  6167. length += byteLength(password) + 2
  6168. } else {
  6169. stream.emit('error', new Error('Invalid password'))
  6170. return false
  6171. }
  6172. }
  6173. // Generate header
  6174. stream.write(protocol.CONNECT_HEADER)
  6175. // Generate length
  6176. writeLength(stream, length)
  6177. // Generate protocol ID
  6178. writeStringOrBuffer(stream, protocolId)
  6179. stream.write(
  6180. protocolVersion === 4 ? protocol.VERSION4 : protocol.VERSION3
  6181. )
  6182. // Connect flags
  6183. var flags = 0
  6184. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  6185. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  6186. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  6187. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  6188. flags |= will ? protocol.WILL_FLAG_MASK : 0
  6189. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  6190. stream.write(Buffer.from([flags]))
  6191. // Keepalive
  6192. writeNumber(stream, keepalive)
  6193. // Client ID
  6194. writeStringOrBuffer(stream, clientId)
  6195. // Will
  6196. if (will) {
  6197. writeString(stream, will.topic)
  6198. writeStringOrBuffer(stream, will.payload)
  6199. }
  6200. // Username and password
  6201. if (username != null) {
  6202. writeStringOrBuffer(stream, username)
  6203. }
  6204. if (password != null) {
  6205. writeStringOrBuffer(stream, password)
  6206. }
  6207. // This is a small packet that happens only once on a stream
  6208. // We assume the stream is always free to receive more data after this
  6209. return true
  6210. }
  6211. function connack (opts, stream) {
  6212. var settings = opts || {}
  6213. var rc = settings.returnCode
  6214. // Check return code
  6215. if (typeof rc !== 'number') {
  6216. stream.emit('error', new Error('Invalid return code'))
  6217. return false
  6218. }
  6219. stream.write(protocol.CONNACK_HEADER)
  6220. writeLength(stream, 2)
  6221. stream.write(opts.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  6222. return stream.write(Buffer.from([rc]))
  6223. }
  6224. function publish (opts, stream) {
  6225. var settings = opts || {}
  6226. var qos = settings.qos || 0
  6227. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  6228. var topic = settings.topic
  6229. var payload = settings.payload || empty
  6230. var id = settings.messageId
  6231. var length = 0
  6232. // Topic must be a non-empty string or Buffer
  6233. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  6234. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  6235. else {
  6236. stream.emit('error', new Error('Invalid topic'))
  6237. return false
  6238. }
  6239. // Get the payload length
  6240. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  6241. else length += payload.length
  6242. // Message ID must a number if qos > 0
  6243. if (qos && typeof id !== 'number') {
  6244. stream.emit('error', new Error('Invalid messageId'))
  6245. return false
  6246. } else if (qos) length += 2
  6247. // Header
  6248. stream.write(protocol.PUBLISH_HEADER[qos][opts.dup ? 1 : 0][retain ? 1 : 0])
  6249. // Remaining length
  6250. writeLength(stream, length)
  6251. // Topic
  6252. writeNumber(stream, byteLength(topic))
  6253. stream.write(topic)
  6254. // Message ID
  6255. if (qos > 0) writeNumber(stream, id)
  6256. // Payload
  6257. return stream.write(payload)
  6258. }
  6259. /* Puback, pubrec, pubrel and pubcomp */
  6260. function confirmation (opts, stream) {
  6261. var settings = opts || {}
  6262. var type = settings.cmd || 'puback'
  6263. var id = settings.messageId
  6264. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  6265. var qos = 0
  6266. if (type === 'pubrel') qos = 1
  6267. // Check message ID
  6268. if (typeof id !== 'number') {
  6269. stream.emit('error', new Error('Invalid messageId'))
  6270. return false
  6271. }
  6272. // Header
  6273. stream.write(protocol.ACKS[type][qos][dup][0])
  6274. // Length
  6275. writeLength(stream, 2)
  6276. // Message ID
  6277. return writeNumber(stream, id)
  6278. }
  6279. function subscribe (opts, stream) {
  6280. var settings = opts || {}
  6281. var dup = settings.dup ? protocol.DUP_MASK : 0
  6282. var id = settings.messageId
  6283. var subs = settings.subscriptions
  6284. var length = 0
  6285. // Check message ID
  6286. if (typeof id !== 'number') {
  6287. stream.emit('error', new Error('Invalid messageId'))
  6288. return false
  6289. } else length += 2
  6290. // Check subscriptions
  6291. if (typeof subs === 'object' && subs.length) {
  6292. for (var i = 0; i < subs.length; i += 1) {
  6293. var itopic = subs[i].topic
  6294. var iqos = subs[i].qos
  6295. if (typeof itopic !== 'string') {
  6296. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  6297. return false
  6298. }
  6299. if (typeof iqos !== 'number') {
  6300. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  6301. return false
  6302. }
  6303. length += Buffer.byteLength(itopic) + 2 + 1
  6304. }
  6305. } else {
  6306. stream.emit('error', new Error('Invalid subscriptions'))
  6307. return false
  6308. }
  6309. // Generate header
  6310. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  6311. // Generate length
  6312. writeLength(stream, length)
  6313. // Generate message ID
  6314. writeNumber(stream, id)
  6315. var result = true
  6316. // Generate subs
  6317. for (var j = 0; j < subs.length; j++) {
  6318. var sub = subs[j]
  6319. var jtopic = sub.topic
  6320. var jqos = sub.qos
  6321. // Write topic string
  6322. writeString(stream, jtopic)
  6323. // Write qos
  6324. result = stream.write(protocol.QOS[jqos])
  6325. }
  6326. return result
  6327. }
  6328. function suback (opts, stream) {
  6329. var settings = opts || {}
  6330. var id = settings.messageId
  6331. var granted = settings.granted
  6332. var length = 0
  6333. // Check message ID
  6334. if (typeof id !== 'number') {
  6335. stream.emit('error', new Error('Invalid messageId'))
  6336. return false
  6337. } else length += 2
  6338. // Check granted qos vector
  6339. if (typeof granted === 'object' && granted.length) {
  6340. for (var i = 0; i < granted.length; i += 1) {
  6341. if (typeof granted[i] !== 'number') {
  6342. stream.emit('error', new Error('Invalid qos vector'))
  6343. return false
  6344. }
  6345. length += 1
  6346. }
  6347. } else {
  6348. stream.emit('error', new Error('Invalid qos vector'))
  6349. return false
  6350. }
  6351. // header
  6352. stream.write(protocol.SUBACK_HEADER)
  6353. // Length
  6354. writeLength(stream, length)
  6355. // Message ID
  6356. writeNumber(stream, id)
  6357. return stream.write(Buffer.from(granted))
  6358. }
  6359. function unsubscribe (opts, stream) {
  6360. var settings = opts || {}
  6361. var id = settings.messageId
  6362. var dup = settings.dup ? protocol.DUP_MASK : 0
  6363. var unsubs = settings.unsubscriptions
  6364. var length = 0
  6365. // Check message ID
  6366. if (typeof id !== 'number') {
  6367. stream.emit('error', new Error('Invalid messageId'))
  6368. return false
  6369. } else {
  6370. length += 2
  6371. }
  6372. // Check unsubs
  6373. if (typeof unsubs === 'object' && unsubs.length) {
  6374. for (var i = 0; i < unsubs.length; i += 1) {
  6375. if (typeof unsubs[i] !== 'string') {
  6376. stream.emit('error', new Error('Invalid unsubscriptions'))
  6377. return false
  6378. }
  6379. length += Buffer.byteLength(unsubs[i]) + 2
  6380. }
  6381. } else {
  6382. stream.emit('error', new Error('Invalid unsubscriptions'))
  6383. return false
  6384. }
  6385. // Header
  6386. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  6387. // Length
  6388. writeLength(stream, length)
  6389. // Message ID
  6390. writeNumber(stream, id)
  6391. // Unsubs
  6392. var result = true
  6393. for (var j = 0; j < unsubs.length; j++) {
  6394. result = writeString(stream, unsubs[j])
  6395. }
  6396. return result
  6397. }
  6398. function emptyPacket (opts, stream) {
  6399. return stream.write(protocol.EMPTY[opts.cmd])
  6400. }
  6401. /**
  6402. * calcLengthLength - calculate the length of the remaining
  6403. * length field
  6404. *
  6405. * @api private
  6406. */
  6407. function calcLengthLength (length) {
  6408. if (length >= 0 && length < 128) return 1
  6409. else if (length >= 128 && length < 16384) return 2
  6410. else if (length >= 16384 && length < 2097152) return 3
  6411. else if (length >= 2097152 && length < 268435456) return 4
  6412. else return 0
  6413. }
  6414. function genBufLength (length) {
  6415. var digit = 0
  6416. var pos = 0
  6417. var buffer = Buffer.allocUnsafe(calcLengthLength(length))
  6418. do {
  6419. digit = length % 128 | 0
  6420. length = length / 128 | 0
  6421. if (length > 0) digit = digit | 0x80
  6422. buffer.writeUInt8(digit, pos++)
  6423. } while (length > 0)
  6424. return buffer
  6425. }
  6426. /**
  6427. * writeLength - write an MQTT style length field to the buffer
  6428. *
  6429. * @param <Buffer> buffer - destination
  6430. * @param <Number> pos - offset
  6431. * @param <Number> length - length (>0)
  6432. * @returns <Number> number of bytes written
  6433. *
  6434. * @api private
  6435. */
  6436. var lengthCache = {}
  6437. function writeLength (stream, length) {
  6438. var buffer = lengthCache[length]
  6439. if (!buffer) {
  6440. buffer = genBufLength(length)
  6441. if (length < 16384) lengthCache[length] = buffer
  6442. }
  6443. stream.write(buffer)
  6444. }
  6445. /**
  6446. * writeString - write a utf8 string to the buffer
  6447. *
  6448. * @param <Buffer> buffer - destination
  6449. * @param <Number> pos - offset
  6450. * @param <String> string - string to write
  6451. * @return <Number> number of bytes written
  6452. *
  6453. * @api private
  6454. */
  6455. function writeString (stream, string) {
  6456. var strlen = Buffer.byteLength(string)
  6457. writeNumber(stream, strlen)
  6458. stream.write(string, 'utf8')
  6459. }
  6460. /**
  6461. * writeNumber - write a two byte number to the buffer
  6462. *
  6463. * @param <Buffer> buffer - destination
  6464. * @param <Number> pos - offset
  6465. * @param <String> number - number to write
  6466. * @return <Number> number of bytes written
  6467. *
  6468. * @api private
  6469. */
  6470. function writeNumberCached (stream, number) {
  6471. return stream.write(numCache[number])
  6472. }
  6473. function writeNumberGenerated (stream, number) {
  6474. return stream.write(generateNumber(number))
  6475. }
  6476. /**
  6477. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  6478. *
  6479. * @param <Buffer> buffer - destination
  6480. * @param <Number> pos - offset
  6481. * @param <String> toWrite - String or Buffer
  6482. * @return <Number> number of bytes written
  6483. */
  6484. function writeStringOrBuffer (stream, toWrite) {
  6485. if (typeof toWrite === 'string') {
  6486. writeString(stream, toWrite)
  6487. } else if (toWrite) {
  6488. writeNumber(stream, toWrite.length)
  6489. stream.write(toWrite)
  6490. } else writeNumber(stream, 0)
  6491. }
  6492. function byteLength (bufOrString) {
  6493. if (!bufOrString) return 0
  6494. else if (bufOrString instanceof Buffer) return bufOrString.length
  6495. else return Buffer.byteLength(bufOrString)
  6496. }
  6497. function isStringOrBuffer (field) {
  6498. return typeof field === 'string' || field instanceof Buffer
  6499. }
  6500. module.exports = generate
  6501. },{"./constants":87,"./numbers":90,"process-nextick-args":95,"safe-buffer":114}],94:[function(require,module,exports){
  6502. var wrappy = require('wrappy')
  6503. module.exports = wrappy(once)
  6504. module.exports.strict = wrappy(onceStrict)
  6505. once.proto = once(function () {
  6506. Object.defineProperty(Function.prototype, 'once', {
  6507. value: function () {
  6508. return once(this)
  6509. },
  6510. configurable: true
  6511. })
  6512. Object.defineProperty(Function.prototype, 'onceStrict', {
  6513. value: function () {
  6514. return onceStrict(this)
  6515. },
  6516. configurable: true
  6517. })
  6518. })
  6519. function once (fn) {
  6520. var f = function () {
  6521. if (f.called) return f.value
  6522. f.called = true
  6523. return f.value = fn.apply(this, arguments)
  6524. }
  6525. f.called = false
  6526. return f
  6527. }
  6528. function onceStrict (fn) {
  6529. var f = function () {
  6530. if (f.called)
  6531. throw new Error(f.onceError)
  6532. f.called = true
  6533. return f.value = fn.apply(this, arguments)
  6534. }
  6535. var name = fn.name || 'Function wrapped with `once`'
  6536. f.onceError = name + " shouldn't be called more than once"
  6537. f.called = false
  6538. return f
  6539. }
  6540. },{"wrappy":164}],95:[function(require,module,exports){
  6541. (function (process){(function (){
  6542. 'use strict';
  6543. if (typeof process === 'undefined' ||
  6544. !process.version ||
  6545. process.version.indexOf('v0.') === 0 ||
  6546. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  6547. module.exports = { nextTick: nextTick };
  6548. } else {
  6549. module.exports = process
  6550. }
  6551. function nextTick(fn, arg1, arg2, arg3) {
  6552. if (typeof fn !== 'function') {
  6553. throw new TypeError('"callback" argument must be a function');
  6554. }
  6555. var len = arguments.length;
  6556. var args, i;
  6557. switch (len) {
  6558. case 0:
  6559. case 1:
  6560. return process.nextTick(fn);
  6561. case 2:
  6562. return process.nextTick(function afterTickOne() {
  6563. fn.call(null, arg1);
  6564. });
  6565. case 3:
  6566. return process.nextTick(function afterTickTwo() {
  6567. fn.call(null, arg1, arg2);
  6568. });
  6569. case 4:
  6570. return process.nextTick(function afterTickThree() {
  6571. fn.call(null, arg1, arg2, arg3);
  6572. });
  6573. default:
  6574. args = new Array(len - 1);
  6575. i = 0;
  6576. while (i < args.length) {
  6577. args[i++] = arguments[i];
  6578. }
  6579. return process.nextTick(function afterTick() {
  6580. fn.apply(null, args);
  6581. });
  6582. }
  6583. }
  6584. }).call(this)}).call(this,require('_process'))
  6585. },{"_process":96}],96:[function(require,module,exports){
  6586. // shim for using process in browser
  6587. var process = module.exports = {};
  6588. // cached from whatever global is present so that test runners that stub it
  6589. // don't break things. But we need to wrap it in a try catch in case it is
  6590. // wrapped in strict mode code which doesn't define any globals. It's inside a
  6591. // function because try/catches deoptimize in certain engines.
  6592. var cachedSetTimeout;
  6593. var cachedClearTimeout;
  6594. function defaultSetTimout() {
  6595. throw new Error('setTimeout has not been defined');
  6596. }
  6597. function defaultClearTimeout () {
  6598. throw new Error('clearTimeout has not been defined');
  6599. }
  6600. (function () {
  6601. try {
  6602. if (typeof setTimeout === 'function') {
  6603. cachedSetTimeout = setTimeout;
  6604. } else {
  6605. cachedSetTimeout = defaultSetTimout;
  6606. }
  6607. } catch (e) {
  6608. cachedSetTimeout = defaultSetTimout;
  6609. }
  6610. try {
  6611. if (typeof clearTimeout === 'function') {
  6612. cachedClearTimeout = clearTimeout;
  6613. } else {
  6614. cachedClearTimeout = defaultClearTimeout;
  6615. }
  6616. } catch (e) {
  6617. cachedClearTimeout = defaultClearTimeout;
  6618. }
  6619. } ())
  6620. function runTimeout(fun) {
  6621. if (cachedSetTimeout === setTimeout) {
  6622. //normal enviroments in sane situations
  6623. return setTimeout(fun, 0);
  6624. }
  6625. // if setTimeout wasn't available but was latter defined
  6626. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  6627. cachedSetTimeout = setTimeout;
  6628. return setTimeout(fun, 0);
  6629. }
  6630. try {
  6631. // when when somebody has screwed with setTimeout but no I.E. maddness
  6632. return cachedSetTimeout(fun, 0);
  6633. } catch(e){
  6634. try {
  6635. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  6636. return cachedSetTimeout.call(null, fun, 0);
  6637. } catch(e){
  6638. // 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
  6639. return cachedSetTimeout.call(this, fun, 0);
  6640. }
  6641. }
  6642. }
  6643. function runClearTimeout(marker) {
  6644. if (cachedClearTimeout === clearTimeout) {
  6645. //normal enviroments in sane situations
  6646. return clearTimeout(marker);
  6647. }
  6648. // if clearTimeout wasn't available but was latter defined
  6649. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  6650. cachedClearTimeout = clearTimeout;
  6651. return clearTimeout(marker);
  6652. }
  6653. try {
  6654. // when when somebody has screwed with setTimeout but no I.E. maddness
  6655. return cachedClearTimeout(marker);
  6656. } catch (e){
  6657. try {
  6658. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  6659. return cachedClearTimeout.call(null, marker);
  6660. } catch (e){
  6661. // 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.
  6662. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  6663. return cachedClearTimeout.call(this, marker);
  6664. }
  6665. }
  6666. }
  6667. var queue = [];
  6668. var draining = false;
  6669. var currentQueue;
  6670. var queueIndex = -1;
  6671. function cleanUpNextTick() {
  6672. if (!draining || !currentQueue) {
  6673. return;
  6674. }
  6675. draining = false;
  6676. if (currentQueue.length) {
  6677. queue = currentQueue.concat(queue);
  6678. } else {
  6679. queueIndex = -1;
  6680. }
  6681. if (queue.length) {
  6682. drainQueue();
  6683. }
  6684. }
  6685. function drainQueue() {
  6686. if (draining) {
  6687. return;
  6688. }
  6689. var timeout = runTimeout(cleanUpNextTick);
  6690. draining = true;
  6691. var len = queue.length;
  6692. while(len) {
  6693. currentQueue = queue;
  6694. queue = [];
  6695. while (++queueIndex < len) {
  6696. if (currentQueue) {
  6697. currentQueue[queueIndex].run();
  6698. }
  6699. }
  6700. queueIndex = -1;
  6701. len = queue.length;
  6702. }
  6703. currentQueue = null;
  6704. draining = false;
  6705. runClearTimeout(timeout);
  6706. }
  6707. process.nextTick = function (fun) {
  6708. var args = new Array(arguments.length - 1);
  6709. if (arguments.length > 1) {
  6710. for (var i = 1; i < arguments.length; i++) {
  6711. args[i - 1] = arguments[i];
  6712. }
  6713. }
  6714. queue.push(new Item(fun, args));
  6715. if (queue.length === 1 && !draining) {
  6716. runTimeout(drainQueue);
  6717. }
  6718. };
  6719. // v8 likes predictible objects
  6720. function Item(fun, array) {
  6721. this.fun = fun;
  6722. this.array = array;
  6723. }
  6724. Item.prototype.run = function () {
  6725. this.fun.apply(null, this.array);
  6726. };
  6727. process.title = 'browser';
  6728. process.browser = true;
  6729. process.env = {};
  6730. process.argv = [];
  6731. process.version = ''; // empty string to avoid regexp issues
  6732. process.versions = {};
  6733. function noop() {}
  6734. process.on = noop;
  6735. process.addListener = noop;
  6736. process.once = noop;
  6737. process.off = noop;
  6738. process.removeListener = noop;
  6739. process.removeAllListeners = noop;
  6740. process.emit = noop;
  6741. process.prependListener = noop;
  6742. process.prependOnceListener = noop;
  6743. process.listeners = function (name) { return [] }
  6744. process.binding = function (name) {
  6745. throw new Error('process.binding is not supported');
  6746. };
  6747. process.cwd = function () { return '/' };
  6748. process.chdir = function (dir) {
  6749. throw new Error('process.chdir is not supported');
  6750. };
  6751. process.umask = function() { return 0; };
  6752. },{}],97:[function(require,module,exports){
  6753. (function (global){(function (){
  6754. /*! https://mths.be/punycode v1.4.1 by @mathias */
  6755. ;(function(root) {
  6756. /** Detect free variables */
  6757. var freeExports = typeof exports == 'object' && exports &&
  6758. !exports.nodeType && exports;
  6759. var freeModule = typeof module == 'object' && module &&
  6760. !module.nodeType && module;
  6761. var freeGlobal = typeof global == 'object' && global;
  6762. if (
  6763. freeGlobal.global === freeGlobal ||
  6764. freeGlobal.window === freeGlobal ||
  6765. freeGlobal.self === freeGlobal
  6766. ) {
  6767. root = freeGlobal;
  6768. }
  6769. /**
  6770. * The `punycode` object.
  6771. * @name punycode
  6772. * @type Object
  6773. */
  6774. var punycode,
  6775. /** Highest positive signed 32-bit float value */
  6776. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  6777. /** Bootstring parameters */
  6778. base = 36,
  6779. tMin = 1,
  6780. tMax = 26,
  6781. skew = 38,
  6782. damp = 700,
  6783. initialBias = 72,
  6784. initialN = 128, // 0x80
  6785. delimiter = '-', // '\x2D'
  6786. /** Regular expressions */
  6787. regexPunycode = /^xn--/,
  6788. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  6789. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  6790. /** Error messages */
  6791. errors = {
  6792. 'overflow': 'Overflow: input needs wider integers to process',
  6793. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  6794. 'invalid-input': 'Invalid input'
  6795. },
  6796. /** Convenience shortcuts */
  6797. baseMinusTMin = base - tMin,
  6798. floor = Math.floor,
  6799. stringFromCharCode = String.fromCharCode,
  6800. /** Temporary variable */
  6801. key;
  6802. /*--------------------------------------------------------------------------*/
  6803. /**
  6804. * A generic error utility function.
  6805. * @private
  6806. * @param {String} type The error type.
  6807. * @returns {Error} Throws a `RangeError` with the applicable error message.
  6808. */
  6809. function error(type) {
  6810. throw new RangeError(errors[type]);
  6811. }
  6812. /**
  6813. * A generic `Array#map` utility function.
  6814. * @private
  6815. * @param {Array} array The array to iterate over.
  6816. * @param {Function} callback The function that gets called for every array
  6817. * item.
  6818. * @returns {Array} A new array of values returned by the callback function.
  6819. */
  6820. function map(array, fn) {
  6821. var length = array.length;
  6822. var result = [];
  6823. while (length--) {
  6824. result[length] = fn(array[length]);
  6825. }
  6826. return result;
  6827. }
  6828. /**
  6829. * A simple `Array#map`-like wrapper to work with domain name strings or email
  6830. * addresses.
  6831. * @private
  6832. * @param {String} domain The domain name or email address.
  6833. * @param {Function} callback The function that gets called for every
  6834. * character.
  6835. * @returns {Array} A new string of characters returned by the callback
  6836. * function.
  6837. */
  6838. function mapDomain(string, fn) {
  6839. var parts = string.split('@');
  6840. var result = '';
  6841. if (parts.length > 1) {
  6842. // In email addresses, only the domain name should be punycoded. Leave
  6843. // the local part (i.e. everything up to `@`) intact.
  6844. result = parts[0] + '@';
  6845. string = parts[1];
  6846. }
  6847. // Avoid `split(regex)` for IE8 compatibility. See #17.
  6848. string = string.replace(regexSeparators, '\x2E');
  6849. var labels = string.split('.');
  6850. var encoded = map(labels, fn).join('.');
  6851. return result + encoded;
  6852. }
  6853. /**
  6854. * Creates an array containing the numeric code points of each Unicode
  6855. * character in the string. While JavaScript uses UCS-2 internally,
  6856. * this function will convert a pair of surrogate halves (each of which
  6857. * UCS-2 exposes as separate characters) into a single code point,
  6858. * matching UTF-16.
  6859. * @see `punycode.ucs2.encode`
  6860. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  6861. * @memberOf punycode.ucs2
  6862. * @name decode
  6863. * @param {String} string The Unicode input string (UCS-2).
  6864. * @returns {Array} The new array of code points.
  6865. */
  6866. function ucs2decode(string) {
  6867. var output = [],
  6868. counter = 0,
  6869. length = string.length,
  6870. value,
  6871. extra;
  6872. while (counter < length) {
  6873. value = string.charCodeAt(counter++);
  6874. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  6875. // high surrogate, and there is a next character
  6876. extra = string.charCodeAt(counter++);
  6877. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  6878. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  6879. } else {
  6880. // unmatched surrogate; only append this code unit, in case the next
  6881. // code unit is the high surrogate of a surrogate pair
  6882. output.push(value);
  6883. counter--;
  6884. }
  6885. } else {
  6886. output.push(value);
  6887. }
  6888. }
  6889. return output;
  6890. }
  6891. /**
  6892. * Creates a string based on an array of numeric code points.
  6893. * @see `punycode.ucs2.decode`
  6894. * @memberOf punycode.ucs2
  6895. * @name encode
  6896. * @param {Array} codePoints The array of numeric code points.
  6897. * @returns {String} The new Unicode string (UCS-2).
  6898. */
  6899. function ucs2encode(array) {
  6900. return map(array, function(value) {
  6901. var output = '';
  6902. if (value > 0xFFFF) {
  6903. value -= 0x10000;
  6904. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  6905. value = 0xDC00 | value & 0x3FF;
  6906. }
  6907. output += stringFromCharCode(value);
  6908. return output;
  6909. }).join('');
  6910. }
  6911. /**
  6912. * Converts a basic code point into a digit/integer.
  6913. * @see `digitToBasic()`
  6914. * @private
  6915. * @param {Number} codePoint The basic numeric code point value.
  6916. * @returns {Number} The numeric value of a basic code point (for use in
  6917. * representing integers) in the range `0` to `base - 1`, or `base` if
  6918. * the code point does not represent a value.
  6919. */
  6920. function basicToDigit(codePoint) {
  6921. if (codePoint - 48 < 10) {
  6922. return codePoint - 22;
  6923. }
  6924. if (codePoint - 65 < 26) {
  6925. return codePoint - 65;
  6926. }
  6927. if (codePoint - 97 < 26) {
  6928. return codePoint - 97;
  6929. }
  6930. return base;
  6931. }
  6932. /**
  6933. * Converts a digit/integer into a basic code point.
  6934. * @see `basicToDigit()`
  6935. * @private
  6936. * @param {Number} digit The numeric value of a basic code point.
  6937. * @returns {Number} The basic code point whose value (when used for
  6938. * representing integers) is `digit`, which needs to be in the range
  6939. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  6940. * used; else, the lowercase form is used. The behavior is undefined
  6941. * if `flag` is non-zero and `digit` has no uppercase form.
  6942. */
  6943. function digitToBasic(digit, flag) {
  6944. // 0..25 map to ASCII a..z or A..Z
  6945. // 26..35 map to ASCII 0..9
  6946. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  6947. }
  6948. /**
  6949. * Bias adaptation function as per section 3.4 of RFC 3492.
  6950. * https://tools.ietf.org/html/rfc3492#section-3.4
  6951. * @private
  6952. */
  6953. function adapt(delta, numPoints, firstTime) {
  6954. var k = 0;
  6955. delta = firstTime ? floor(delta / damp) : delta >> 1;
  6956. delta += floor(delta / numPoints);
  6957. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  6958. delta = floor(delta / baseMinusTMin);
  6959. }
  6960. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  6961. }
  6962. /**
  6963. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  6964. * symbols.
  6965. * @memberOf punycode
  6966. * @param {String} input The Punycode string of ASCII-only symbols.
  6967. * @returns {String} The resulting string of Unicode symbols.
  6968. */
  6969. function decode(input) {
  6970. // Don't use UCS-2
  6971. var output = [],
  6972. inputLength = input.length,
  6973. out,
  6974. i = 0,
  6975. n = initialN,
  6976. bias = initialBias,
  6977. basic,
  6978. j,
  6979. index,
  6980. oldi,
  6981. w,
  6982. k,
  6983. digit,
  6984. t,
  6985. /** Cached calculation results */
  6986. baseMinusT;
  6987. // Handle the basic code points: let `basic` be the number of input code
  6988. // points before the last delimiter, or `0` if there is none, then copy
  6989. // the first basic code points to the output.
  6990. basic = input.lastIndexOf(delimiter);
  6991. if (basic < 0) {
  6992. basic = 0;
  6993. }
  6994. for (j = 0; j < basic; ++j) {
  6995. // if it's not a basic code point
  6996. if (input.charCodeAt(j) >= 0x80) {
  6997. error('not-basic');
  6998. }
  6999. output.push(input.charCodeAt(j));
  7000. }
  7001. // Main decoding loop: start just after the last delimiter if any basic code
  7002. // points were copied; start at the beginning otherwise.
  7003. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  7004. // `index` is the index of the next character to be consumed.
  7005. // Decode a generalized variable-length integer into `delta`,
  7006. // which gets added to `i`. The overflow checking is easier
  7007. // if we increase `i` as we go, then subtract off its starting
  7008. // value at the end to obtain `delta`.
  7009. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  7010. if (index >= inputLength) {
  7011. error('invalid-input');
  7012. }
  7013. digit = basicToDigit(input.charCodeAt(index++));
  7014. if (digit >= base || digit > floor((maxInt - i) / w)) {
  7015. error('overflow');
  7016. }
  7017. i += digit * w;
  7018. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  7019. if (digit < t) {
  7020. break;
  7021. }
  7022. baseMinusT = base - t;
  7023. if (w > floor(maxInt / baseMinusT)) {
  7024. error('overflow');
  7025. }
  7026. w *= baseMinusT;
  7027. }
  7028. out = output.length + 1;
  7029. bias = adapt(i - oldi, out, oldi == 0);
  7030. // `i` was supposed to wrap around from `out` to `0`,
  7031. // incrementing `n` each time, so we'll fix that now:
  7032. if (floor(i / out) > maxInt - n) {
  7033. error('overflow');
  7034. }
  7035. n += floor(i / out);
  7036. i %= out;
  7037. // Insert `n` at position `i` of the output
  7038. output.splice(i++, 0, n);
  7039. }
  7040. return ucs2encode(output);
  7041. }
  7042. /**
  7043. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  7044. * Punycode string of ASCII-only symbols.
  7045. * @memberOf punycode
  7046. * @param {String} input The string of Unicode symbols.
  7047. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  7048. */
  7049. function encode(input) {
  7050. var n,
  7051. delta,
  7052. handledCPCount,
  7053. basicLength,
  7054. bias,
  7055. j,
  7056. m,
  7057. q,
  7058. k,
  7059. t,
  7060. currentValue,
  7061. output = [],
  7062. /** `inputLength` will hold the number of code points in `input`. */
  7063. inputLength,
  7064. /** Cached calculation results */
  7065. handledCPCountPlusOne,
  7066. baseMinusT,
  7067. qMinusT;
  7068. // Convert the input in UCS-2 to Unicode
  7069. input = ucs2decode(input);
  7070. // Cache the length
  7071. inputLength = input.length;
  7072. // Initialize the state
  7073. n = initialN;
  7074. delta = 0;
  7075. bias = initialBias;
  7076. // Handle the basic code points
  7077. for (j = 0; j < inputLength; ++j) {
  7078. currentValue = input[j];
  7079. if (currentValue < 0x80) {
  7080. output.push(stringFromCharCode(currentValue));
  7081. }
  7082. }
  7083. handledCPCount = basicLength = output.length;
  7084. // `handledCPCount` is the number of code points that have been handled;
  7085. // `basicLength` is the number of basic code points.
  7086. // Finish the basic string - if it is not empty - with a delimiter
  7087. if (basicLength) {
  7088. output.push(delimiter);
  7089. }
  7090. // Main encoding loop:
  7091. while (handledCPCount < inputLength) {
  7092. // All non-basic code points < n have been handled already. Find the next
  7093. // larger one:
  7094. for (m = maxInt, j = 0; j < inputLength; ++j) {
  7095. currentValue = input[j];
  7096. if (currentValue >= n && currentValue < m) {
  7097. m = currentValue;
  7098. }
  7099. }
  7100. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  7101. // but guard against overflow
  7102. handledCPCountPlusOne = handledCPCount + 1;
  7103. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  7104. error('overflow');
  7105. }
  7106. delta += (m - n) * handledCPCountPlusOne;
  7107. n = m;
  7108. for (j = 0; j < inputLength; ++j) {
  7109. currentValue = input[j];
  7110. if (currentValue < n && ++delta > maxInt) {
  7111. error('overflow');
  7112. }
  7113. if (currentValue == n) {
  7114. // Represent delta as a generalized variable-length integer
  7115. for (q = delta, k = base; /* no condition */; k += base) {
  7116. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  7117. if (q < t) {
  7118. break;
  7119. }
  7120. qMinusT = q - t;
  7121. baseMinusT = base - t;
  7122. output.push(
  7123. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  7124. );
  7125. q = floor(qMinusT / baseMinusT);
  7126. }
  7127. output.push(stringFromCharCode(digitToBasic(q, 0)));
  7128. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  7129. delta = 0;
  7130. ++handledCPCount;
  7131. }
  7132. }
  7133. ++delta;
  7134. ++n;
  7135. }
  7136. return output.join('');
  7137. }
  7138. /**
  7139. * Converts a Punycode string representing a domain name or an email address
  7140. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  7141. * it doesn't matter if you call it on a string that has already been
  7142. * converted to Unicode.
  7143. * @memberOf punycode
  7144. * @param {String} input The Punycoded domain name or email address to
  7145. * convert to Unicode.
  7146. * @returns {String} The Unicode representation of the given Punycode
  7147. * string.
  7148. */
  7149. function toUnicode(input) {
  7150. return mapDomain(input, function(string) {
  7151. return regexPunycode.test(string)
  7152. ? decode(string.slice(4).toLowerCase())
  7153. : string;
  7154. });
  7155. }
  7156. /**
  7157. * Converts a Unicode string representing a domain name or an email address to
  7158. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  7159. * i.e. it doesn't matter if you call it with a domain that's already in
  7160. * ASCII.
  7161. * @memberOf punycode
  7162. * @param {String} input The domain name or email address to convert, as a
  7163. * Unicode string.
  7164. * @returns {String} The Punycode representation of the given domain name or
  7165. * email address.
  7166. */
  7167. function toASCII(input) {
  7168. return mapDomain(input, function(string) {
  7169. return regexNonASCII.test(string)
  7170. ? 'xn--' + encode(string)
  7171. : string;
  7172. });
  7173. }
  7174. /*--------------------------------------------------------------------------*/
  7175. /** Define the public API */
  7176. punycode = {
  7177. /**
  7178. * A string representing the current Punycode.js version number.
  7179. * @memberOf punycode
  7180. * @type String
  7181. */
  7182. 'version': '1.4.1',
  7183. /**
  7184. * An object of methods to convert from JavaScript's internal character
  7185. * representation (UCS-2) to Unicode code points, and back.
  7186. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  7187. * @memberOf punycode
  7188. * @type Object
  7189. */
  7190. 'ucs2': {
  7191. 'decode': ucs2decode,
  7192. 'encode': ucs2encode
  7193. },
  7194. 'decode': decode,
  7195. 'encode': encode,
  7196. 'toASCII': toASCII,
  7197. 'toUnicode': toUnicode
  7198. };
  7199. /** Expose `punycode` */
  7200. // Some AMD build optimizers, like r.js, check for specific condition patterns
  7201. // like the following:
  7202. if (
  7203. typeof define == 'function' &&
  7204. typeof define.amd == 'object' &&
  7205. define.amd
  7206. ) {
  7207. define('punycode', function() {
  7208. return punycode;
  7209. });
  7210. } else if (freeExports && freeModule) {
  7211. if (module.exports == freeExports) {
  7212. // in Node.js, io.js, or RingoJS v0.8.0+
  7213. freeModule.exports = punycode;
  7214. } else {
  7215. // in Narwhal or RingoJS v0.7.0-
  7216. for (key in punycode) {
  7217. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  7218. }
  7219. }
  7220. } else {
  7221. // in Rhino or a web browser
  7222. root.punycode = punycode;
  7223. }
  7224. }(this));
  7225. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  7226. },{}],98:[function(require,module,exports){
  7227. // Copyright Joyent, Inc. and other Node contributors.
  7228. //
  7229. // Permission is hereby granted, free of charge, to any person obtaining a
  7230. // copy of this software and associated documentation files (the
  7231. // "Software"), to deal in the Software without restriction, including
  7232. // without limitation the rights to use, copy, modify, merge, publish,
  7233. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7234. // persons to whom the Software is furnished to do so, subject to the
  7235. // following conditions:
  7236. //
  7237. // The above copyright notice and this permission notice shall be included
  7238. // in all copies or substantial portions of the Software.
  7239. //
  7240. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7241. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7242. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7243. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7244. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7245. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7246. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7247. 'use strict';
  7248. // If obj.hasOwnProperty has been overridden, then calling
  7249. // obj.hasOwnProperty(prop) will break.
  7250. // See: https://github.com/joyent/node/issues/1707
  7251. function hasOwnProperty(obj, prop) {
  7252. return Object.prototype.hasOwnProperty.call(obj, prop);
  7253. }
  7254. module.exports = function(qs, sep, eq, options) {
  7255. sep = sep || '&';
  7256. eq = eq || '=';
  7257. var obj = {};
  7258. if (typeof qs !== 'string' || qs.length === 0) {
  7259. return obj;
  7260. }
  7261. var regexp = /\+/g;
  7262. qs = qs.split(sep);
  7263. var maxKeys = 1000;
  7264. if (options && typeof options.maxKeys === 'number') {
  7265. maxKeys = options.maxKeys;
  7266. }
  7267. var len = qs.length;
  7268. // maxKeys <= 0 means that we should not limit keys count
  7269. if (maxKeys > 0 && len > maxKeys) {
  7270. len = maxKeys;
  7271. }
  7272. for (var i = 0; i < len; ++i) {
  7273. var x = qs[i].replace(regexp, '%20'),
  7274. idx = x.indexOf(eq),
  7275. kstr, vstr, k, v;
  7276. if (idx >= 0) {
  7277. kstr = x.substr(0, idx);
  7278. vstr = x.substr(idx + 1);
  7279. } else {
  7280. kstr = x;
  7281. vstr = '';
  7282. }
  7283. k = decodeURIComponent(kstr);
  7284. v = decodeURIComponent(vstr);
  7285. if (!hasOwnProperty(obj, k)) {
  7286. obj[k] = v;
  7287. } else if (isArray(obj[k])) {
  7288. obj[k].push(v);
  7289. } else {
  7290. obj[k] = [obj[k], v];
  7291. }
  7292. }
  7293. return obj;
  7294. };
  7295. var isArray = Array.isArray || function (xs) {
  7296. return Object.prototype.toString.call(xs) === '[object Array]';
  7297. };
  7298. },{}],99:[function(require,module,exports){
  7299. // Copyright Joyent, Inc. and other Node contributors.
  7300. //
  7301. // Permission is hereby granted, free of charge, to any person obtaining a
  7302. // copy of this software and associated documentation files (the
  7303. // "Software"), to deal in the Software without restriction, including
  7304. // without limitation the rights to use, copy, modify, merge, publish,
  7305. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7306. // persons to whom the Software is furnished to do so, subject to the
  7307. // following conditions:
  7308. //
  7309. // The above copyright notice and this permission notice shall be included
  7310. // in all copies or substantial portions of the Software.
  7311. //
  7312. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7313. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7314. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7315. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7316. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7317. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7318. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7319. 'use strict';
  7320. var stringifyPrimitive = function(v) {
  7321. switch (typeof v) {
  7322. case 'string':
  7323. return v;
  7324. case 'boolean':
  7325. return v ? 'true' : 'false';
  7326. case 'number':
  7327. return isFinite(v) ? v : '';
  7328. default:
  7329. return '';
  7330. }
  7331. };
  7332. module.exports = function(obj, sep, eq, name) {
  7333. sep = sep || '&';
  7334. eq = eq || '=';
  7335. if (obj === null) {
  7336. obj = undefined;
  7337. }
  7338. if (typeof obj === 'object') {
  7339. return map(objectKeys(obj), function(k) {
  7340. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  7341. if (isArray(obj[k])) {
  7342. return map(obj[k], function(v) {
  7343. return ks + encodeURIComponent(stringifyPrimitive(v));
  7344. }).join(sep);
  7345. } else {
  7346. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  7347. }
  7348. }).join(sep);
  7349. }
  7350. if (!name) return '';
  7351. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  7352. encodeURIComponent(stringifyPrimitive(obj));
  7353. };
  7354. var isArray = Array.isArray || function (xs) {
  7355. return Object.prototype.toString.call(xs) === '[object Array]';
  7356. };
  7357. function map (xs, f) {
  7358. if (xs.map) return xs.map(f);
  7359. var res = [];
  7360. for (var i = 0; i < xs.length; i++) {
  7361. res.push(f(xs[i], i));
  7362. }
  7363. return res;
  7364. }
  7365. var objectKeys = Object.keys || function (obj) {
  7366. var res = [];
  7367. for (var key in obj) {
  7368. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  7369. }
  7370. return res;
  7371. };
  7372. },{}],100:[function(require,module,exports){
  7373. 'use strict';
  7374. exports.decode = exports.parse = require('./decode');
  7375. exports.encode = exports.stringify = require('./encode');
  7376. },{"./decode":98,"./encode":99}],101:[function(require,module,exports){
  7377. module.exports = require('./lib/_stream_duplex.js');
  7378. },{"./lib/_stream_duplex.js":102}],102:[function(require,module,exports){
  7379. // Copyright Joyent, Inc. and other Node contributors.
  7380. //
  7381. // Permission is hereby granted, free of charge, to any person obtaining a
  7382. // copy of this software and associated documentation files (the
  7383. // "Software"), to deal in the Software without restriction, including
  7384. // without limitation the rights to use, copy, modify, merge, publish,
  7385. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7386. // persons to whom the Software is furnished to do so, subject to the
  7387. // following conditions:
  7388. //
  7389. // The above copyright notice and this permission notice shall be included
  7390. // in all copies or substantial portions of the Software.
  7391. //
  7392. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7393. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7394. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7395. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7396. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7397. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7398. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7399. // a duplex stream is just a stream that is both readable and writable.
  7400. // Since JS doesn't have multiple prototypal inheritance, this class
  7401. // prototypally inherits from Readable, and then parasitically from
  7402. // Writable.
  7403. 'use strict';
  7404. /*<replacement>*/
  7405. var pna = require('process-nextick-args');
  7406. /*</replacement>*/
  7407. /*<replacement>*/
  7408. var objectKeys = Object.keys || function (obj) {
  7409. var keys = [];
  7410. for (var key in obj) {
  7411. keys.push(key);
  7412. }return keys;
  7413. };
  7414. /*</replacement>*/
  7415. module.exports = Duplex;
  7416. /*<replacement>*/
  7417. var util = Object.create(require('core-util-is'));
  7418. util.inherits = require('inherits');
  7419. /*</replacement>*/
  7420. var Readable = require('./_stream_readable');
  7421. var Writable = require('./_stream_writable');
  7422. util.inherits(Duplex, Readable);
  7423. {
  7424. // avoid scope creep, the keys array can then be collected
  7425. var keys = objectKeys(Writable.prototype);
  7426. for (var v = 0; v < keys.length; v++) {
  7427. var method = keys[v];
  7428. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  7429. }
  7430. }
  7431. function Duplex(options) {
  7432. if (!(this instanceof Duplex)) return new Duplex(options);
  7433. Readable.call(this, options);
  7434. Writable.call(this, options);
  7435. if (options && options.readable === false) this.readable = false;
  7436. if (options && options.writable === false) this.writable = false;
  7437. this.allowHalfOpen = true;
  7438. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  7439. this.once('end', onend);
  7440. }
  7441. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  7442. // making it explicit this property is not enumerable
  7443. // because otherwise some prototype manipulation in
  7444. // userland will fail
  7445. enumerable: false,
  7446. get: function () {
  7447. return this._writableState.highWaterMark;
  7448. }
  7449. });
  7450. // the no-half-open enforcer
  7451. function onend() {
  7452. // if we allow half-open state, or if the writable side ended,
  7453. // then we're ok.
  7454. if (this.allowHalfOpen || this._writableState.ended) return;
  7455. // no more data can be written.
  7456. // But allow more writes to happen in this tick.
  7457. pna.nextTick(onEndNT, this);
  7458. }
  7459. function onEndNT(self) {
  7460. self.end();
  7461. }
  7462. Object.defineProperty(Duplex.prototype, 'destroyed', {
  7463. get: function () {
  7464. if (this._readableState === undefined || this._writableState === undefined) {
  7465. return false;
  7466. }
  7467. return this._readableState.destroyed && this._writableState.destroyed;
  7468. },
  7469. set: function (value) {
  7470. // we ignore the value if the stream
  7471. // has not been initialized yet
  7472. if (this._readableState === undefined || this._writableState === undefined) {
  7473. return;
  7474. }
  7475. // backward compatibility, the user is explicitly
  7476. // managing destroyed
  7477. this._readableState.destroyed = value;
  7478. this._writableState.destroyed = value;
  7479. }
  7480. });
  7481. Duplex.prototype._destroy = function (err, cb) {
  7482. this.push(null);
  7483. this.end();
  7484. pna.nextTick(cb, err);
  7485. };
  7486. },{"./_stream_readable":104,"./_stream_writable":106,"core-util-is":13,"inherits":84,"process-nextick-args":95}],103:[function(require,module,exports){
  7487. // Copyright Joyent, Inc. and other Node contributors.
  7488. //
  7489. // Permission is hereby granted, free of charge, to any person obtaining a
  7490. // copy of this software and associated documentation files (the
  7491. // "Software"), to deal in the Software without restriction, including
  7492. // without limitation the rights to use, copy, modify, merge, publish,
  7493. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7494. // persons to whom the Software is furnished to do so, subject to the
  7495. // following conditions:
  7496. //
  7497. // The above copyright notice and this permission notice shall be included
  7498. // in all copies or substantial portions of the Software.
  7499. //
  7500. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7501. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7502. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7503. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7504. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7505. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7506. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7507. // a passthrough stream.
  7508. // basically just the most minimal sort of Transform stream.
  7509. // Every written chunk gets output as-is.
  7510. 'use strict';
  7511. module.exports = PassThrough;
  7512. var Transform = require('./_stream_transform');
  7513. /*<replacement>*/
  7514. var util = Object.create(require('core-util-is'));
  7515. util.inherits = require('inherits');
  7516. /*</replacement>*/
  7517. util.inherits(PassThrough, Transform);
  7518. function PassThrough(options) {
  7519. if (!(this instanceof PassThrough)) return new PassThrough(options);
  7520. Transform.call(this, options);
  7521. }
  7522. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  7523. cb(null, chunk);
  7524. };
  7525. },{"./_stream_transform":105,"core-util-is":13,"inherits":84}],104:[function(require,module,exports){
  7526. (function (process,global){(function (){
  7527. // Copyright Joyent, Inc. and other Node contributors.
  7528. //
  7529. // Permission is hereby granted, free of charge, to any person obtaining a
  7530. // copy of this software and associated documentation files (the
  7531. // "Software"), to deal in the Software without restriction, including
  7532. // without limitation the rights to use, copy, modify, merge, publish,
  7533. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7534. // persons to whom the Software is furnished to do so, subject to the
  7535. // following conditions:
  7536. //
  7537. // The above copyright notice and this permission notice shall be included
  7538. // in all copies or substantial portions of the Software.
  7539. //
  7540. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7541. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7542. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7543. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7544. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7545. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7546. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7547. 'use strict';
  7548. /*<replacement>*/
  7549. var pna = require('process-nextick-args');
  7550. /*</replacement>*/
  7551. module.exports = Readable;
  7552. /*<replacement>*/
  7553. var isArray = require('isarray');
  7554. /*</replacement>*/
  7555. /*<replacement>*/
  7556. var Duplex;
  7557. /*</replacement>*/
  7558. Readable.ReadableState = ReadableState;
  7559. /*<replacement>*/
  7560. var EE = require('events').EventEmitter;
  7561. var EElistenerCount = function (emitter, type) {
  7562. return emitter.listeners(type).length;
  7563. };
  7564. /*</replacement>*/
  7565. /*<replacement>*/
  7566. var Stream = require('./internal/streams/stream');
  7567. /*</replacement>*/
  7568. /*<replacement>*/
  7569. var Buffer = require('safe-buffer').Buffer;
  7570. var OurUint8Array = global.Uint8Array || function () {};
  7571. function _uint8ArrayToBuffer(chunk) {
  7572. return Buffer.from(chunk);
  7573. }
  7574. function _isUint8Array(obj) {
  7575. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  7576. }
  7577. /*</replacement>*/
  7578. /*<replacement>*/
  7579. var util = Object.create(require('core-util-is'));
  7580. util.inherits = require('inherits');
  7581. /*</replacement>*/
  7582. /*<replacement>*/
  7583. var debugUtil = require('util');
  7584. var debug = void 0;
  7585. if (debugUtil && debugUtil.debuglog) {
  7586. debug = debugUtil.debuglog('stream');
  7587. } else {
  7588. debug = function () {};
  7589. }
  7590. /*</replacement>*/
  7591. var BufferList = require('./internal/streams/BufferList');
  7592. var destroyImpl = require('./internal/streams/destroy');
  7593. var StringDecoder;
  7594. util.inherits(Readable, Stream);
  7595. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  7596. function prependListener(emitter, event, fn) {
  7597. // Sadly this is not cacheable as some libraries bundle their own
  7598. // event emitter implementation with them.
  7599. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  7600. // This is a hack to make sure that our error handler is attached before any
  7601. // userland ones. NEVER DO THIS. This is here only because this code needs
  7602. // to continue to work with older versions of Node.js that do not include
  7603. // the prependListener() method. The goal is to eventually remove this hack.
  7604. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  7605. }
  7606. function ReadableState(options, stream) {
  7607. Duplex = Duplex || require('./_stream_duplex');
  7608. options = options || {};
  7609. // Duplex streams are both readable and writable, but share
  7610. // the same options object.
  7611. // However, some cases require setting options to different
  7612. // values for the readable and the writable sides of the duplex stream.
  7613. // These options can be provided separately as readableXXX and writableXXX.
  7614. var isDuplex = stream instanceof Duplex;
  7615. // object stream flag. Used to make read(n) ignore n and to
  7616. // make all the buffer merging and length checks go away
  7617. this.objectMode = !!options.objectMode;
  7618. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  7619. // the point at which it stops calling _read() to fill the buffer
  7620. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  7621. var hwm = options.highWaterMark;
  7622. var readableHwm = options.readableHighWaterMark;
  7623. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  7624. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  7625. // cast to ints.
  7626. this.highWaterMark = Math.floor(this.highWaterMark);
  7627. // A linked list is used to store data chunks instead of an array because the
  7628. // linked list can remove elements from the beginning faster than
  7629. // array.shift()
  7630. this.buffer = new BufferList();
  7631. this.length = 0;
  7632. this.pipes = null;
  7633. this.pipesCount = 0;
  7634. this.flowing = null;
  7635. this.ended = false;
  7636. this.endEmitted = false;
  7637. this.reading = false;
  7638. // a flag to be able to tell if the event 'readable'/'data' is emitted
  7639. // immediately, or on a later tick. We set this to true at first, because
  7640. // any actions that shouldn't happen until "later" should generally also
  7641. // not happen before the first read call.
  7642. this.sync = true;
  7643. // whenever we return null, then we set a flag to say
  7644. // that we're awaiting a 'readable' event emission.
  7645. this.needReadable = false;
  7646. this.emittedReadable = false;
  7647. this.readableListening = false;
  7648. this.resumeScheduled = false;
  7649. // has it been destroyed
  7650. this.destroyed = false;
  7651. // Crypto is kind of old and crusty. Historically, its default string
  7652. // encoding is 'binary' so we have to make this configurable.
  7653. // Everything else in the universe uses 'utf8', though.
  7654. this.defaultEncoding = options.defaultEncoding || 'utf8';
  7655. // the number of writers that are awaiting a drain event in .pipe()s
  7656. this.awaitDrain = 0;
  7657. // if true, a maybeReadMore has been scheduled
  7658. this.readingMore = false;
  7659. this.decoder = null;
  7660. this.encoding = null;
  7661. if (options.encoding) {
  7662. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  7663. this.decoder = new StringDecoder(options.encoding);
  7664. this.encoding = options.encoding;
  7665. }
  7666. }
  7667. function Readable(options) {
  7668. Duplex = Duplex || require('./_stream_duplex');
  7669. if (!(this instanceof Readable)) return new Readable(options);
  7670. this._readableState = new ReadableState(options, this);
  7671. // legacy
  7672. this.readable = true;
  7673. if (options) {
  7674. if (typeof options.read === 'function') this._read = options.read;
  7675. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  7676. }
  7677. Stream.call(this);
  7678. }
  7679. Object.defineProperty(Readable.prototype, 'destroyed', {
  7680. get: function () {
  7681. if (this._readableState === undefined) {
  7682. return false;
  7683. }
  7684. return this._readableState.destroyed;
  7685. },
  7686. set: function (value) {
  7687. // we ignore the value if the stream
  7688. // has not been initialized yet
  7689. if (!this._readableState) {
  7690. return;
  7691. }
  7692. // backward compatibility, the user is explicitly
  7693. // managing destroyed
  7694. this._readableState.destroyed = value;
  7695. }
  7696. });
  7697. Readable.prototype.destroy = destroyImpl.destroy;
  7698. Readable.prototype._undestroy = destroyImpl.undestroy;
  7699. Readable.prototype._destroy = function (err, cb) {
  7700. this.push(null);
  7701. cb(err);
  7702. };
  7703. // Manually shove something into the read() buffer.
  7704. // This returns true if the highWaterMark has not been hit yet,
  7705. // similar to how Writable.write() returns true if you should
  7706. // write() some more.
  7707. Readable.prototype.push = function (chunk, encoding) {
  7708. var state = this._readableState;
  7709. var skipChunkCheck;
  7710. if (!state.objectMode) {
  7711. if (typeof chunk === 'string') {
  7712. encoding = encoding || state.defaultEncoding;
  7713. if (encoding !== state.encoding) {
  7714. chunk = Buffer.from(chunk, encoding);
  7715. encoding = '';
  7716. }
  7717. skipChunkCheck = true;
  7718. }
  7719. } else {
  7720. skipChunkCheck = true;
  7721. }
  7722. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  7723. };
  7724. // Unshift should *always* be something directly out of read()
  7725. Readable.prototype.unshift = function (chunk) {
  7726. return readableAddChunk(this, chunk, null, true, false);
  7727. };
  7728. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  7729. var state = stream._readableState;
  7730. if (chunk === null) {
  7731. state.reading = false;
  7732. onEofChunk(stream, state);
  7733. } else {
  7734. var er;
  7735. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  7736. if (er) {
  7737. stream.emit('error', er);
  7738. } else if (state.objectMode || chunk && chunk.length > 0) {
  7739. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  7740. chunk = _uint8ArrayToBuffer(chunk);
  7741. }
  7742. if (addToFront) {
  7743. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  7744. } else if (state.ended) {
  7745. stream.emit('error', new Error('stream.push() after EOF'));
  7746. } else {
  7747. state.reading = false;
  7748. if (state.decoder && !encoding) {
  7749. chunk = state.decoder.write(chunk);
  7750. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  7751. } else {
  7752. addChunk(stream, state, chunk, false);
  7753. }
  7754. }
  7755. } else if (!addToFront) {
  7756. state.reading = false;
  7757. }
  7758. }
  7759. return needMoreData(state);
  7760. }
  7761. function addChunk(stream, state, chunk, addToFront) {
  7762. if (state.flowing && state.length === 0 && !state.sync) {
  7763. stream.emit('data', chunk);
  7764. stream.read(0);
  7765. } else {
  7766. // update the buffer info.
  7767. state.length += state.objectMode ? 1 : chunk.length;
  7768. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  7769. if (state.needReadable) emitReadable(stream);
  7770. }
  7771. maybeReadMore(stream, state);
  7772. }
  7773. function chunkInvalid(state, chunk) {
  7774. var er;
  7775. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  7776. er = new TypeError('Invalid non-string/buffer chunk');
  7777. }
  7778. return er;
  7779. }
  7780. // if it's past the high water mark, we can push in some more.
  7781. // Also, if we have no data yet, we can stand some
  7782. // more bytes. This is to work around cases where hwm=0,
  7783. // such as the repl. Also, if the push() triggered a
  7784. // readable event, and the user called read(largeNumber) such that
  7785. // needReadable was set, then we ought to push more, so that another
  7786. // 'readable' event will be triggered.
  7787. function needMoreData(state) {
  7788. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  7789. }
  7790. Readable.prototype.isPaused = function () {
  7791. return this._readableState.flowing === false;
  7792. };
  7793. // backwards compatibility.
  7794. Readable.prototype.setEncoding = function (enc) {
  7795. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  7796. this._readableState.decoder = new StringDecoder(enc);
  7797. this._readableState.encoding = enc;
  7798. return this;
  7799. };
  7800. // Don't raise the hwm > 8MB
  7801. var MAX_HWM = 0x800000;
  7802. function computeNewHighWaterMark(n) {
  7803. if (n >= MAX_HWM) {
  7804. n = MAX_HWM;
  7805. } else {
  7806. // Get the next highest power of 2 to prevent increasing hwm excessively in
  7807. // tiny amounts
  7808. n--;
  7809. n |= n >>> 1;
  7810. n |= n >>> 2;
  7811. n |= n >>> 4;
  7812. n |= n >>> 8;
  7813. n |= n >>> 16;
  7814. n++;
  7815. }
  7816. return n;
  7817. }
  7818. // This function is designed to be inlinable, so please take care when making
  7819. // changes to the function body.
  7820. function howMuchToRead(n, state) {
  7821. if (n <= 0 || state.length === 0 && state.ended) return 0;
  7822. if (state.objectMode) return 1;
  7823. if (n !== n) {
  7824. // Only flow one buffer at a time
  7825. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  7826. }
  7827. // If we're asking for more than the current hwm, then raise the hwm.
  7828. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  7829. if (n <= state.length) return n;
  7830. // Don't have enough
  7831. if (!state.ended) {
  7832. state.needReadable = true;
  7833. return 0;
  7834. }
  7835. return state.length;
  7836. }
  7837. // you can override either this method, or the async _read(n) below.
  7838. Readable.prototype.read = function (n) {
  7839. debug('read', n);
  7840. n = parseInt(n, 10);
  7841. var state = this._readableState;
  7842. var nOrig = n;
  7843. if (n !== 0) state.emittedReadable = false;
  7844. // if we're doing read(0) to trigger a readable event, but we
  7845. // already have a bunch of data in the buffer, then just trigger
  7846. // the 'readable' event and move on.
  7847. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  7848. debug('read: emitReadable', state.length, state.ended);
  7849. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  7850. return null;
  7851. }
  7852. n = howMuchToRead(n, state);
  7853. // if we've ended, and we're now clear, then finish it up.
  7854. if (n === 0 && state.ended) {
  7855. if (state.length === 0) endReadable(this);
  7856. return null;
  7857. }
  7858. // All the actual chunk generation logic needs to be
  7859. // *below* the call to _read. The reason is that in certain
  7860. // synthetic stream cases, such as passthrough streams, _read
  7861. // may be a completely synchronous operation which may change
  7862. // the state of the read buffer, providing enough data when
  7863. // before there was *not* enough.
  7864. //
  7865. // So, the steps are:
  7866. // 1. Figure out what the state of things will be after we do
  7867. // a read from the buffer.
  7868. //
  7869. // 2. If that resulting state will trigger a _read, then call _read.
  7870. // Note that this may be asynchronous, or synchronous. Yes, it is
  7871. // deeply ugly to write APIs this way, but that still doesn't mean
  7872. // that the Readable class should behave improperly, as streams are
  7873. // designed to be sync/async agnostic.
  7874. // Take note if the _read call is sync or async (ie, if the read call
  7875. // has returned yet), so that we know whether or not it's safe to emit
  7876. // 'readable' etc.
  7877. //
  7878. // 3. Actually pull the requested chunks out of the buffer and return.
  7879. // if we need a readable event, then we need to do some reading.
  7880. var doRead = state.needReadable;
  7881. debug('need readable', doRead);
  7882. // if we currently have less than the highWaterMark, then also read some
  7883. if (state.length === 0 || state.length - n < state.highWaterMark) {
  7884. doRead = true;
  7885. debug('length less than watermark', doRead);
  7886. }
  7887. // however, if we've ended, then there's no point, and if we're already
  7888. // reading, then it's unnecessary.
  7889. if (state.ended || state.reading) {
  7890. doRead = false;
  7891. debug('reading or ended', doRead);
  7892. } else if (doRead) {
  7893. debug('do read');
  7894. state.reading = true;
  7895. state.sync = true;
  7896. // if the length is currently zero, then we *need* a readable event.
  7897. if (state.length === 0) state.needReadable = true;
  7898. // call internal read method
  7899. this._read(state.highWaterMark);
  7900. state.sync = false;
  7901. // If _read pushed data synchronously, then `reading` will be false,
  7902. // and we need to re-evaluate how much data we can return to the user.
  7903. if (!state.reading) n = howMuchToRead(nOrig, state);
  7904. }
  7905. var ret;
  7906. if (n > 0) ret = fromList(n, state);else ret = null;
  7907. if (ret === null) {
  7908. state.needReadable = true;
  7909. n = 0;
  7910. } else {
  7911. state.length -= n;
  7912. }
  7913. if (state.length === 0) {
  7914. // If we have nothing in the buffer, then we want to know
  7915. // as soon as we *do* get something into the buffer.
  7916. if (!state.ended) state.needReadable = true;
  7917. // If we tried to read() past the EOF, then emit end on the next tick.
  7918. if (nOrig !== n && state.ended) endReadable(this);
  7919. }
  7920. if (ret !== null) this.emit('data', ret);
  7921. return ret;
  7922. };
  7923. function onEofChunk(stream, state) {
  7924. if (state.ended) return;
  7925. if (state.decoder) {
  7926. var chunk = state.decoder.end();
  7927. if (chunk && chunk.length) {
  7928. state.buffer.push(chunk);
  7929. state.length += state.objectMode ? 1 : chunk.length;
  7930. }
  7931. }
  7932. state.ended = true;
  7933. // emit 'readable' now to make sure it gets picked up.
  7934. emitReadable(stream);
  7935. }
  7936. // Don't emit readable right away in sync mode, because this can trigger
  7937. // another read() call => stack overflow. This way, it might trigger
  7938. // a nextTick recursion warning, but that's not so bad.
  7939. function emitReadable(stream) {
  7940. var state = stream._readableState;
  7941. state.needReadable = false;
  7942. if (!state.emittedReadable) {
  7943. debug('emitReadable', state.flowing);
  7944. state.emittedReadable = true;
  7945. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  7946. }
  7947. }
  7948. function emitReadable_(stream) {
  7949. debug('emit readable');
  7950. stream.emit('readable');
  7951. flow(stream);
  7952. }
  7953. // at this point, the user has presumably seen the 'readable' event,
  7954. // and called read() to consume some data. that may have triggered
  7955. // in turn another _read(n) call, in which case reading = true if
  7956. // it's in progress.
  7957. // However, if we're not ended, or reading, and the length < hwm,
  7958. // then go ahead and try to read some more preemptively.
  7959. function maybeReadMore(stream, state) {
  7960. if (!state.readingMore) {
  7961. state.readingMore = true;
  7962. pna.nextTick(maybeReadMore_, stream, state);
  7963. }
  7964. }
  7965. function maybeReadMore_(stream, state) {
  7966. var len = state.length;
  7967. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  7968. debug('maybeReadMore read 0');
  7969. stream.read(0);
  7970. if (len === state.length)
  7971. // didn't get any data, stop spinning.
  7972. break;else len = state.length;
  7973. }
  7974. state.readingMore = false;
  7975. }
  7976. // abstract method. to be overridden in specific implementation classes.
  7977. // call cb(er, data) where data is <= n in length.
  7978. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  7979. // arbitrary, and perhaps not very meaningful.
  7980. Readable.prototype._read = function (n) {
  7981. this.emit('error', new Error('_read() is not implemented'));
  7982. };
  7983. Readable.prototype.pipe = function (dest, pipeOpts) {
  7984. var src = this;
  7985. var state = this._readableState;
  7986. switch (state.pipesCount) {
  7987. case 0:
  7988. state.pipes = dest;
  7989. break;
  7990. case 1:
  7991. state.pipes = [state.pipes, dest];
  7992. break;
  7993. default:
  7994. state.pipes.push(dest);
  7995. break;
  7996. }
  7997. state.pipesCount += 1;
  7998. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  7999. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  8000. var endFn = doEnd ? onend : unpipe;
  8001. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  8002. dest.on('unpipe', onunpipe);
  8003. function onunpipe(readable, unpipeInfo) {
  8004. debug('onunpipe');
  8005. if (readable === src) {
  8006. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  8007. unpipeInfo.hasUnpiped = true;
  8008. cleanup();
  8009. }
  8010. }
  8011. }
  8012. function onend() {
  8013. debug('onend');
  8014. dest.end();
  8015. }
  8016. // when the dest drains, it reduces the awaitDrain counter
  8017. // on the source. This would be more elegant with a .once()
  8018. // handler in flow(), but adding and removing repeatedly is
  8019. // too slow.
  8020. var ondrain = pipeOnDrain(src);
  8021. dest.on('drain', ondrain);
  8022. var cleanedUp = false;
  8023. function cleanup() {
  8024. debug('cleanup');
  8025. // cleanup event handlers once the pipe is broken
  8026. dest.removeListener('close', onclose);
  8027. dest.removeListener('finish', onfinish);
  8028. dest.removeListener('drain', ondrain);
  8029. dest.removeListener('error', onerror);
  8030. dest.removeListener('unpipe', onunpipe);
  8031. src.removeListener('end', onend);
  8032. src.removeListener('end', unpipe);
  8033. src.removeListener('data', ondata);
  8034. cleanedUp = true;
  8035. // if the reader is waiting for a drain event from this
  8036. // specific writer, then it would cause it to never start
  8037. // flowing again.
  8038. // So, if this is awaiting a drain, then we just call it now.
  8039. // If we don't know, then assume that we are waiting for one.
  8040. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  8041. }
  8042. // If the user pushes more data while we're writing to dest then we'll end up
  8043. // in ondata again. However, we only want to increase awaitDrain once because
  8044. // dest will only emit one 'drain' event for the multiple writes.
  8045. // => Introduce a guard on increasing awaitDrain.
  8046. var increasedAwaitDrain = false;
  8047. src.on('data', ondata);
  8048. function ondata(chunk) {
  8049. debug('ondata');
  8050. increasedAwaitDrain = false;
  8051. var ret = dest.write(chunk);
  8052. if (false === ret && !increasedAwaitDrain) {
  8053. // If the user unpiped during `dest.write()`, it is possible
  8054. // to get stuck in a permanently paused state if that write
  8055. // also returned false.
  8056. // => Check whether `dest` is still a piping destination.
  8057. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  8058. debug('false write response, pause', src._readableState.awaitDrain);
  8059. src._readableState.awaitDrain++;
  8060. increasedAwaitDrain = true;
  8061. }
  8062. src.pause();
  8063. }
  8064. }
  8065. // if the dest has an error, then stop piping into it.
  8066. // however, don't suppress the throwing behavior for this.
  8067. function onerror(er) {
  8068. debug('onerror', er);
  8069. unpipe();
  8070. dest.removeListener('error', onerror);
  8071. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  8072. }
  8073. // Make sure our error handler is attached before userland ones.
  8074. prependListener(dest, 'error', onerror);
  8075. // Both close and finish should trigger unpipe, but only once.
  8076. function onclose() {
  8077. dest.removeListener('finish', onfinish);
  8078. unpipe();
  8079. }
  8080. dest.once('close', onclose);
  8081. function onfinish() {
  8082. debug('onfinish');
  8083. dest.removeListener('close', onclose);
  8084. unpipe();
  8085. }
  8086. dest.once('finish', onfinish);
  8087. function unpipe() {
  8088. debug('unpipe');
  8089. src.unpipe(dest);
  8090. }
  8091. // tell the dest that it's being piped to
  8092. dest.emit('pipe', src);
  8093. // start the flow if it hasn't been started already.
  8094. if (!state.flowing) {
  8095. debug('pipe resume');
  8096. src.resume();
  8097. }
  8098. return dest;
  8099. };
  8100. function pipeOnDrain(src) {
  8101. return function () {
  8102. var state = src._readableState;
  8103. debug('pipeOnDrain', state.awaitDrain);
  8104. if (state.awaitDrain) state.awaitDrain--;
  8105. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  8106. state.flowing = true;
  8107. flow(src);
  8108. }
  8109. };
  8110. }
  8111. Readable.prototype.unpipe = function (dest) {
  8112. var state = this._readableState;
  8113. var unpipeInfo = { hasUnpiped: false };
  8114. // if we're not piping anywhere, then do nothing.
  8115. if (state.pipesCount === 0) return this;
  8116. // just one destination. most common case.
  8117. if (state.pipesCount === 1) {
  8118. // passed in one, but it's not the right one.
  8119. if (dest && dest !== state.pipes) return this;
  8120. if (!dest) dest = state.pipes;
  8121. // got a match.
  8122. state.pipes = null;
  8123. state.pipesCount = 0;
  8124. state.flowing = false;
  8125. if (dest) dest.emit('unpipe', this, unpipeInfo);
  8126. return this;
  8127. }
  8128. // slow case. multiple pipe destinations.
  8129. if (!dest) {
  8130. // remove all.
  8131. var dests = state.pipes;
  8132. var len = state.pipesCount;
  8133. state.pipes = null;
  8134. state.pipesCount = 0;
  8135. state.flowing = false;
  8136. for (var i = 0; i < len; i++) {
  8137. dests[i].emit('unpipe', this, unpipeInfo);
  8138. }return this;
  8139. }
  8140. // try to find the right one.
  8141. var index = indexOf(state.pipes, dest);
  8142. if (index === -1) return this;
  8143. state.pipes.splice(index, 1);
  8144. state.pipesCount -= 1;
  8145. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  8146. dest.emit('unpipe', this, unpipeInfo);
  8147. return this;
  8148. };
  8149. // set up data events if they are asked for
  8150. // Ensure readable listeners eventually get something
  8151. Readable.prototype.on = function (ev, fn) {
  8152. var res = Stream.prototype.on.call(this, ev, fn);
  8153. if (ev === 'data') {
  8154. // Start flowing on next tick if stream isn't explicitly paused
  8155. if (this._readableState.flowing !== false) this.resume();
  8156. } else if (ev === 'readable') {
  8157. var state = this._readableState;
  8158. if (!state.endEmitted && !state.readableListening) {
  8159. state.readableListening = state.needReadable = true;
  8160. state.emittedReadable = false;
  8161. if (!state.reading) {
  8162. pna.nextTick(nReadingNextTick, this);
  8163. } else if (state.length) {
  8164. emitReadable(this);
  8165. }
  8166. }
  8167. }
  8168. return res;
  8169. };
  8170. Readable.prototype.addListener = Readable.prototype.on;
  8171. function nReadingNextTick(self) {
  8172. debug('readable nexttick read 0');
  8173. self.read(0);
  8174. }
  8175. // pause() and resume() are remnants of the legacy readable stream API
  8176. // If the user uses them, then switch into old mode.
  8177. Readable.prototype.resume = function () {
  8178. var state = this._readableState;
  8179. if (!state.flowing) {
  8180. debug('resume');
  8181. state.flowing = true;
  8182. resume(this, state);
  8183. }
  8184. return this;
  8185. };
  8186. function resume(stream, state) {
  8187. if (!state.resumeScheduled) {
  8188. state.resumeScheduled = true;
  8189. pna.nextTick(resume_, stream, state);
  8190. }
  8191. }
  8192. function resume_(stream, state) {
  8193. if (!state.reading) {
  8194. debug('resume read 0');
  8195. stream.read(0);
  8196. }
  8197. state.resumeScheduled = false;
  8198. state.awaitDrain = 0;
  8199. stream.emit('resume');
  8200. flow(stream);
  8201. if (state.flowing && !state.reading) stream.read(0);
  8202. }
  8203. Readable.prototype.pause = function () {
  8204. debug('call pause flowing=%j', this._readableState.flowing);
  8205. if (false !== this._readableState.flowing) {
  8206. debug('pause');
  8207. this._readableState.flowing = false;
  8208. this.emit('pause');
  8209. }
  8210. return this;
  8211. };
  8212. function flow(stream) {
  8213. var state = stream._readableState;
  8214. debug('flow', state.flowing);
  8215. while (state.flowing && stream.read() !== null) {}
  8216. }
  8217. // wrap an old-style stream as the async data source.
  8218. // This is *not* part of the readable stream interface.
  8219. // It is an ugly unfortunate mess of history.
  8220. Readable.prototype.wrap = function (stream) {
  8221. var _this = this;
  8222. var state = this._readableState;
  8223. var paused = false;
  8224. stream.on('end', function () {
  8225. debug('wrapped end');
  8226. if (state.decoder && !state.ended) {
  8227. var chunk = state.decoder.end();
  8228. if (chunk && chunk.length) _this.push(chunk);
  8229. }
  8230. _this.push(null);
  8231. });
  8232. stream.on('data', function (chunk) {
  8233. debug('wrapped data');
  8234. if (state.decoder) chunk = state.decoder.write(chunk);
  8235. // don't skip over falsy values in objectMode
  8236. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  8237. var ret = _this.push(chunk);
  8238. if (!ret) {
  8239. paused = true;
  8240. stream.pause();
  8241. }
  8242. });
  8243. // proxy all the other methods.
  8244. // important when wrapping filters and duplexes.
  8245. for (var i in stream) {
  8246. if (this[i] === undefined && typeof stream[i] === 'function') {
  8247. this[i] = function (method) {
  8248. return function () {
  8249. return stream[method].apply(stream, arguments);
  8250. };
  8251. }(i);
  8252. }
  8253. }
  8254. // proxy certain important events.
  8255. for (var n = 0; n < kProxyEvents.length; n++) {
  8256. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  8257. }
  8258. // when we try to consume some more bytes, simply unpause the
  8259. // underlying stream.
  8260. this._read = function (n) {
  8261. debug('wrapped _read', n);
  8262. if (paused) {
  8263. paused = false;
  8264. stream.resume();
  8265. }
  8266. };
  8267. return this;
  8268. };
  8269. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  8270. // making it explicit this property is not enumerable
  8271. // because otherwise some prototype manipulation in
  8272. // userland will fail
  8273. enumerable: false,
  8274. get: function () {
  8275. return this._readableState.highWaterMark;
  8276. }
  8277. });
  8278. // exposed for testing purposes only.
  8279. Readable._fromList = fromList;
  8280. // Pluck off n bytes from an array of buffers.
  8281. // Length is the combined lengths of all the buffers in the list.
  8282. // This function is designed to be inlinable, so please take care when making
  8283. // changes to the function body.
  8284. function fromList(n, state) {
  8285. // nothing buffered
  8286. if (state.length === 0) return null;
  8287. var ret;
  8288. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  8289. // read it all, truncate the list
  8290. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  8291. state.buffer.clear();
  8292. } else {
  8293. // read part of list
  8294. ret = fromListPartial(n, state.buffer, state.decoder);
  8295. }
  8296. return ret;
  8297. }
  8298. // Extracts only enough buffered data to satisfy the amount requested.
  8299. // This function is designed to be inlinable, so please take care when making
  8300. // changes to the function body.
  8301. function fromListPartial(n, list, hasStrings) {
  8302. var ret;
  8303. if (n < list.head.data.length) {
  8304. // slice is the same for buffers and strings
  8305. ret = list.head.data.slice(0, n);
  8306. list.head.data = list.head.data.slice(n);
  8307. } else if (n === list.head.data.length) {
  8308. // first chunk is a perfect match
  8309. ret = list.shift();
  8310. } else {
  8311. // result spans more than one buffer
  8312. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  8313. }
  8314. return ret;
  8315. }
  8316. // Copies a specified amount of characters from the list of buffered data
  8317. // chunks.
  8318. // This function is designed to be inlinable, so please take care when making
  8319. // changes to the function body.
  8320. function copyFromBufferString(n, list) {
  8321. var p = list.head;
  8322. var c = 1;
  8323. var ret = p.data;
  8324. n -= ret.length;
  8325. while (p = p.next) {
  8326. var str = p.data;
  8327. var nb = n > str.length ? str.length : n;
  8328. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  8329. n -= nb;
  8330. if (n === 0) {
  8331. if (nb === str.length) {
  8332. ++c;
  8333. if (p.next) list.head = p.next;else list.head = list.tail = null;
  8334. } else {
  8335. list.head = p;
  8336. p.data = str.slice(nb);
  8337. }
  8338. break;
  8339. }
  8340. ++c;
  8341. }
  8342. list.length -= c;
  8343. return ret;
  8344. }
  8345. // Copies a specified amount of bytes from the list of buffered data chunks.
  8346. // This function is designed to be inlinable, so please take care when making
  8347. // changes to the function body.
  8348. function copyFromBuffer(n, list) {
  8349. var ret = Buffer.allocUnsafe(n);
  8350. var p = list.head;
  8351. var c = 1;
  8352. p.data.copy(ret);
  8353. n -= p.data.length;
  8354. while (p = p.next) {
  8355. var buf = p.data;
  8356. var nb = n > buf.length ? buf.length : n;
  8357. buf.copy(ret, ret.length - n, 0, nb);
  8358. n -= nb;
  8359. if (n === 0) {
  8360. if (nb === buf.length) {
  8361. ++c;
  8362. if (p.next) list.head = p.next;else list.head = list.tail = null;
  8363. } else {
  8364. list.head = p;
  8365. p.data = buf.slice(nb);
  8366. }
  8367. break;
  8368. }
  8369. ++c;
  8370. }
  8371. list.length -= c;
  8372. return ret;
  8373. }
  8374. function endReadable(stream) {
  8375. var state = stream._readableState;
  8376. // If we get here before consuming all the bytes, then that is a
  8377. // bug in node. Should never happen.
  8378. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  8379. if (!state.endEmitted) {
  8380. state.ended = true;
  8381. pna.nextTick(endReadableNT, state, stream);
  8382. }
  8383. }
  8384. function endReadableNT(state, stream) {
  8385. // Check that we didn't get one last unshift.
  8386. if (!state.endEmitted && state.length === 0) {
  8387. state.endEmitted = true;
  8388. stream.readable = false;
  8389. stream.emit('end');
  8390. }
  8391. }
  8392. function indexOf(xs, x) {
  8393. for (var i = 0, l = xs.length; i < l; i++) {
  8394. if (xs[i] === x) return i;
  8395. }
  8396. return -1;
  8397. }
  8398. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8399. },{"./_stream_duplex":102,"./internal/streams/BufferList":107,"./internal/streams/destroy":108,"./internal/streams/stream":109,"_process":96,"core-util-is":13,"events":79,"inherits":84,"isarray":86,"process-nextick-args":95,"safe-buffer":110,"string_decoder/":111,"util":11}],105:[function(require,module,exports){
  8400. // Copyright Joyent, Inc. and other Node contributors.
  8401. //
  8402. // Permission is hereby granted, free of charge, to any person obtaining a
  8403. // copy of this software and associated documentation files (the
  8404. // "Software"), to deal in the Software without restriction, including
  8405. // without limitation the rights to use, copy, modify, merge, publish,
  8406. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8407. // persons to whom the Software is furnished to do so, subject to the
  8408. // following conditions:
  8409. //
  8410. // The above copyright notice and this permission notice shall be included
  8411. // in all copies or substantial portions of the Software.
  8412. //
  8413. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8414. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8415. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8416. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8417. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8418. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8419. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8420. // a transform stream is a readable/writable stream where you do
  8421. // something with the data. Sometimes it's called a "filter",
  8422. // but that's not a great name for it, since that implies a thing where
  8423. // some bits pass through, and others are simply ignored. (That would
  8424. // be a valid example of a transform, of course.)
  8425. //
  8426. // While the output is causally related to the input, it's not a
  8427. // necessarily symmetric or synchronous transformation. For example,
  8428. // a zlib stream might take multiple plain-text writes(), and then
  8429. // emit a single compressed chunk some time in the future.
  8430. //
  8431. // Here's how this works:
  8432. //
  8433. // The Transform stream has all the aspects of the readable and writable
  8434. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  8435. // internally, and returns false if there's a lot of pending writes
  8436. // buffered up. When you call read(), that calls _read(n) until
  8437. // there's enough pending readable data buffered up.
  8438. //
  8439. // In a transform stream, the written data is placed in a buffer. When
  8440. // _read(n) is called, it transforms the queued up data, calling the
  8441. // buffered _write cb's as it consumes chunks. If consuming a single
  8442. // written chunk would result in multiple output chunks, then the first
  8443. // outputted bit calls the readcb, and subsequent chunks just go into
  8444. // the read buffer, and will cause it to emit 'readable' if necessary.
  8445. //
  8446. // This way, back-pressure is actually determined by the reading side,
  8447. // since _read has to be called to start processing a new chunk. However,
  8448. // a pathological inflate type of transform can cause excessive buffering
  8449. // here. For example, imagine a stream where every byte of input is
  8450. // interpreted as an integer from 0-255, and then results in that many
  8451. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  8452. // 1kb of data being output. In this case, you could write a very small
  8453. // amount of input, and end up with a very large amount of output. In
  8454. // such a pathological inflating mechanism, there'd be no way to tell
  8455. // the system to stop doing the transform. A single 4MB write could
  8456. // cause the system to run out of memory.
  8457. //
  8458. // However, even in such a pathological case, only a single written chunk
  8459. // would be consumed, and then the rest would wait (un-transformed) until
  8460. // the results of the previous transformed chunk were consumed.
  8461. 'use strict';
  8462. module.exports = Transform;
  8463. var Duplex = require('./_stream_duplex');
  8464. /*<replacement>*/
  8465. var util = Object.create(require('core-util-is'));
  8466. util.inherits = require('inherits');
  8467. /*</replacement>*/
  8468. util.inherits(Transform, Duplex);
  8469. function afterTransform(er, data) {
  8470. var ts = this._transformState;
  8471. ts.transforming = false;
  8472. var cb = ts.writecb;
  8473. if (!cb) {
  8474. return this.emit('error', new Error('write callback called multiple times'));
  8475. }
  8476. ts.writechunk = null;
  8477. ts.writecb = null;
  8478. if (data != null) // single equals check for both `null` and `undefined`
  8479. this.push(data);
  8480. cb(er);
  8481. var rs = this._readableState;
  8482. rs.reading = false;
  8483. if (rs.needReadable || rs.length < rs.highWaterMark) {
  8484. this._read(rs.highWaterMark);
  8485. }
  8486. }
  8487. function Transform(options) {
  8488. if (!(this instanceof Transform)) return new Transform(options);
  8489. Duplex.call(this, options);
  8490. this._transformState = {
  8491. afterTransform: afterTransform.bind(this),
  8492. needTransform: false,
  8493. transforming: false,
  8494. writecb: null,
  8495. writechunk: null,
  8496. writeencoding: null
  8497. };
  8498. // start out asking for a readable event once data is transformed.
  8499. this._readableState.needReadable = true;
  8500. // we have implemented the _read method, and done the other things
  8501. // that Readable wants before the first _read call, so unset the
  8502. // sync guard flag.
  8503. this._readableState.sync = false;
  8504. if (options) {
  8505. if (typeof options.transform === 'function') this._transform = options.transform;
  8506. if (typeof options.flush === 'function') this._flush = options.flush;
  8507. }
  8508. // When the writable side finishes, then flush out anything remaining.
  8509. this.on('prefinish', prefinish);
  8510. }
  8511. function prefinish() {
  8512. var _this = this;
  8513. if (typeof this._flush === 'function') {
  8514. this._flush(function (er, data) {
  8515. done(_this, er, data);
  8516. });
  8517. } else {
  8518. done(this, null, null);
  8519. }
  8520. }
  8521. Transform.prototype.push = function (chunk, encoding) {
  8522. this._transformState.needTransform = false;
  8523. return Duplex.prototype.push.call(this, chunk, encoding);
  8524. };
  8525. // This is the part where you do stuff!
  8526. // override this function in implementation classes.
  8527. // 'chunk' is an input chunk.
  8528. //
  8529. // Call `push(newChunk)` to pass along transformed output
  8530. // to the readable side. You may call 'push' zero or more times.
  8531. //
  8532. // Call `cb(err)` when you are done with this chunk. If you pass
  8533. // an error, then that'll put the hurt on the whole operation. If you
  8534. // never call cb(), then you'll never get another chunk.
  8535. Transform.prototype._transform = function (chunk, encoding, cb) {
  8536. throw new Error('_transform() is not implemented');
  8537. };
  8538. Transform.prototype._write = function (chunk, encoding, cb) {
  8539. var ts = this._transformState;
  8540. ts.writecb = cb;
  8541. ts.writechunk = chunk;
  8542. ts.writeencoding = encoding;
  8543. if (!ts.transforming) {
  8544. var rs = this._readableState;
  8545. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  8546. }
  8547. };
  8548. // Doesn't matter what the args are here.
  8549. // _transform does all the work.
  8550. // That we got here means that the readable side wants more data.
  8551. Transform.prototype._read = function (n) {
  8552. var ts = this._transformState;
  8553. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  8554. ts.transforming = true;
  8555. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  8556. } else {
  8557. // mark that we need a transform, so that any data that comes in
  8558. // will get processed, now that we've asked for it.
  8559. ts.needTransform = true;
  8560. }
  8561. };
  8562. Transform.prototype._destroy = function (err, cb) {
  8563. var _this2 = this;
  8564. Duplex.prototype._destroy.call(this, err, function (err2) {
  8565. cb(err2);
  8566. _this2.emit('close');
  8567. });
  8568. };
  8569. function done(stream, er, data) {
  8570. if (er) return stream.emit('error', er);
  8571. if (data != null) // single equals check for both `null` and `undefined`
  8572. stream.push(data);
  8573. // if there's nothing in the write buffer, then that means
  8574. // that nothing more will ever be provided
  8575. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  8576. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  8577. return stream.push(null);
  8578. }
  8579. },{"./_stream_duplex":102,"core-util-is":13,"inherits":84}],106:[function(require,module,exports){
  8580. (function (process,global,setImmediate){(function (){
  8581. // Copyright Joyent, Inc. and other Node contributors.
  8582. //
  8583. // Permission is hereby granted, free of charge, to any person obtaining a
  8584. // copy of this software and associated documentation files (the
  8585. // "Software"), to deal in the Software without restriction, including
  8586. // without limitation the rights to use, copy, modify, merge, publish,
  8587. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8588. // persons to whom the Software is furnished to do so, subject to the
  8589. // following conditions:
  8590. //
  8591. // The above copyright notice and this permission notice shall be included
  8592. // in all copies or substantial portions of the Software.
  8593. //
  8594. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8595. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8596. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8597. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8598. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8599. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8600. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8601. // A bit simpler than readable streams.
  8602. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  8603. // the drain event emission and buffering.
  8604. 'use strict';
  8605. /*<replacement>*/
  8606. var pna = require('process-nextick-args');
  8607. /*</replacement>*/
  8608. module.exports = Writable;
  8609. /* <replacement> */
  8610. function WriteReq(chunk, encoding, cb) {
  8611. this.chunk = chunk;
  8612. this.encoding = encoding;
  8613. this.callback = cb;
  8614. this.next = null;
  8615. }
  8616. // It seems a linked list but it is not
  8617. // there will be only 2 of these for each stream
  8618. function CorkedRequest(state) {
  8619. var _this = this;
  8620. this.next = null;
  8621. this.entry = null;
  8622. this.finish = function () {
  8623. onCorkedFinish(_this, state);
  8624. };
  8625. }
  8626. /* </replacement> */
  8627. /*<replacement>*/
  8628. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  8629. /*</replacement>*/
  8630. /*<replacement>*/
  8631. var Duplex;
  8632. /*</replacement>*/
  8633. Writable.WritableState = WritableState;
  8634. /*<replacement>*/
  8635. var util = Object.create(require('core-util-is'));
  8636. util.inherits = require('inherits');
  8637. /*</replacement>*/
  8638. /*<replacement>*/
  8639. var internalUtil = {
  8640. deprecate: require('util-deprecate')
  8641. };
  8642. /*</replacement>*/
  8643. /*<replacement>*/
  8644. var Stream = require('./internal/streams/stream');
  8645. /*</replacement>*/
  8646. /*<replacement>*/
  8647. var Buffer = require('safe-buffer').Buffer;
  8648. var OurUint8Array = global.Uint8Array || function () {};
  8649. function _uint8ArrayToBuffer(chunk) {
  8650. return Buffer.from(chunk);
  8651. }
  8652. function _isUint8Array(obj) {
  8653. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  8654. }
  8655. /*</replacement>*/
  8656. var destroyImpl = require('./internal/streams/destroy');
  8657. util.inherits(Writable, Stream);
  8658. function nop() {}
  8659. function WritableState(options, stream) {
  8660. Duplex = Duplex || require('./_stream_duplex');
  8661. options = options || {};
  8662. // Duplex streams are both readable and writable, but share
  8663. // the same options object.
  8664. // However, some cases require setting options to different
  8665. // values for the readable and the writable sides of the duplex stream.
  8666. // These options can be provided separately as readableXXX and writableXXX.
  8667. var isDuplex = stream instanceof Duplex;
  8668. // object stream flag to indicate whether or not this stream
  8669. // contains buffers or objects.
  8670. this.objectMode = !!options.objectMode;
  8671. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  8672. // the point at which write() starts returning false
  8673. // Note: 0 is a valid value, means that we always return false if
  8674. // the entire buffer is not flushed immediately on write()
  8675. var hwm = options.highWaterMark;
  8676. var writableHwm = options.writableHighWaterMark;
  8677. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  8678. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  8679. // cast to ints.
  8680. this.highWaterMark = Math.floor(this.highWaterMark);
  8681. // if _final has been called
  8682. this.finalCalled = false;
  8683. // drain event flag.
  8684. this.needDrain = false;
  8685. // at the start of calling end()
  8686. this.ending = false;
  8687. // when end() has been called, and returned
  8688. this.ended = false;
  8689. // when 'finish' is emitted
  8690. this.finished = false;
  8691. // has it been destroyed
  8692. this.destroyed = false;
  8693. // should we decode strings into buffers before passing to _write?
  8694. // this is here so that some node-core streams can optimize string
  8695. // handling at a lower level.
  8696. var noDecode = options.decodeStrings === false;
  8697. this.decodeStrings = !noDecode;
  8698. // Crypto is kind of old and crusty. Historically, its default string
  8699. // encoding is 'binary' so we have to make this configurable.
  8700. // Everything else in the universe uses 'utf8', though.
  8701. this.defaultEncoding = options.defaultEncoding || 'utf8';
  8702. // not an actual buffer we keep track of, but a measurement
  8703. // of how much we're waiting to get pushed to some underlying
  8704. // socket or file.
  8705. this.length = 0;
  8706. // a flag to see when we're in the middle of a write.
  8707. this.writing = false;
  8708. // when true all writes will be buffered until .uncork() call
  8709. this.corked = 0;
  8710. // a flag to be able to tell if the onwrite cb is called immediately,
  8711. // or on a later tick. We set this to true at first, because any
  8712. // actions that shouldn't happen until "later" should generally also
  8713. // not happen before the first write call.
  8714. this.sync = true;
  8715. // a flag to know if we're processing previously buffered items, which
  8716. // may call the _write() callback in the same tick, so that we don't
  8717. // end up in an overlapped onwrite situation.
  8718. this.bufferProcessing = false;
  8719. // the callback that's passed to _write(chunk,cb)
  8720. this.onwrite = function (er) {
  8721. onwrite(stream, er);
  8722. };
  8723. // the callback that the user supplies to write(chunk,encoding,cb)
  8724. this.writecb = null;
  8725. // the amount that is being written when _write is called.
  8726. this.writelen = 0;
  8727. this.bufferedRequest = null;
  8728. this.lastBufferedRequest = null;
  8729. // number of pending user-supplied write callbacks
  8730. // this must be 0 before 'finish' can be emitted
  8731. this.pendingcb = 0;
  8732. // emit prefinish if the only thing we're waiting for is _write cbs
  8733. // This is relevant for synchronous Transform streams
  8734. this.prefinished = false;
  8735. // True if the error was already emitted and should not be thrown again
  8736. this.errorEmitted = false;
  8737. // count buffered requests
  8738. this.bufferedRequestCount = 0;
  8739. // allocate the first CorkedRequest, there is always
  8740. // one allocated and free to use, and we maintain at most two
  8741. this.corkedRequestsFree = new CorkedRequest(this);
  8742. }
  8743. WritableState.prototype.getBuffer = function getBuffer() {
  8744. var current = this.bufferedRequest;
  8745. var out = [];
  8746. while (current) {
  8747. out.push(current);
  8748. current = current.next;
  8749. }
  8750. return out;
  8751. };
  8752. (function () {
  8753. try {
  8754. Object.defineProperty(WritableState.prototype, 'buffer', {
  8755. get: internalUtil.deprecate(function () {
  8756. return this.getBuffer();
  8757. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  8758. });
  8759. } catch (_) {}
  8760. })();
  8761. // Test _writableState for inheritance to account for Duplex streams,
  8762. // whose prototype chain only points to Readable.
  8763. var realHasInstance;
  8764. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  8765. realHasInstance = Function.prototype[Symbol.hasInstance];
  8766. Object.defineProperty(Writable, Symbol.hasInstance, {
  8767. value: function (object) {
  8768. if (realHasInstance.call(this, object)) return true;
  8769. if (this !== Writable) return false;
  8770. return object && object._writableState instanceof WritableState;
  8771. }
  8772. });
  8773. } else {
  8774. realHasInstance = function (object) {
  8775. return object instanceof this;
  8776. };
  8777. }
  8778. function Writable(options) {
  8779. Duplex = Duplex || require('./_stream_duplex');
  8780. // Writable ctor is applied to Duplexes, too.
  8781. // `realHasInstance` is necessary because using plain `instanceof`
  8782. // would return false, as no `_writableState` property is attached.
  8783. // Trying to use the custom `instanceof` for Writable here will also break the
  8784. // Node.js LazyTransform implementation, which has a non-trivial getter for
  8785. // `_writableState` that would lead to infinite recursion.
  8786. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  8787. return new Writable(options);
  8788. }
  8789. this._writableState = new WritableState(options, this);
  8790. // legacy.
  8791. this.writable = true;
  8792. if (options) {
  8793. if (typeof options.write === 'function') this._write = options.write;
  8794. if (typeof options.writev === 'function') this._writev = options.writev;
  8795. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  8796. if (typeof options.final === 'function') this._final = options.final;
  8797. }
  8798. Stream.call(this);
  8799. }
  8800. // Otherwise people can pipe Writable streams, which is just wrong.
  8801. Writable.prototype.pipe = function () {
  8802. this.emit('error', new Error('Cannot pipe, not readable'));
  8803. };
  8804. function writeAfterEnd(stream, cb) {
  8805. var er = new Error('write after end');
  8806. // TODO: defer error events consistently everywhere, not just the cb
  8807. stream.emit('error', er);
  8808. pna.nextTick(cb, er);
  8809. }
  8810. // Checks that a user-supplied chunk is valid, especially for the particular
  8811. // mode the stream is in. Currently this means that `null` is never accepted
  8812. // and undefined/non-string values are only allowed in object mode.
  8813. function validChunk(stream, state, chunk, cb) {
  8814. var valid = true;
  8815. var er = false;
  8816. if (chunk === null) {
  8817. er = new TypeError('May not write null values to stream');
  8818. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  8819. er = new TypeError('Invalid non-string/buffer chunk');
  8820. }
  8821. if (er) {
  8822. stream.emit('error', er);
  8823. pna.nextTick(cb, er);
  8824. valid = false;
  8825. }
  8826. return valid;
  8827. }
  8828. Writable.prototype.write = function (chunk, encoding, cb) {
  8829. var state = this._writableState;
  8830. var ret = false;
  8831. var isBuf = !state.objectMode && _isUint8Array(chunk);
  8832. if (isBuf && !Buffer.isBuffer(chunk)) {
  8833. chunk = _uint8ArrayToBuffer(chunk);
  8834. }
  8835. if (typeof encoding === 'function') {
  8836. cb = encoding;
  8837. encoding = null;
  8838. }
  8839. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  8840. if (typeof cb !== 'function') cb = nop;
  8841. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  8842. state.pendingcb++;
  8843. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  8844. }
  8845. return ret;
  8846. };
  8847. Writable.prototype.cork = function () {
  8848. var state = this._writableState;
  8849. state.corked++;
  8850. };
  8851. Writable.prototype.uncork = function () {
  8852. var state = this._writableState;
  8853. if (state.corked) {
  8854. state.corked--;
  8855. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  8856. }
  8857. };
  8858. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  8859. // node::ParseEncoding() requires lower case.
  8860. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  8861. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  8862. this._writableState.defaultEncoding = encoding;
  8863. return this;
  8864. };
  8865. function decodeChunk(state, chunk, encoding) {
  8866. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  8867. chunk = Buffer.from(chunk, encoding);
  8868. }
  8869. return chunk;
  8870. }
  8871. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  8872. // making it explicit this property is not enumerable
  8873. // because otherwise some prototype manipulation in
  8874. // userland will fail
  8875. enumerable: false,
  8876. get: function () {
  8877. return this._writableState.highWaterMark;
  8878. }
  8879. });
  8880. // if we're already writing something, then just put this
  8881. // in the queue, and wait our turn. Otherwise, call _write
  8882. // If we return false, then we need a drain event, so set that flag.
  8883. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  8884. if (!isBuf) {
  8885. var newChunk = decodeChunk(state, chunk, encoding);
  8886. if (chunk !== newChunk) {
  8887. isBuf = true;
  8888. encoding = 'buffer';
  8889. chunk = newChunk;
  8890. }
  8891. }
  8892. var len = state.objectMode ? 1 : chunk.length;
  8893. state.length += len;
  8894. var ret = state.length < state.highWaterMark;
  8895. // we must ensure that previous needDrain will not be reset to false.
  8896. if (!ret) state.needDrain = true;
  8897. if (state.writing || state.corked) {
  8898. var last = state.lastBufferedRequest;
  8899. state.lastBufferedRequest = {
  8900. chunk: chunk,
  8901. encoding: encoding,
  8902. isBuf: isBuf,
  8903. callback: cb,
  8904. next: null
  8905. };
  8906. if (last) {
  8907. last.next = state.lastBufferedRequest;
  8908. } else {
  8909. state.bufferedRequest = state.lastBufferedRequest;
  8910. }
  8911. state.bufferedRequestCount += 1;
  8912. } else {
  8913. doWrite(stream, state, false, len, chunk, encoding, cb);
  8914. }
  8915. return ret;
  8916. }
  8917. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  8918. state.writelen = len;
  8919. state.writecb = cb;
  8920. state.writing = true;
  8921. state.sync = true;
  8922. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  8923. state.sync = false;
  8924. }
  8925. function onwriteError(stream, state, sync, er, cb) {
  8926. --state.pendingcb;
  8927. if (sync) {
  8928. // defer the callback if we are being called synchronously
  8929. // to avoid piling up things on the stack
  8930. pna.nextTick(cb, er);
  8931. // this can emit finish, and it will always happen
  8932. // after error
  8933. pna.nextTick(finishMaybe, stream, state);
  8934. stream._writableState.errorEmitted = true;
  8935. stream.emit('error', er);
  8936. } else {
  8937. // the caller expect this to happen before if
  8938. // it is async
  8939. cb(er);
  8940. stream._writableState.errorEmitted = true;
  8941. stream.emit('error', er);
  8942. // this can emit finish, but finish must
  8943. // always follow error
  8944. finishMaybe(stream, state);
  8945. }
  8946. }
  8947. function onwriteStateUpdate(state) {
  8948. state.writing = false;
  8949. state.writecb = null;
  8950. state.length -= state.writelen;
  8951. state.writelen = 0;
  8952. }
  8953. function onwrite(stream, er) {
  8954. var state = stream._writableState;
  8955. var sync = state.sync;
  8956. var cb = state.writecb;
  8957. onwriteStateUpdate(state);
  8958. if (er) onwriteError(stream, state, sync, er, cb);else {
  8959. // Check if we're actually ready to finish, but don't emit yet
  8960. var finished = needFinish(state);
  8961. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  8962. clearBuffer(stream, state);
  8963. }
  8964. if (sync) {
  8965. /*<replacement>*/
  8966. asyncWrite(afterWrite, stream, state, finished, cb);
  8967. /*</replacement>*/
  8968. } else {
  8969. afterWrite(stream, state, finished, cb);
  8970. }
  8971. }
  8972. }
  8973. function afterWrite(stream, state, finished, cb) {
  8974. if (!finished) onwriteDrain(stream, state);
  8975. state.pendingcb--;
  8976. cb();
  8977. finishMaybe(stream, state);
  8978. }
  8979. // Must force callback to be called on nextTick, so that we don't
  8980. // emit 'drain' before the write() consumer gets the 'false' return
  8981. // value, and has a chance to attach a 'drain' listener.
  8982. function onwriteDrain(stream, state) {
  8983. if (state.length === 0 && state.needDrain) {
  8984. state.needDrain = false;
  8985. stream.emit('drain');
  8986. }
  8987. }
  8988. // if there's something in the buffer waiting, then process it
  8989. function clearBuffer(stream, state) {
  8990. state.bufferProcessing = true;
  8991. var entry = state.bufferedRequest;
  8992. if (stream._writev && entry && entry.next) {
  8993. // Fast case, write everything using _writev()
  8994. var l = state.bufferedRequestCount;
  8995. var buffer = new Array(l);
  8996. var holder = state.corkedRequestsFree;
  8997. holder.entry = entry;
  8998. var count = 0;
  8999. var allBuffers = true;
  9000. while (entry) {
  9001. buffer[count] = entry;
  9002. if (!entry.isBuf) allBuffers = false;
  9003. entry = entry.next;
  9004. count += 1;
  9005. }
  9006. buffer.allBuffers = allBuffers;
  9007. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  9008. // doWrite is almost always async, defer these to save a bit of time
  9009. // as the hot path ends with doWrite
  9010. state.pendingcb++;
  9011. state.lastBufferedRequest = null;
  9012. if (holder.next) {
  9013. state.corkedRequestsFree = holder.next;
  9014. holder.next = null;
  9015. } else {
  9016. state.corkedRequestsFree = new CorkedRequest(state);
  9017. }
  9018. state.bufferedRequestCount = 0;
  9019. } else {
  9020. // Slow case, write chunks one-by-one
  9021. while (entry) {
  9022. var chunk = entry.chunk;
  9023. var encoding = entry.encoding;
  9024. var cb = entry.callback;
  9025. var len = state.objectMode ? 1 : chunk.length;
  9026. doWrite(stream, state, false, len, chunk, encoding, cb);
  9027. entry = entry.next;
  9028. state.bufferedRequestCount--;
  9029. // if we didn't call the onwrite immediately, then
  9030. // it means that we need to wait until it does.
  9031. // also, that means that the chunk and cb are currently
  9032. // being processed, so move the buffer counter past them.
  9033. if (state.writing) {
  9034. break;
  9035. }
  9036. }
  9037. if (entry === null) state.lastBufferedRequest = null;
  9038. }
  9039. state.bufferedRequest = entry;
  9040. state.bufferProcessing = false;
  9041. }
  9042. Writable.prototype._write = function (chunk, encoding, cb) {
  9043. cb(new Error('_write() is not implemented'));
  9044. };
  9045. Writable.prototype._writev = null;
  9046. Writable.prototype.end = function (chunk, encoding, cb) {
  9047. var state = this._writableState;
  9048. if (typeof chunk === 'function') {
  9049. cb = chunk;
  9050. chunk = null;
  9051. encoding = null;
  9052. } else if (typeof encoding === 'function') {
  9053. cb = encoding;
  9054. encoding = null;
  9055. }
  9056. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  9057. // .end() fully uncorks
  9058. if (state.corked) {
  9059. state.corked = 1;
  9060. this.uncork();
  9061. }
  9062. // ignore unnecessary end() calls.
  9063. if (!state.ending && !state.finished) endWritable(this, state, cb);
  9064. };
  9065. function needFinish(state) {
  9066. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  9067. }
  9068. function callFinal(stream, state) {
  9069. stream._final(function (err) {
  9070. state.pendingcb--;
  9071. if (err) {
  9072. stream.emit('error', err);
  9073. }
  9074. state.prefinished = true;
  9075. stream.emit('prefinish');
  9076. finishMaybe(stream, state);
  9077. });
  9078. }
  9079. function prefinish(stream, state) {
  9080. if (!state.prefinished && !state.finalCalled) {
  9081. if (typeof stream._final === 'function') {
  9082. state.pendingcb++;
  9083. state.finalCalled = true;
  9084. pna.nextTick(callFinal, stream, state);
  9085. } else {
  9086. state.prefinished = true;
  9087. stream.emit('prefinish');
  9088. }
  9089. }
  9090. }
  9091. function finishMaybe(stream, state) {
  9092. var need = needFinish(state);
  9093. if (need) {
  9094. prefinish(stream, state);
  9095. if (state.pendingcb === 0) {
  9096. state.finished = true;
  9097. stream.emit('finish');
  9098. }
  9099. }
  9100. return need;
  9101. }
  9102. function endWritable(stream, state, cb) {
  9103. state.ending = true;
  9104. finishMaybe(stream, state);
  9105. if (cb) {
  9106. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  9107. }
  9108. state.ended = true;
  9109. stream.writable = false;
  9110. }
  9111. function onCorkedFinish(corkReq, state, err) {
  9112. var entry = corkReq.entry;
  9113. corkReq.entry = null;
  9114. while (entry) {
  9115. var cb = entry.callback;
  9116. state.pendingcb--;
  9117. cb(err);
  9118. entry = entry.next;
  9119. }
  9120. if (state.corkedRequestsFree) {
  9121. state.corkedRequestsFree.next = corkReq;
  9122. } else {
  9123. state.corkedRequestsFree = corkReq;
  9124. }
  9125. }
  9126. Object.defineProperty(Writable.prototype, 'destroyed', {
  9127. get: function () {
  9128. if (this._writableState === undefined) {
  9129. return false;
  9130. }
  9131. return this._writableState.destroyed;
  9132. },
  9133. set: function (value) {
  9134. // we ignore the value if the stream
  9135. // has not been initialized yet
  9136. if (!this._writableState) {
  9137. return;
  9138. }
  9139. // backward compatibility, the user is explicitly
  9140. // managing destroyed
  9141. this._writableState.destroyed = value;
  9142. }
  9143. });
  9144. Writable.prototype.destroy = destroyImpl.destroy;
  9145. Writable.prototype._undestroy = destroyImpl.undestroy;
  9146. Writable.prototype._destroy = function (err, cb) {
  9147. this.end();
  9148. cb(err);
  9149. };
  9150. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  9151. },{"./_stream_duplex":102,"./internal/streams/destroy":108,"./internal/streams/stream":109,"_process":96,"core-util-is":13,"inherits":84,"process-nextick-args":95,"safe-buffer":110,"timers":116,"util-deprecate":130}],107:[function(require,module,exports){
  9152. 'use strict';
  9153. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9154. var Buffer = require('safe-buffer').Buffer;
  9155. var util = require('util');
  9156. function copyBuffer(src, target, offset) {
  9157. src.copy(target, offset);
  9158. }
  9159. module.exports = function () {
  9160. function BufferList() {
  9161. _classCallCheck(this, BufferList);
  9162. this.head = null;
  9163. this.tail = null;
  9164. this.length = 0;
  9165. }
  9166. BufferList.prototype.push = function push(v) {
  9167. var entry = { data: v, next: null };
  9168. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  9169. this.tail = entry;
  9170. ++this.length;
  9171. };
  9172. BufferList.prototype.unshift = function unshift(v) {
  9173. var entry = { data: v, next: this.head };
  9174. if (this.length === 0) this.tail = entry;
  9175. this.head = entry;
  9176. ++this.length;
  9177. };
  9178. BufferList.prototype.shift = function shift() {
  9179. if (this.length === 0) return;
  9180. var ret = this.head.data;
  9181. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  9182. --this.length;
  9183. return ret;
  9184. };
  9185. BufferList.prototype.clear = function clear() {
  9186. this.head = this.tail = null;
  9187. this.length = 0;
  9188. };
  9189. BufferList.prototype.join = function join(s) {
  9190. if (this.length === 0) return '';
  9191. var p = this.head;
  9192. var ret = '' + p.data;
  9193. while (p = p.next) {
  9194. ret += s + p.data;
  9195. }return ret;
  9196. };
  9197. BufferList.prototype.concat = function concat(n) {
  9198. if (this.length === 0) return Buffer.alloc(0);
  9199. if (this.length === 1) return this.head.data;
  9200. var ret = Buffer.allocUnsafe(n >>> 0);
  9201. var p = this.head;
  9202. var i = 0;
  9203. while (p) {
  9204. copyBuffer(p.data, ret, i);
  9205. i += p.data.length;
  9206. p = p.next;
  9207. }
  9208. return ret;
  9209. };
  9210. return BufferList;
  9211. }();
  9212. if (util && util.inspect && util.inspect.custom) {
  9213. module.exports.prototype[util.inspect.custom] = function () {
  9214. var obj = util.inspect({ length: this.length });
  9215. return this.constructor.name + ' ' + obj;
  9216. };
  9217. }
  9218. },{"safe-buffer":110,"util":11}],108:[function(require,module,exports){
  9219. 'use strict';
  9220. /*<replacement>*/
  9221. var pna = require('process-nextick-args');
  9222. /*</replacement>*/
  9223. // undocumented cb() API, needed for core, not for public API
  9224. function destroy(err, cb) {
  9225. var _this = this;
  9226. var readableDestroyed = this._readableState && this._readableState.destroyed;
  9227. var writableDestroyed = this._writableState && this._writableState.destroyed;
  9228. if (readableDestroyed || writableDestroyed) {
  9229. if (cb) {
  9230. cb(err);
  9231. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  9232. pna.nextTick(emitErrorNT, this, err);
  9233. }
  9234. return this;
  9235. }
  9236. // we set destroyed to true before firing error callbacks in order
  9237. // to make it re-entrance safe in case destroy() is called within callbacks
  9238. if (this._readableState) {
  9239. this._readableState.destroyed = true;
  9240. }
  9241. // if this is a duplex stream mark the writable part as destroyed as well
  9242. if (this._writableState) {
  9243. this._writableState.destroyed = true;
  9244. }
  9245. this._destroy(err || null, function (err) {
  9246. if (!cb && err) {
  9247. pna.nextTick(emitErrorNT, _this, err);
  9248. if (_this._writableState) {
  9249. _this._writableState.errorEmitted = true;
  9250. }
  9251. } else if (cb) {
  9252. cb(err);
  9253. }
  9254. });
  9255. return this;
  9256. }
  9257. function undestroy() {
  9258. if (this._readableState) {
  9259. this._readableState.destroyed = false;
  9260. this._readableState.reading = false;
  9261. this._readableState.ended = false;
  9262. this._readableState.endEmitted = false;
  9263. }
  9264. if (this._writableState) {
  9265. this._writableState.destroyed = false;
  9266. this._writableState.ended = false;
  9267. this._writableState.ending = false;
  9268. this._writableState.finished = false;
  9269. this._writableState.errorEmitted = false;
  9270. }
  9271. }
  9272. function emitErrorNT(self, err) {
  9273. self.emit('error', err);
  9274. }
  9275. module.exports = {
  9276. destroy: destroy,
  9277. undestroy: undestroy
  9278. };
  9279. },{"process-nextick-args":95}],109:[function(require,module,exports){
  9280. module.exports = require('events').EventEmitter;
  9281. },{"events":79}],110:[function(require,module,exports){
  9282. /* eslint-disable node/no-deprecated-api */
  9283. var buffer = require('buffer')
  9284. var Buffer = buffer.Buffer
  9285. // alternative to using Object.keys for old browsers
  9286. function copyProps (src, dst) {
  9287. for (var key in src) {
  9288. dst[key] = src[key]
  9289. }
  9290. }
  9291. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  9292. module.exports = buffer
  9293. } else {
  9294. // Copy properties from require('buffer')
  9295. copyProps(buffer, exports)
  9296. exports.Buffer = SafeBuffer
  9297. }
  9298. function SafeBuffer (arg, encodingOrOffset, length) {
  9299. return Buffer(arg, encodingOrOffset, length)
  9300. }
  9301. // Copy static methods from Buffer
  9302. copyProps(Buffer, SafeBuffer)
  9303. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  9304. if (typeof arg === 'number') {
  9305. throw new TypeError('Argument must not be a number')
  9306. }
  9307. return Buffer(arg, encodingOrOffset, length)
  9308. }
  9309. SafeBuffer.alloc = function (size, fill, encoding) {
  9310. if (typeof size !== 'number') {
  9311. throw new TypeError('Argument must be a number')
  9312. }
  9313. var buf = Buffer(size)
  9314. if (fill !== undefined) {
  9315. if (typeof encoding === 'string') {
  9316. buf.fill(fill, encoding)
  9317. } else {
  9318. buf.fill(fill)
  9319. }
  9320. } else {
  9321. buf.fill(0)
  9322. }
  9323. return buf
  9324. }
  9325. SafeBuffer.allocUnsafe = function (size) {
  9326. if (typeof size !== 'number') {
  9327. throw new TypeError('Argument must be a number')
  9328. }
  9329. return Buffer(size)
  9330. }
  9331. SafeBuffer.allocUnsafeSlow = function (size) {
  9332. if (typeof size !== 'number') {
  9333. throw new TypeError('Argument must be a number')
  9334. }
  9335. return buffer.SlowBuffer(size)
  9336. }
  9337. },{"buffer":12}],111:[function(require,module,exports){
  9338. // Copyright Joyent, Inc. and other Node contributors.
  9339. //
  9340. // Permission is hereby granted, free of charge, to any person obtaining a
  9341. // copy of this software and associated documentation files (the
  9342. // "Software"), to deal in the Software without restriction, including
  9343. // without limitation the rights to use, copy, modify, merge, publish,
  9344. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9345. // persons to whom the Software is furnished to do so, subject to the
  9346. // following conditions:
  9347. //
  9348. // The above copyright notice and this permission notice shall be included
  9349. // in all copies or substantial portions of the Software.
  9350. //
  9351. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9352. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9353. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9354. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9355. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9356. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9357. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9358. 'use strict';
  9359. /*<replacement>*/
  9360. var Buffer = require('safe-buffer').Buffer;
  9361. /*</replacement>*/
  9362. var isEncoding = Buffer.isEncoding || function (encoding) {
  9363. encoding = '' + encoding;
  9364. switch (encoding && encoding.toLowerCase()) {
  9365. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  9366. return true;
  9367. default:
  9368. return false;
  9369. }
  9370. };
  9371. function _normalizeEncoding(enc) {
  9372. if (!enc) return 'utf8';
  9373. var retried;
  9374. while (true) {
  9375. switch (enc) {
  9376. case 'utf8':
  9377. case 'utf-8':
  9378. return 'utf8';
  9379. case 'ucs2':
  9380. case 'ucs-2':
  9381. case 'utf16le':
  9382. case 'utf-16le':
  9383. return 'utf16le';
  9384. case 'latin1':
  9385. case 'binary':
  9386. return 'latin1';
  9387. case 'base64':
  9388. case 'ascii':
  9389. case 'hex':
  9390. return enc;
  9391. default:
  9392. if (retried) return; // undefined
  9393. enc = ('' + enc).toLowerCase();
  9394. retried = true;
  9395. }
  9396. }
  9397. };
  9398. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  9399. // modules monkey-patch it to support additional encodings
  9400. function normalizeEncoding(enc) {
  9401. var nenc = _normalizeEncoding(enc);
  9402. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  9403. return nenc || enc;
  9404. }
  9405. // StringDecoder provides an interface for efficiently splitting a series of
  9406. // buffers into a series of JS strings without breaking apart multi-byte
  9407. // characters.
  9408. exports.StringDecoder = StringDecoder;
  9409. function StringDecoder(encoding) {
  9410. this.encoding = normalizeEncoding(encoding);
  9411. var nb;
  9412. switch (this.encoding) {
  9413. case 'utf16le':
  9414. this.text = utf16Text;
  9415. this.end = utf16End;
  9416. nb = 4;
  9417. break;
  9418. case 'utf8':
  9419. this.fillLast = utf8FillLast;
  9420. nb = 4;
  9421. break;
  9422. case 'base64':
  9423. this.text = base64Text;
  9424. this.end = base64End;
  9425. nb = 3;
  9426. break;
  9427. default:
  9428. this.write = simpleWrite;
  9429. this.end = simpleEnd;
  9430. return;
  9431. }
  9432. this.lastNeed = 0;
  9433. this.lastTotal = 0;
  9434. this.lastChar = Buffer.allocUnsafe(nb);
  9435. }
  9436. StringDecoder.prototype.write = function (buf) {
  9437. if (buf.length === 0) return '';
  9438. var r;
  9439. var i;
  9440. if (this.lastNeed) {
  9441. r = this.fillLast(buf);
  9442. if (r === undefined) return '';
  9443. i = this.lastNeed;
  9444. this.lastNeed = 0;
  9445. } else {
  9446. i = 0;
  9447. }
  9448. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  9449. return r || '';
  9450. };
  9451. StringDecoder.prototype.end = utf8End;
  9452. // Returns only complete characters in a Buffer
  9453. StringDecoder.prototype.text = utf8Text;
  9454. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  9455. StringDecoder.prototype.fillLast = function (buf) {
  9456. if (this.lastNeed <= buf.length) {
  9457. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  9458. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  9459. }
  9460. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  9461. this.lastNeed -= buf.length;
  9462. };
  9463. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  9464. // continuation byte. If an invalid byte is detected, -2 is returned.
  9465. function utf8CheckByte(byte) {
  9466. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  9467. return byte >> 6 === 0x02 ? -1 : -2;
  9468. }
  9469. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  9470. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  9471. // needed to complete the UTF-8 character (if applicable) are returned.
  9472. function utf8CheckIncomplete(self, buf, i) {
  9473. var j = buf.length - 1;
  9474. if (j < i) return 0;
  9475. var nb = utf8CheckByte(buf[j]);
  9476. if (nb >= 0) {
  9477. if (nb > 0) self.lastNeed = nb - 1;
  9478. return nb;
  9479. }
  9480. if (--j < i || nb === -2) return 0;
  9481. nb = utf8CheckByte(buf[j]);
  9482. if (nb >= 0) {
  9483. if (nb > 0) self.lastNeed = nb - 2;
  9484. return nb;
  9485. }
  9486. if (--j < i || nb === -2) return 0;
  9487. nb = utf8CheckByte(buf[j]);
  9488. if (nb >= 0) {
  9489. if (nb > 0) {
  9490. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  9491. }
  9492. return nb;
  9493. }
  9494. return 0;
  9495. }
  9496. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  9497. // needed or are available. If we see a non-continuation byte where we expect
  9498. // one, we "replace" the validated continuation bytes we've seen so far with
  9499. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  9500. // behavior. The continuation byte check is included three times in the case
  9501. // where all of the continuation bytes for a character exist in the same buffer.
  9502. // It is also done this way as a slight performance increase instead of using a
  9503. // loop.
  9504. function utf8CheckExtraBytes(self, buf, p) {
  9505. if ((buf[0] & 0xC0) !== 0x80) {
  9506. self.lastNeed = 0;
  9507. return '\ufffd';
  9508. }
  9509. if (self.lastNeed > 1 && buf.length > 1) {
  9510. if ((buf[1] & 0xC0) !== 0x80) {
  9511. self.lastNeed = 1;
  9512. return '\ufffd';
  9513. }
  9514. if (self.lastNeed > 2 && buf.length > 2) {
  9515. if ((buf[2] & 0xC0) !== 0x80) {
  9516. self.lastNeed = 2;
  9517. return '\ufffd';
  9518. }
  9519. }
  9520. }
  9521. }
  9522. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  9523. function utf8FillLast(buf) {
  9524. var p = this.lastTotal - this.lastNeed;
  9525. var r = utf8CheckExtraBytes(this, buf, p);
  9526. if (r !== undefined) return r;
  9527. if (this.lastNeed <= buf.length) {
  9528. buf.copy(this.lastChar, p, 0, this.lastNeed);
  9529. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  9530. }
  9531. buf.copy(this.lastChar, p, 0, buf.length);
  9532. this.lastNeed -= buf.length;
  9533. }
  9534. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  9535. // partial character, the character's bytes are buffered until the required
  9536. // number of bytes are available.
  9537. function utf8Text(buf, i) {
  9538. var total = utf8CheckIncomplete(this, buf, i);
  9539. if (!this.lastNeed) return buf.toString('utf8', i);
  9540. this.lastTotal = total;
  9541. var end = buf.length - (total - this.lastNeed);
  9542. buf.copy(this.lastChar, 0, end);
  9543. return buf.toString('utf8', i, end);
  9544. }
  9545. // For UTF-8, a replacement character is added when ending on a partial
  9546. // character.
  9547. function utf8End(buf) {
  9548. var r = buf && buf.length ? this.write(buf) : '';
  9549. if (this.lastNeed) return r + '\ufffd';
  9550. return r;
  9551. }
  9552. // UTF-16LE typically needs two bytes per character, but even if we have an even
  9553. // number of bytes available, we need to check if we end on a leading/high
  9554. // surrogate. In that case, we need to wait for the next two bytes in order to
  9555. // decode the last character properly.
  9556. function utf16Text(buf, i) {
  9557. if ((buf.length - i) % 2 === 0) {
  9558. var r = buf.toString('utf16le', i);
  9559. if (r) {
  9560. var c = r.charCodeAt(r.length - 1);
  9561. if (c >= 0xD800 && c <= 0xDBFF) {
  9562. this.lastNeed = 2;
  9563. this.lastTotal = 4;
  9564. this.lastChar[0] = buf[buf.length - 2];
  9565. this.lastChar[1] = buf[buf.length - 1];
  9566. return r.slice(0, -1);
  9567. }
  9568. }
  9569. return r;
  9570. }
  9571. this.lastNeed = 1;
  9572. this.lastTotal = 2;
  9573. this.lastChar[0] = buf[buf.length - 1];
  9574. return buf.toString('utf16le', i, buf.length - 1);
  9575. }
  9576. // For UTF-16LE we do not explicitly append special replacement characters if we
  9577. // end on a partial character, we simply let v8 handle that.
  9578. function utf16End(buf) {
  9579. var r = buf && buf.length ? this.write(buf) : '';
  9580. if (this.lastNeed) {
  9581. var end = this.lastTotal - this.lastNeed;
  9582. return r + this.lastChar.toString('utf16le', 0, end);
  9583. }
  9584. return r;
  9585. }
  9586. function base64Text(buf, i) {
  9587. var n = (buf.length - i) % 3;
  9588. if (n === 0) return buf.toString('base64', i);
  9589. this.lastNeed = 3 - n;
  9590. this.lastTotal = 3;
  9591. if (n === 1) {
  9592. this.lastChar[0] = buf[buf.length - 1];
  9593. } else {
  9594. this.lastChar[0] = buf[buf.length - 2];
  9595. this.lastChar[1] = buf[buf.length - 1];
  9596. }
  9597. return buf.toString('base64', i, buf.length - n);
  9598. }
  9599. function base64End(buf) {
  9600. var r = buf && buf.length ? this.write(buf) : '';
  9601. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  9602. return r;
  9603. }
  9604. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  9605. function simpleWrite(buf) {
  9606. return buf.toString(this.encoding);
  9607. }
  9608. function simpleEnd(buf) {
  9609. return buf && buf.length ? this.write(buf) : '';
  9610. }
  9611. },{"safe-buffer":110}],112:[function(require,module,exports){
  9612. exports = module.exports = require('./lib/_stream_readable.js');
  9613. exports.Stream = exports;
  9614. exports.Readable = exports;
  9615. exports.Writable = require('./lib/_stream_writable.js');
  9616. exports.Duplex = require('./lib/_stream_duplex.js');
  9617. exports.Transform = require('./lib/_stream_transform.js');
  9618. exports.PassThrough = require('./lib/_stream_passthrough.js');
  9619. },{"./lib/_stream_duplex.js":102,"./lib/_stream_passthrough.js":103,"./lib/_stream_readable.js":104,"./lib/_stream_transform.js":105,"./lib/_stream_writable.js":106}],113:[function(require,module,exports){
  9620. 'use strict'
  9621. function ReInterval (callback, interval, args) {
  9622. var self = this;
  9623. this._callback = callback;
  9624. this._args = args;
  9625. this._interval = setInterval(callback, interval, this._args);
  9626. this.reschedule = function (interval) {
  9627. // if no interval entered, use the interval passed in on creation
  9628. if (!interval)
  9629. interval = self._interval;
  9630. if (self._interval)
  9631. clearInterval(self._interval);
  9632. self._interval = setInterval(self._callback, interval, self._args);
  9633. };
  9634. this.clear = function () {
  9635. if (self._interval) {
  9636. clearInterval(self._interval);
  9637. self._interval = undefined;
  9638. }
  9639. };
  9640. this.destroy = function () {
  9641. if (self._interval) {
  9642. clearInterval(self._interval);
  9643. }
  9644. self._callback = undefined;
  9645. self._interval = undefined;
  9646. self._args = undefined;
  9647. };
  9648. }
  9649. function reInterval () {
  9650. if (typeof arguments[0] !== 'function')
  9651. throw new Error('callback needed');
  9652. if (typeof arguments[1] !== 'number')
  9653. throw new Error('interval needed');
  9654. var args;
  9655. if (arguments.length > 0) {
  9656. args = new Array(arguments.length - 2);
  9657. for (var i = 0; i < args.length; i++) {
  9658. args[i] = arguments[i + 2];
  9659. }
  9660. }
  9661. return new ReInterval(arguments[0], arguments[1], args);
  9662. }
  9663. module.exports = reInterval;
  9664. },{}],114:[function(require,module,exports){
  9665. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  9666. /* eslint-disable node/no-deprecated-api */
  9667. var buffer = require('buffer')
  9668. var Buffer = buffer.Buffer
  9669. // alternative to using Object.keys for old browsers
  9670. function copyProps (src, dst) {
  9671. for (var key in src) {
  9672. dst[key] = src[key]
  9673. }
  9674. }
  9675. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  9676. module.exports = buffer
  9677. } else {
  9678. // Copy properties from require('buffer')
  9679. copyProps(buffer, exports)
  9680. exports.Buffer = SafeBuffer
  9681. }
  9682. function SafeBuffer (arg, encodingOrOffset, length) {
  9683. return Buffer(arg, encodingOrOffset, length)
  9684. }
  9685. SafeBuffer.prototype = Object.create(Buffer.prototype)
  9686. // Copy static methods from Buffer
  9687. copyProps(Buffer, SafeBuffer)
  9688. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  9689. if (typeof arg === 'number') {
  9690. throw new TypeError('Argument must not be a number')
  9691. }
  9692. return Buffer(arg, encodingOrOffset, length)
  9693. }
  9694. SafeBuffer.alloc = function (size, fill, encoding) {
  9695. if (typeof size !== 'number') {
  9696. throw new TypeError('Argument must be a number')
  9697. }
  9698. var buf = Buffer(size)
  9699. if (fill !== undefined) {
  9700. if (typeof encoding === 'string') {
  9701. buf.fill(fill, encoding)
  9702. } else {
  9703. buf.fill(fill)
  9704. }
  9705. } else {
  9706. buf.fill(0)
  9707. }
  9708. return buf
  9709. }
  9710. SafeBuffer.allocUnsafe = function (size) {
  9711. if (typeof size !== 'number') {
  9712. throw new TypeError('Argument must be a number')
  9713. }
  9714. return Buffer(size)
  9715. }
  9716. SafeBuffer.allocUnsafeSlow = function (size) {
  9717. if (typeof size !== 'number') {
  9718. throw new TypeError('Argument must be a number')
  9719. }
  9720. return buffer.SlowBuffer(size)
  9721. }
  9722. },{"buffer":12}],115:[function(require,module,exports){
  9723. module.exports = shift
  9724. function shift (stream) {
  9725. var rs = stream._readableState
  9726. if (!rs) return null
  9727. return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs))
  9728. }
  9729. function getStateLength (state) {
  9730. if (state.buffer.length) {
  9731. // Since node 6.3.0 state.buffer is a BufferList not an array
  9732. if (state.buffer.head) {
  9733. return state.buffer.head.data.length
  9734. }
  9735. return state.buffer[0].length
  9736. }
  9737. return state.length
  9738. }
  9739. },{}],116:[function(require,module,exports){
  9740. (function (setImmediate,clearImmediate){(function (){
  9741. var nextTick = require('process/browser.js').nextTick;
  9742. var apply = Function.prototype.apply;
  9743. var slice = Array.prototype.slice;
  9744. var immediateIds = {};
  9745. var nextImmediateId = 0;
  9746. // DOM APIs, for completeness
  9747. exports.setTimeout = function() {
  9748. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  9749. };
  9750. exports.setInterval = function() {
  9751. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  9752. };
  9753. exports.clearTimeout =
  9754. exports.clearInterval = function(timeout) { timeout.close(); };
  9755. function Timeout(id, clearFn) {
  9756. this._id = id;
  9757. this._clearFn = clearFn;
  9758. }
  9759. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  9760. Timeout.prototype.close = function() {
  9761. this._clearFn.call(window, this._id);
  9762. };
  9763. // Does not start the time, just sets up the members needed.
  9764. exports.enroll = function(item, msecs) {
  9765. clearTimeout(item._idleTimeoutId);
  9766. item._idleTimeout = msecs;
  9767. };
  9768. exports.unenroll = function(item) {
  9769. clearTimeout(item._idleTimeoutId);
  9770. item._idleTimeout = -1;
  9771. };
  9772. exports._unrefActive = exports.active = function(item) {
  9773. clearTimeout(item._idleTimeoutId);
  9774. var msecs = item._idleTimeout;
  9775. if (msecs >= 0) {
  9776. item._idleTimeoutId = setTimeout(function onTimeout() {
  9777. if (item._onTimeout)
  9778. item._onTimeout();
  9779. }, msecs);
  9780. }
  9781. };
  9782. // That's not how node.js implements it but the exposed api is the same.
  9783. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  9784. var id = nextImmediateId++;
  9785. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  9786. immediateIds[id] = true;
  9787. nextTick(function onNextTick() {
  9788. if (immediateIds[id]) {
  9789. // fn.call() is faster so we optimize for the common use-case
  9790. // @see http://jsperf.com/call-apply-segu
  9791. if (args) {
  9792. fn.apply(null, args);
  9793. } else {
  9794. fn.call(null);
  9795. }
  9796. // Prevent ids from leaking
  9797. exports.clearImmediate(id);
  9798. }
  9799. });
  9800. return id;
  9801. };
  9802. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  9803. delete immediateIds[id];
  9804. };
  9805. }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  9806. },{"process/browser.js":96,"timers":116}],117:[function(require,module,exports){
  9807. "use strict";
  9808. var isPrototype = require("../prototype/is");
  9809. module.exports = function (value) {
  9810. if (typeof value !== "function") return false;
  9811. if (!hasOwnProperty.call(value, "length")) return false;
  9812. try {
  9813. if (typeof value.length !== "number") return false;
  9814. if (typeof value.call !== "function") return false;
  9815. if (typeof value.apply !== "function") return false;
  9816. } catch (error) {
  9817. return false;
  9818. }
  9819. return !isPrototype(value);
  9820. };
  9821. },{"../prototype/is":124}],118:[function(require,module,exports){
  9822. "use strict";
  9823. var isValue = require("../value/is")
  9824. , isObject = require("../object/is")
  9825. , stringCoerce = require("../string/coerce")
  9826. , toShortString = require("./to-short-string");
  9827. var resolveMessage = function (message, value) {
  9828. return message.replace("%v", toShortString(value));
  9829. };
  9830. module.exports = function (value, defaultMessage, inputOptions) {
  9831. if (!isObject(inputOptions)) throw new TypeError(resolveMessage(defaultMessage, value));
  9832. if (!isValue(value)) {
  9833. if ("default" in inputOptions) return inputOptions["default"];
  9834. if (inputOptions.isOptional) return null;
  9835. }
  9836. var errorMessage = stringCoerce(inputOptions.errorMessage);
  9837. if (!isValue(errorMessage)) errorMessage = defaultMessage;
  9838. throw new TypeError(resolveMessage(errorMessage, value));
  9839. };
  9840. },{"../object/is":121,"../string/coerce":125,"../value/is":127,"./to-short-string":120}],119:[function(require,module,exports){
  9841. "use strict";
  9842. module.exports = function (value) {
  9843. try {
  9844. return value.toString();
  9845. } catch (error) {
  9846. try { return String(value); }
  9847. catch (error2) { return null; }
  9848. }
  9849. };
  9850. },{}],120:[function(require,module,exports){
  9851. "use strict";
  9852. var safeToString = require("./safe-to-string");
  9853. var reNewLine = /[\n\r\u2028\u2029]/g;
  9854. module.exports = function (value) {
  9855. var string = safeToString(value);
  9856. if (string === null) return "<Non-coercible to string value>";
  9857. // Trim if too long
  9858. if (string.length > 100) string = string.slice(0, 99) + "…";
  9859. // Replace eventual new lines
  9860. string = string.replace(reNewLine, function (char) {
  9861. switch (char) {
  9862. case "\n":
  9863. return "\\n";
  9864. case "\r":
  9865. return "\\r";
  9866. case "\u2028":
  9867. return "\\u2028";
  9868. case "\u2029":
  9869. return "\\u2029";
  9870. /* istanbul ignore next */
  9871. default:
  9872. throw new Error("Unexpected character");
  9873. }
  9874. });
  9875. return string;
  9876. };
  9877. },{"./safe-to-string":119}],121:[function(require,module,exports){
  9878. "use strict";
  9879. var isValue = require("../value/is");
  9880. // prettier-ignore
  9881. var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ };
  9882. module.exports = function (value) {
  9883. if (!isValue(value)) return false;
  9884. return hasOwnProperty.call(possibleTypes, typeof value);
  9885. };
  9886. },{"../value/is":127}],122:[function(require,module,exports){
  9887. "use strict";
  9888. var resolveException = require("../lib/resolve-exception")
  9889. , is = require("./is");
  9890. module.exports = function (value/*, options*/) {
  9891. if (is(value)) return value;
  9892. return resolveException(value, "%v is not a plain function", arguments[1]);
  9893. };
  9894. },{"../lib/resolve-exception":118,"./is":123}],123:[function(require,module,exports){
  9895. "use strict";
  9896. var isFunction = require("../function/is");
  9897. var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString;
  9898. module.exports = function (value) {
  9899. if (!isFunction(value)) return false;
  9900. if (classRe.test(functionToString.call(value))) return false;
  9901. return true;
  9902. };
  9903. },{"../function/is":117}],124:[function(require,module,exports){
  9904. "use strict";
  9905. var isObject = require("../object/is");
  9906. module.exports = function (value) {
  9907. if (!isObject(value)) return false;
  9908. try {
  9909. if (!value.constructor) return false;
  9910. return value.constructor.prototype === value;
  9911. } catch (error) {
  9912. return false;
  9913. }
  9914. };
  9915. },{"../object/is":121}],125:[function(require,module,exports){
  9916. "use strict";
  9917. var isValue = require("../value/is")
  9918. , isObject = require("../object/is");
  9919. var objectToString = Object.prototype.toString;
  9920. module.exports = function (value) {
  9921. if (!isValue(value)) return null;
  9922. if (isObject(value)) {
  9923. // Reject Object.prototype.toString coercion
  9924. var valueToString = value.toString;
  9925. if (typeof valueToString !== "function") return null;
  9926. if (valueToString === objectToString) return null;
  9927. // Note: It can be object coming from other realm, still as there's no ES3 and CSP compliant
  9928. // way to resolve its realm's Object.prototype.toString it's left as not addressed edge case
  9929. }
  9930. try {
  9931. return "" + value; // Ensure implicit coercion
  9932. } catch (error) {
  9933. return null;
  9934. }
  9935. };
  9936. },{"../object/is":121,"../value/is":127}],126:[function(require,module,exports){
  9937. "use strict";
  9938. var resolveException = require("../lib/resolve-exception")
  9939. , is = require("./is");
  9940. module.exports = function (value/*, options*/) {
  9941. if (is(value)) return value;
  9942. return resolveException(value, "Cannot use %v", arguments[1]);
  9943. };
  9944. },{"../lib/resolve-exception":118,"./is":127}],127:[function(require,module,exports){
  9945. "use strict";
  9946. // ES3 safe
  9947. var _undefined = void 0;
  9948. module.exports = function (value) { return value !== _undefined && value !== null; };
  9949. },{}],128:[function(require,module,exports){
  9950. // Copyright Joyent, Inc. and other Node contributors.
  9951. //
  9952. // Permission is hereby granted, free of charge, to any person obtaining a
  9953. // copy of this software and associated documentation files (the
  9954. // "Software"), to deal in the Software without restriction, including
  9955. // without limitation the rights to use, copy, modify, merge, publish,
  9956. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9957. // persons to whom the Software is furnished to do so, subject to the
  9958. // following conditions:
  9959. //
  9960. // The above copyright notice and this permission notice shall be included
  9961. // in all copies or substantial portions of the Software.
  9962. //
  9963. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9964. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9965. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9966. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9967. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9968. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9969. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9970. 'use strict';
  9971. var punycode = require('punycode');
  9972. var util = require('./util');
  9973. exports.parse = urlParse;
  9974. exports.resolve = urlResolve;
  9975. exports.resolveObject = urlResolveObject;
  9976. exports.format = urlFormat;
  9977. exports.Url = Url;
  9978. function Url() {
  9979. this.protocol = null;
  9980. this.slashes = null;
  9981. this.auth = null;
  9982. this.host = null;
  9983. this.port = null;
  9984. this.hostname = null;
  9985. this.hash = null;
  9986. this.search = null;
  9987. this.query = null;
  9988. this.pathname = null;
  9989. this.path = null;
  9990. this.href = null;
  9991. }
  9992. // Reference: RFC 3986, RFC 1808, RFC 2396
  9993. // define these here so at least they only have to be
  9994. // compiled once on the first module load.
  9995. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  9996. portPattern = /:[0-9]*$/,
  9997. // Special case for a simple path URL
  9998. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  9999. // RFC 2396: characters reserved for delimiting URLs.
  10000. // We actually just auto-escape these.
  10001. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  10002. // RFC 2396: characters not allowed for various reasons.
  10003. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  10004. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  10005. autoEscape = ['\''].concat(unwise),
  10006. // Characters that are never ever allowed in a hostname.
  10007. // Note that any invalid chars are also handled, but these
  10008. // are the ones that are *expected* to be seen, so we fast-path
  10009. // them.
  10010. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  10011. hostEndingChars = ['/', '?', '#'],
  10012. hostnameMaxLen = 255,
  10013. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  10014. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  10015. // protocols that can allow "unsafe" and "unwise" chars.
  10016. unsafeProtocol = {
  10017. 'javascript': true,
  10018. 'javascript:': true
  10019. },
  10020. // protocols that never have a hostname.
  10021. hostlessProtocol = {
  10022. 'javascript': true,
  10023. 'javascript:': true
  10024. },
  10025. // protocols that always contain a // bit.
  10026. slashedProtocol = {
  10027. 'http': true,
  10028. 'https': true,
  10029. 'ftp': true,
  10030. 'gopher': true,
  10031. 'file': true,
  10032. 'http:': true,
  10033. 'https:': true,
  10034. 'ftp:': true,
  10035. 'gopher:': true,
  10036. 'file:': true
  10037. },
  10038. querystring = require('querystring');
  10039. function urlParse(url, parseQueryString, slashesDenoteHost) {
  10040. if (url && util.isObject(url) && url instanceof Url) return url;
  10041. var u = new Url;
  10042. u.parse(url, parseQueryString, slashesDenoteHost);
  10043. return u;
  10044. }
  10045. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  10046. if (!util.isString(url)) {
  10047. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  10048. }
  10049. // Copy chrome, IE, opera backslash-handling behavior.
  10050. // Back slashes before the query string get converted to forward slashes
  10051. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  10052. var queryIndex = url.indexOf('?'),
  10053. splitter =
  10054. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  10055. uSplit = url.split(splitter),
  10056. slashRegex = /\\/g;
  10057. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  10058. url = uSplit.join(splitter);
  10059. var rest = url;
  10060. // trim before proceeding.
  10061. // This is to support parse stuff like " http://foo.com \n"
  10062. rest = rest.trim();
  10063. if (!slashesDenoteHost && url.split('#').length === 1) {
  10064. // Try fast path regexp
  10065. var simplePath = simplePathPattern.exec(rest);
  10066. if (simplePath) {
  10067. this.path = rest;
  10068. this.href = rest;
  10069. this.pathname = simplePath[1];
  10070. if (simplePath[2]) {
  10071. this.search = simplePath[2];
  10072. if (parseQueryString) {
  10073. this.query = querystring.parse(this.search.substr(1));
  10074. } else {
  10075. this.query = this.search.substr(1);
  10076. }
  10077. } else if (parseQueryString) {
  10078. this.search = '';
  10079. this.query = {};
  10080. }
  10081. return this;
  10082. }
  10083. }
  10084. var proto = protocolPattern.exec(rest);
  10085. if (proto) {
  10086. proto = proto[0];
  10087. var lowerProto = proto.toLowerCase();
  10088. this.protocol = lowerProto;
  10089. rest = rest.substr(proto.length);
  10090. }
  10091. // figure out if it's got a host
  10092. // user@server is *always* interpreted as a hostname, and url
  10093. // resolution will treat //foo/bar as host=foo,path=bar because that's
  10094. // how the browser resolves relative URLs.
  10095. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  10096. var slashes = rest.substr(0, 2) === '//';
  10097. if (slashes && !(proto && hostlessProtocol[proto])) {
  10098. rest = rest.substr(2);
  10099. this.slashes = true;
  10100. }
  10101. }
  10102. if (!hostlessProtocol[proto] &&
  10103. (slashes || (proto && !slashedProtocol[proto]))) {
  10104. // there's a hostname.
  10105. // the first instance of /, ?, ;, or # ends the host.
  10106. //
  10107. // If there is an @ in the hostname, then non-host chars *are* allowed
  10108. // to the left of the last @ sign, unless some host-ending character
  10109. // comes *before* the @-sign.
  10110. // URLs are obnoxious.
  10111. //
  10112. // ex:
  10113. // http://a@b@c/ => user:a@b host:c
  10114. // http://a@b?@c => user:a host:c path:/?@c
  10115. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  10116. // Review our test case against browsers more comprehensively.
  10117. // find the first instance of any hostEndingChars
  10118. var hostEnd = -1;
  10119. for (var i = 0; i < hostEndingChars.length; i++) {
  10120. var hec = rest.indexOf(hostEndingChars[i]);
  10121. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  10122. hostEnd = hec;
  10123. }
  10124. // at this point, either we have an explicit point where the
  10125. // auth portion cannot go past, or the last @ char is the decider.
  10126. var auth, atSign;
  10127. if (hostEnd === -1) {
  10128. // atSign can be anywhere.
  10129. atSign = rest.lastIndexOf('@');
  10130. } else {
  10131. // atSign must be in auth portion.
  10132. // http://a@b/c@d => host:b auth:a path:/c@d
  10133. atSign = rest.lastIndexOf('@', hostEnd);
  10134. }
  10135. // Now we have a portion which is definitely the auth.
  10136. // Pull that off.
  10137. if (atSign !== -1) {
  10138. auth = rest.slice(0, atSign);
  10139. rest = rest.slice(atSign + 1);
  10140. this.auth = decodeURIComponent(auth);
  10141. }
  10142. // the host is the remaining to the left of the first non-host char
  10143. hostEnd = -1;
  10144. for (var i = 0; i < nonHostChars.length; i++) {
  10145. var hec = rest.indexOf(nonHostChars[i]);
  10146. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  10147. hostEnd = hec;
  10148. }
  10149. // if we still have not hit it, then the entire thing is a host.
  10150. if (hostEnd === -1)
  10151. hostEnd = rest.length;
  10152. this.host = rest.slice(0, hostEnd);
  10153. rest = rest.slice(hostEnd);
  10154. // pull out port.
  10155. this.parseHost();
  10156. // we've indicated that there is a hostname,
  10157. // so even if it's empty, it has to be present.
  10158. this.hostname = this.hostname || '';
  10159. // if hostname begins with [ and ends with ]
  10160. // assume that it's an IPv6 address.
  10161. var ipv6Hostname = this.hostname[0] === '[' &&
  10162. this.hostname[this.hostname.length - 1] === ']';
  10163. // validate a little.
  10164. if (!ipv6Hostname) {
  10165. var hostparts = this.hostname.split(/\./);
  10166. for (var i = 0, l = hostparts.length; i < l; i++) {
  10167. var part = hostparts[i];
  10168. if (!part) continue;
  10169. if (!part.match(hostnamePartPattern)) {
  10170. var newpart = '';
  10171. for (var j = 0, k = part.length; j < k; j++) {
  10172. if (part.charCodeAt(j) > 127) {
  10173. // we replace non-ASCII char with a temporary placeholder
  10174. // we need this to make sure size of hostname is not
  10175. // broken by replacing non-ASCII by nothing
  10176. newpart += 'x';
  10177. } else {
  10178. newpart += part[j];
  10179. }
  10180. }
  10181. // we test again with ASCII char only
  10182. if (!newpart.match(hostnamePartPattern)) {
  10183. var validParts = hostparts.slice(0, i);
  10184. var notHost = hostparts.slice(i + 1);
  10185. var bit = part.match(hostnamePartStart);
  10186. if (bit) {
  10187. validParts.push(bit[1]);
  10188. notHost.unshift(bit[2]);
  10189. }
  10190. if (notHost.length) {
  10191. rest = '/' + notHost.join('.') + rest;
  10192. }
  10193. this.hostname = validParts.join('.');
  10194. break;
  10195. }
  10196. }
  10197. }
  10198. }
  10199. if (this.hostname.length > hostnameMaxLen) {
  10200. this.hostname = '';
  10201. } else {
  10202. // hostnames are always lower case.
  10203. this.hostname = this.hostname.toLowerCase();
  10204. }
  10205. if (!ipv6Hostname) {
  10206. // IDNA Support: Returns a punycoded representation of "domain".
  10207. // It only converts parts of the domain name that
  10208. // have non-ASCII characters, i.e. it doesn't matter if
  10209. // you call it with a domain that already is ASCII-only.
  10210. this.hostname = punycode.toASCII(this.hostname);
  10211. }
  10212. var p = this.port ? ':' + this.port : '';
  10213. var h = this.hostname || '';
  10214. this.host = h + p;
  10215. this.href += this.host;
  10216. // strip [ and ] from the hostname
  10217. // the host field still retains them, though
  10218. if (ipv6Hostname) {
  10219. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  10220. if (rest[0] !== '/') {
  10221. rest = '/' + rest;
  10222. }
  10223. }
  10224. }
  10225. // now rest is set to the post-host stuff.
  10226. // chop off any delim chars.
  10227. if (!unsafeProtocol[lowerProto]) {
  10228. // First, make 100% sure that any "autoEscape" chars get
  10229. // escaped, even if encodeURIComponent doesn't think they
  10230. // need to be.
  10231. for (var i = 0, l = autoEscape.length; i < l; i++) {
  10232. var ae = autoEscape[i];
  10233. if (rest.indexOf(ae) === -1)
  10234. continue;
  10235. var esc = encodeURIComponent(ae);
  10236. if (esc === ae) {
  10237. esc = escape(ae);
  10238. }
  10239. rest = rest.split(ae).join(esc);
  10240. }
  10241. }
  10242. // chop off from the tail first.
  10243. var hash = rest.indexOf('#');
  10244. if (hash !== -1) {
  10245. // got a fragment string.
  10246. this.hash = rest.substr(hash);
  10247. rest = rest.slice(0, hash);
  10248. }
  10249. var qm = rest.indexOf('?');
  10250. if (qm !== -1) {
  10251. this.search = rest.substr(qm);
  10252. this.query = rest.substr(qm + 1);
  10253. if (parseQueryString) {
  10254. this.query = querystring.parse(this.query);
  10255. }
  10256. rest = rest.slice(0, qm);
  10257. } else if (parseQueryString) {
  10258. // no query string, but parseQueryString still requested
  10259. this.search = '';
  10260. this.query = {};
  10261. }
  10262. if (rest) this.pathname = rest;
  10263. if (slashedProtocol[lowerProto] &&
  10264. this.hostname && !this.pathname) {
  10265. this.pathname = '/';
  10266. }
  10267. //to support http.request
  10268. if (this.pathname || this.search) {
  10269. var p = this.pathname || '';
  10270. var s = this.search || '';
  10271. this.path = p + s;
  10272. }
  10273. // finally, reconstruct the href based on what has been validated.
  10274. this.href = this.format();
  10275. return this;
  10276. };
  10277. // format a parsed object into a url string
  10278. function urlFormat(obj) {
  10279. // ensure it's an object, and not a string url.
  10280. // If it's an obj, this is a no-op.
  10281. // this way, you can call url_format() on strings
  10282. // to clean up potentially wonky urls.
  10283. if (util.isString(obj)) obj = urlParse(obj);
  10284. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  10285. return obj.format();
  10286. }
  10287. Url.prototype.format = function() {
  10288. var auth = this.auth || '';
  10289. if (auth) {
  10290. auth = encodeURIComponent(auth);
  10291. auth = auth.replace(/%3A/i, ':');
  10292. auth += '@';
  10293. }
  10294. var protocol = this.protocol || '',
  10295. pathname = this.pathname || '',
  10296. hash = this.hash || '',
  10297. host = false,
  10298. query = '';
  10299. if (this.host) {
  10300. host = auth + this.host;
  10301. } else if (this.hostname) {
  10302. host = auth + (this.hostname.indexOf(':') === -1 ?
  10303. this.hostname :
  10304. '[' + this.hostname + ']');
  10305. if (this.port) {
  10306. host += ':' + this.port;
  10307. }
  10308. }
  10309. if (this.query &&
  10310. util.isObject(this.query) &&
  10311. Object.keys(this.query).length) {
  10312. query = querystring.stringify(this.query);
  10313. }
  10314. var search = this.search || (query && ('?' + query)) || '';
  10315. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  10316. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  10317. // unless they had them to begin with.
  10318. if (this.slashes ||
  10319. (!protocol || slashedProtocol[protocol]) && host !== false) {
  10320. host = '//' + (host || '');
  10321. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  10322. } else if (!host) {
  10323. host = '';
  10324. }
  10325. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  10326. if (search && search.charAt(0) !== '?') search = '?' + search;
  10327. pathname = pathname.replace(/[?#]/g, function(match) {
  10328. return encodeURIComponent(match);
  10329. });
  10330. search = search.replace('#', '%23');
  10331. return protocol + host + pathname + search + hash;
  10332. };
  10333. function urlResolve(source, relative) {
  10334. return urlParse(source, false, true).resolve(relative);
  10335. }
  10336. Url.prototype.resolve = function(relative) {
  10337. return this.resolveObject(urlParse(relative, false, true)).format();
  10338. };
  10339. function urlResolveObject(source, relative) {
  10340. if (!source) return relative;
  10341. return urlParse(source, false, true).resolveObject(relative);
  10342. }
  10343. Url.prototype.resolveObject = function(relative) {
  10344. if (util.isString(relative)) {
  10345. var rel = new Url();
  10346. rel.parse(relative, false, true);
  10347. relative = rel;
  10348. }
  10349. var result = new Url();
  10350. var tkeys = Object.keys(this);
  10351. for (var tk = 0; tk < tkeys.length; tk++) {
  10352. var tkey = tkeys[tk];
  10353. result[tkey] = this[tkey];
  10354. }
  10355. // hash is always overridden, no matter what.
  10356. // even href="" will remove it.
  10357. result.hash = relative.hash;
  10358. // if the relative url is empty, then there's nothing left to do here.
  10359. if (relative.href === '') {
  10360. result.href = result.format();
  10361. return result;
  10362. }
  10363. // hrefs like //foo/bar always cut to the protocol.
  10364. if (relative.slashes && !relative.protocol) {
  10365. // take everything except the protocol from relative
  10366. var rkeys = Object.keys(relative);
  10367. for (var rk = 0; rk < rkeys.length; rk++) {
  10368. var rkey = rkeys[rk];
  10369. if (rkey !== 'protocol')
  10370. result[rkey] = relative[rkey];
  10371. }
  10372. //urlParse appends trailing / to urls like http://www.example.com
  10373. if (slashedProtocol[result.protocol] &&
  10374. result.hostname && !result.pathname) {
  10375. result.path = result.pathname = '/';
  10376. }
  10377. result.href = result.format();
  10378. return result;
  10379. }
  10380. if (relative.protocol && relative.protocol !== result.protocol) {
  10381. // if it's a known url protocol, then changing
  10382. // the protocol does weird things
  10383. // first, if it's not file:, then we MUST have a host,
  10384. // and if there was a path
  10385. // to begin with, then we MUST have a path.
  10386. // if it is file:, then the host is dropped,
  10387. // because that's known to be hostless.
  10388. // anything else is assumed to be absolute.
  10389. if (!slashedProtocol[relative.protocol]) {
  10390. var keys = Object.keys(relative);
  10391. for (var v = 0; v < keys.length; v++) {
  10392. var k = keys[v];
  10393. result[k] = relative[k];
  10394. }
  10395. result.href = result.format();
  10396. return result;
  10397. }
  10398. result.protocol = relative.protocol;
  10399. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  10400. var relPath = (relative.pathname || '').split('/');
  10401. while (relPath.length && !(relative.host = relPath.shift()));
  10402. if (!relative.host) relative.host = '';
  10403. if (!relative.hostname) relative.hostname = '';
  10404. if (relPath[0] !== '') relPath.unshift('');
  10405. if (relPath.length < 2) relPath.unshift('');
  10406. result.pathname = relPath.join('/');
  10407. } else {
  10408. result.pathname = relative.pathname;
  10409. }
  10410. result.search = relative.search;
  10411. result.query = relative.query;
  10412. result.host = relative.host || '';
  10413. result.auth = relative.auth;
  10414. result.hostname = relative.hostname || relative.host;
  10415. result.port = relative.port;
  10416. // to support http.request
  10417. if (result.pathname || result.search) {
  10418. var p = result.pathname || '';
  10419. var s = result.search || '';
  10420. result.path = p + s;
  10421. }
  10422. result.slashes = result.slashes || relative.slashes;
  10423. result.href = result.format();
  10424. return result;
  10425. }
  10426. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  10427. isRelAbs = (
  10428. relative.host ||
  10429. relative.pathname && relative.pathname.charAt(0) === '/'
  10430. ),
  10431. mustEndAbs = (isRelAbs || isSourceAbs ||
  10432. (result.host && relative.pathname)),
  10433. removeAllDots = mustEndAbs,
  10434. srcPath = result.pathname && result.pathname.split('/') || [],
  10435. relPath = relative.pathname && relative.pathname.split('/') || [],
  10436. psychotic = result.protocol && !slashedProtocol[result.protocol];
  10437. // if the url is a non-slashed url, then relative
  10438. // links like ../.. should be able
  10439. // to crawl up to the hostname, as well. This is strange.
  10440. // result.protocol has already been set by now.
  10441. // Later on, put the first path part into the host field.
  10442. if (psychotic) {
  10443. result.hostname = '';
  10444. result.port = null;
  10445. if (result.host) {
  10446. if (srcPath[0] === '') srcPath[0] = result.host;
  10447. else srcPath.unshift(result.host);
  10448. }
  10449. result.host = '';
  10450. if (relative.protocol) {
  10451. relative.hostname = null;
  10452. relative.port = null;
  10453. if (relative.host) {
  10454. if (relPath[0] === '') relPath[0] = relative.host;
  10455. else relPath.unshift(relative.host);
  10456. }
  10457. relative.host = null;
  10458. }
  10459. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  10460. }
  10461. if (isRelAbs) {
  10462. // it's absolute.
  10463. result.host = (relative.host || relative.host === '') ?
  10464. relative.host : result.host;
  10465. result.hostname = (relative.hostname || relative.hostname === '') ?
  10466. relative.hostname : result.hostname;
  10467. result.search = relative.search;
  10468. result.query = relative.query;
  10469. srcPath = relPath;
  10470. // fall through to the dot-handling below.
  10471. } else if (relPath.length) {
  10472. // it's relative
  10473. // throw away the existing file, and take the new path instead.
  10474. if (!srcPath) srcPath = [];
  10475. srcPath.pop();
  10476. srcPath = srcPath.concat(relPath);
  10477. result.search = relative.search;
  10478. result.query = relative.query;
  10479. } else if (!util.isNullOrUndefined(relative.search)) {
  10480. // just pull out the search.
  10481. // like href='?foo'.
  10482. // Put this after the other two cases because it simplifies the booleans
  10483. if (psychotic) {
  10484. result.hostname = result.host = srcPath.shift();
  10485. //occationaly the auth can get stuck only in host
  10486. //this especially happens in cases like
  10487. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  10488. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  10489. result.host.split('@') : false;
  10490. if (authInHost) {
  10491. result.auth = authInHost.shift();
  10492. result.host = result.hostname = authInHost.shift();
  10493. }
  10494. }
  10495. result.search = relative.search;
  10496. result.query = relative.query;
  10497. //to support http.request
  10498. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  10499. result.path = (result.pathname ? result.pathname : '') +
  10500. (result.search ? result.search : '');
  10501. }
  10502. result.href = result.format();
  10503. return result;
  10504. }
  10505. if (!srcPath.length) {
  10506. // no path at all. easy.
  10507. // we've already handled the other stuff above.
  10508. result.pathname = null;
  10509. //to support http.request
  10510. if (result.search) {
  10511. result.path = '/' + result.search;
  10512. } else {
  10513. result.path = null;
  10514. }
  10515. result.href = result.format();
  10516. return result;
  10517. }
  10518. // if a url ENDs in . or .., then it must get a trailing slash.
  10519. // however, if it ends in anything else non-slashy,
  10520. // then it must NOT get a trailing slash.
  10521. var last = srcPath.slice(-1)[0];
  10522. var hasTrailingSlash = (
  10523. (result.host || relative.host || srcPath.length > 1) &&
  10524. (last === '.' || last === '..') || last === '');
  10525. // strip single dots, resolve double dots to parent dir
  10526. // if the path tries to go above the root, `up` ends up > 0
  10527. var up = 0;
  10528. for (var i = srcPath.length; i >= 0; i--) {
  10529. last = srcPath[i];
  10530. if (last === '.') {
  10531. srcPath.splice(i, 1);
  10532. } else if (last === '..') {
  10533. srcPath.splice(i, 1);
  10534. up++;
  10535. } else if (up) {
  10536. srcPath.splice(i, 1);
  10537. up--;
  10538. }
  10539. }
  10540. // if the path is allowed to go above the root, restore leading ..s
  10541. if (!mustEndAbs && !removeAllDots) {
  10542. for (; up--; up) {
  10543. srcPath.unshift('..');
  10544. }
  10545. }
  10546. if (mustEndAbs && srcPath[0] !== '' &&
  10547. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  10548. srcPath.unshift('');
  10549. }
  10550. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  10551. srcPath.push('');
  10552. }
  10553. var isAbsolute = srcPath[0] === '' ||
  10554. (srcPath[0] && srcPath[0].charAt(0) === '/');
  10555. // put the host back
  10556. if (psychotic) {
  10557. result.hostname = result.host = isAbsolute ? '' :
  10558. srcPath.length ? srcPath.shift() : '';
  10559. //occationaly the auth can get stuck only in host
  10560. //this especially happens in cases like
  10561. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  10562. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  10563. result.host.split('@') : false;
  10564. if (authInHost) {
  10565. result.auth = authInHost.shift();
  10566. result.host = result.hostname = authInHost.shift();
  10567. }
  10568. }
  10569. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  10570. if (mustEndAbs && !isAbsolute) {
  10571. srcPath.unshift('');
  10572. }
  10573. if (!srcPath.length) {
  10574. result.pathname = null;
  10575. result.path = null;
  10576. } else {
  10577. result.pathname = srcPath.join('/');
  10578. }
  10579. //to support request.http
  10580. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  10581. result.path = (result.pathname ? result.pathname : '') +
  10582. (result.search ? result.search : '');
  10583. }
  10584. result.auth = relative.auth || result.auth;
  10585. result.slashes = result.slashes || relative.slashes;
  10586. result.href = result.format();
  10587. return result;
  10588. };
  10589. Url.prototype.parseHost = function() {
  10590. var host = this.host;
  10591. var port = portPattern.exec(host);
  10592. if (port) {
  10593. port = port[0];
  10594. if (port !== ':') {
  10595. this.port = port.substr(1);
  10596. }
  10597. host = host.substr(0, host.length - port.length);
  10598. }
  10599. if (host) this.hostname = host;
  10600. };
  10601. },{"./util":129,"punycode":97,"querystring":100}],129:[function(require,module,exports){
  10602. 'use strict';
  10603. module.exports = {
  10604. isString: function(arg) {
  10605. return typeof(arg) === 'string';
  10606. },
  10607. isObject: function(arg) {
  10608. return typeof(arg) === 'object' && arg !== null;
  10609. },
  10610. isNull: function(arg) {
  10611. return arg === null;
  10612. },
  10613. isNullOrUndefined: function(arg) {
  10614. return arg == null;
  10615. }
  10616. };
  10617. },{}],130:[function(require,module,exports){
  10618. (function (global){(function (){
  10619. /**
  10620. * Module exports.
  10621. */
  10622. module.exports = deprecate;
  10623. /**
  10624. * Mark that a method should not be used.
  10625. * Returns a modified function which warns once by default.
  10626. *
  10627. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  10628. *
  10629. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  10630. * will throw an Error when invoked.
  10631. *
  10632. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  10633. * will invoke `console.trace()` instead of `console.error()`.
  10634. *
  10635. * @param {Function} fn - the function to deprecate
  10636. * @param {String} msg - the string to print to the console when `fn` is invoked
  10637. * @returns {Function} a new "deprecated" version of `fn`
  10638. * @api public
  10639. */
  10640. function deprecate (fn, msg) {
  10641. if (config('noDeprecation')) {
  10642. return fn;
  10643. }
  10644. var warned = false;
  10645. function deprecated() {
  10646. if (!warned) {
  10647. if (config('throwDeprecation')) {
  10648. throw new Error(msg);
  10649. } else if (config('traceDeprecation')) {
  10650. console.trace(msg);
  10651. } else {
  10652. console.warn(msg);
  10653. }
  10654. warned = true;
  10655. }
  10656. return fn.apply(this, arguments);
  10657. }
  10658. return deprecated;
  10659. }
  10660. /**
  10661. * Checks `localStorage` for boolean values for the given `name`.
  10662. *
  10663. * @param {String} name
  10664. * @returns {Boolean}
  10665. * @api private
  10666. */
  10667. function config (name) {
  10668. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  10669. try {
  10670. if (!global.localStorage) return false;
  10671. } catch (_) {
  10672. return false;
  10673. }
  10674. var val = global.localStorage[name];
  10675. if (null == val) return false;
  10676. return String(val).toLowerCase() === 'true';
  10677. }
  10678. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10679. },{}],131:[function(require,module,exports){
  10680. if (typeof Object.create === 'function') {
  10681. // implementation from standard node.js 'util' module
  10682. module.exports = function inherits(ctor, superCtor) {
  10683. ctor.super_ = superCtor
  10684. ctor.prototype = Object.create(superCtor.prototype, {
  10685. constructor: {
  10686. value: ctor,
  10687. enumerable: false,
  10688. writable: true,
  10689. configurable: true
  10690. }
  10691. });
  10692. };
  10693. } else {
  10694. // old school shim for old browsers
  10695. module.exports = function inherits(ctor, superCtor) {
  10696. ctor.super_ = superCtor
  10697. var TempCtor = function () {}
  10698. TempCtor.prototype = superCtor.prototype
  10699. ctor.prototype = new TempCtor()
  10700. ctor.prototype.constructor = ctor
  10701. }
  10702. }
  10703. },{}],132:[function(require,module,exports){
  10704. module.exports = function isBuffer(arg) {
  10705. return arg && typeof arg === 'object'
  10706. && typeof arg.copy === 'function'
  10707. && typeof arg.fill === 'function'
  10708. && typeof arg.readUInt8 === 'function';
  10709. }
  10710. },{}],133:[function(require,module,exports){
  10711. (function (process,global){(function (){
  10712. // Copyright Joyent, Inc. and other Node contributors.
  10713. //
  10714. // Permission is hereby granted, free of charge, to any person obtaining a
  10715. // copy of this software and associated documentation files (the
  10716. // "Software"), to deal in the Software without restriction, including
  10717. // without limitation the rights to use, copy, modify, merge, publish,
  10718. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10719. // persons to whom the Software is furnished to do so, subject to the
  10720. // following conditions:
  10721. //
  10722. // The above copyright notice and this permission notice shall be included
  10723. // in all copies or substantial portions of the Software.
  10724. //
  10725. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10726. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10727. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10728. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10729. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10730. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10731. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10732. var formatRegExp = /%[sdj%]/g;
  10733. exports.format = function(f) {
  10734. if (!isString(f)) {
  10735. var objects = [];
  10736. for (var i = 0; i < arguments.length; i++) {
  10737. objects.push(inspect(arguments[i]));
  10738. }
  10739. return objects.join(' ');
  10740. }
  10741. var i = 1;
  10742. var args = arguments;
  10743. var len = args.length;
  10744. var str = String(f).replace(formatRegExp, function(x) {
  10745. if (x === '%%') return '%';
  10746. if (i >= len) return x;
  10747. switch (x) {
  10748. case '%s': return String(args[i++]);
  10749. case '%d': return Number(args[i++]);
  10750. case '%j':
  10751. try {
  10752. return JSON.stringify(args[i++]);
  10753. } catch (_) {
  10754. return '[Circular]';
  10755. }
  10756. default:
  10757. return x;
  10758. }
  10759. });
  10760. for (var x = args[i]; i < len; x = args[++i]) {
  10761. if (isNull(x) || !isObject(x)) {
  10762. str += ' ' + x;
  10763. } else {
  10764. str += ' ' + inspect(x);
  10765. }
  10766. }
  10767. return str;
  10768. };
  10769. // Mark that a method should not be used.
  10770. // Returns a modified function which warns once by default.
  10771. // If --no-deprecation is set, then it is a no-op.
  10772. exports.deprecate = function(fn, msg) {
  10773. // Allow for deprecating things in the process of starting up.
  10774. if (isUndefined(global.process)) {
  10775. return function() {
  10776. return exports.deprecate(fn, msg).apply(this, arguments);
  10777. };
  10778. }
  10779. if (process.noDeprecation === true) {
  10780. return fn;
  10781. }
  10782. var warned = false;
  10783. function deprecated() {
  10784. if (!warned) {
  10785. if (process.throwDeprecation) {
  10786. throw new Error(msg);
  10787. } else if (process.traceDeprecation) {
  10788. console.trace(msg);
  10789. } else {
  10790. console.error(msg);
  10791. }
  10792. warned = true;
  10793. }
  10794. return fn.apply(this, arguments);
  10795. }
  10796. return deprecated;
  10797. };
  10798. var debugs = {};
  10799. var debugEnviron;
  10800. exports.debuglog = function(set) {
  10801. if (isUndefined(debugEnviron))
  10802. debugEnviron = process.env.NODE_DEBUG || '';
  10803. set = set.toUpperCase();
  10804. if (!debugs[set]) {
  10805. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  10806. var pid = process.pid;
  10807. debugs[set] = function() {
  10808. var msg = exports.format.apply(exports, arguments);
  10809. console.error('%s %d: %s', set, pid, msg);
  10810. };
  10811. } else {
  10812. debugs[set] = function() {};
  10813. }
  10814. }
  10815. return debugs[set];
  10816. };
  10817. /**
  10818. * Echos the value of a value. Trys to print the value out
  10819. * in the best way possible given the different types.
  10820. *
  10821. * @param {Object} obj The object to print out.
  10822. * @param {Object} opts Optional options object that alters the output.
  10823. */
  10824. /* legacy: obj, showHidden, depth, colors*/
  10825. function inspect(obj, opts) {
  10826. // default options
  10827. var ctx = {
  10828. seen: [],
  10829. stylize: stylizeNoColor
  10830. };
  10831. // legacy...
  10832. if (arguments.length >= 3) ctx.depth = arguments[2];
  10833. if (arguments.length >= 4) ctx.colors = arguments[3];
  10834. if (isBoolean(opts)) {
  10835. // legacy...
  10836. ctx.showHidden = opts;
  10837. } else if (opts) {
  10838. // got an "options" object
  10839. exports._extend(ctx, opts);
  10840. }
  10841. // set default options
  10842. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  10843. if (isUndefined(ctx.depth)) ctx.depth = 2;
  10844. if (isUndefined(ctx.colors)) ctx.colors = false;
  10845. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  10846. if (ctx.colors) ctx.stylize = stylizeWithColor;
  10847. return formatValue(ctx, obj, ctx.depth);
  10848. }
  10849. exports.inspect = inspect;
  10850. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  10851. inspect.colors = {
  10852. 'bold' : [1, 22],
  10853. 'italic' : [3, 23],
  10854. 'underline' : [4, 24],
  10855. 'inverse' : [7, 27],
  10856. 'white' : [37, 39],
  10857. 'grey' : [90, 39],
  10858. 'black' : [30, 39],
  10859. 'blue' : [34, 39],
  10860. 'cyan' : [36, 39],
  10861. 'green' : [32, 39],
  10862. 'magenta' : [35, 39],
  10863. 'red' : [31, 39],
  10864. 'yellow' : [33, 39]
  10865. };
  10866. // Don't use 'blue' not visible on cmd.exe
  10867. inspect.styles = {
  10868. 'special': 'cyan',
  10869. 'number': 'yellow',
  10870. 'boolean': 'yellow',
  10871. 'undefined': 'grey',
  10872. 'null': 'bold',
  10873. 'string': 'green',
  10874. 'date': 'magenta',
  10875. // "name": intentionally not styling
  10876. 'regexp': 'red'
  10877. };
  10878. function stylizeWithColor(str, styleType) {
  10879. var style = inspect.styles[styleType];
  10880. if (style) {
  10881. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  10882. '\u001b[' + inspect.colors[style][1] + 'm';
  10883. } else {
  10884. return str;
  10885. }
  10886. }
  10887. function stylizeNoColor(str, styleType) {
  10888. return str;
  10889. }
  10890. function arrayToHash(array) {
  10891. var hash = {};
  10892. array.forEach(function(val, idx) {
  10893. hash[val] = true;
  10894. });
  10895. return hash;
  10896. }
  10897. function formatValue(ctx, value, recurseTimes) {
  10898. // Provide a hook for user-specified inspect functions.
  10899. // Check that value is an object with an inspect function on it
  10900. if (ctx.customInspect &&
  10901. value &&
  10902. isFunction(value.inspect) &&
  10903. // Filter out the util module, it's inspect function is special
  10904. value.inspect !== exports.inspect &&
  10905. // Also filter out any prototype objects using the circular check.
  10906. !(value.constructor && value.constructor.prototype === value)) {
  10907. var ret = value.inspect(recurseTimes, ctx);
  10908. if (!isString(ret)) {
  10909. ret = formatValue(ctx, ret, recurseTimes);
  10910. }
  10911. return ret;
  10912. }
  10913. // Primitive types cannot have properties
  10914. var primitive = formatPrimitive(ctx, value);
  10915. if (primitive) {
  10916. return primitive;
  10917. }
  10918. // Look up the keys of the object.
  10919. var keys = Object.keys(value);
  10920. var visibleKeys = arrayToHash(keys);
  10921. if (ctx.showHidden) {
  10922. keys = Object.getOwnPropertyNames(value);
  10923. }
  10924. // IE doesn't make error fields non-enumerable
  10925. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  10926. if (isError(value)
  10927. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  10928. return formatError(value);
  10929. }
  10930. // Some type of object without properties can be shortcutted.
  10931. if (keys.length === 0) {
  10932. if (isFunction(value)) {
  10933. var name = value.name ? ': ' + value.name : '';
  10934. return ctx.stylize('[Function' + name + ']', 'special');
  10935. }
  10936. if (isRegExp(value)) {
  10937. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  10938. }
  10939. if (isDate(value)) {
  10940. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  10941. }
  10942. if (isError(value)) {
  10943. return formatError(value);
  10944. }
  10945. }
  10946. var base = '', array = false, braces = ['{', '}'];
  10947. // Make Array say that they are Array
  10948. if (isArray(value)) {
  10949. array = true;
  10950. braces = ['[', ']'];
  10951. }
  10952. // Make functions say that they are functions
  10953. if (isFunction(value)) {
  10954. var n = value.name ? ': ' + value.name : '';
  10955. base = ' [Function' + n + ']';
  10956. }
  10957. // Make RegExps say that they are RegExps
  10958. if (isRegExp(value)) {
  10959. base = ' ' + RegExp.prototype.toString.call(value);
  10960. }
  10961. // Make dates with properties first say the date
  10962. if (isDate(value)) {
  10963. base = ' ' + Date.prototype.toUTCString.call(value);
  10964. }
  10965. // Make error with message first say the error
  10966. if (isError(value)) {
  10967. base = ' ' + formatError(value);
  10968. }
  10969. if (keys.length === 0 && (!array || value.length == 0)) {
  10970. return braces[0] + base + braces[1];
  10971. }
  10972. if (recurseTimes < 0) {
  10973. if (isRegExp(value)) {
  10974. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  10975. } else {
  10976. return ctx.stylize('[Object]', 'special');
  10977. }
  10978. }
  10979. ctx.seen.push(value);
  10980. var output;
  10981. if (array) {
  10982. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  10983. } else {
  10984. output = keys.map(function(key) {
  10985. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  10986. });
  10987. }
  10988. ctx.seen.pop();
  10989. return reduceToSingleString(output, base, braces);
  10990. }
  10991. function formatPrimitive(ctx, value) {
  10992. if (isUndefined(value))
  10993. return ctx.stylize('undefined', 'undefined');
  10994. if (isString(value)) {
  10995. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  10996. .replace(/'/g, "\\'")
  10997. .replace(/\\"/g, '"') + '\'';
  10998. return ctx.stylize(simple, 'string');
  10999. }
  11000. if (isNumber(value))
  11001. return ctx.stylize('' + value, 'number');
  11002. if (isBoolean(value))
  11003. return ctx.stylize('' + value, 'boolean');
  11004. // For some reason typeof null is "object", so special case here.
  11005. if (isNull(value))
  11006. return ctx.stylize('null', 'null');
  11007. }
  11008. function formatError(value) {
  11009. return '[' + Error.prototype.toString.call(value) + ']';
  11010. }
  11011. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  11012. var output = [];
  11013. for (var i = 0, l = value.length; i < l; ++i) {
  11014. if (hasOwnProperty(value, String(i))) {
  11015. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  11016. String(i), true));
  11017. } else {
  11018. output.push('');
  11019. }
  11020. }
  11021. keys.forEach(function(key) {
  11022. if (!key.match(/^\d+$/)) {
  11023. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  11024. key, true));
  11025. }
  11026. });
  11027. return output;
  11028. }
  11029. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  11030. var name, str, desc;
  11031. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  11032. if (desc.get) {
  11033. if (desc.set) {
  11034. str = ctx.stylize('[Getter/Setter]', 'special');
  11035. } else {
  11036. str = ctx.stylize('[Getter]', 'special');
  11037. }
  11038. } else {
  11039. if (desc.set) {
  11040. str = ctx.stylize('[Setter]', 'special');
  11041. }
  11042. }
  11043. if (!hasOwnProperty(visibleKeys, key)) {
  11044. name = '[' + key + ']';
  11045. }
  11046. if (!str) {
  11047. if (ctx.seen.indexOf(desc.value) < 0) {
  11048. if (isNull(recurseTimes)) {
  11049. str = formatValue(ctx, desc.value, null);
  11050. } else {
  11051. str = formatValue(ctx, desc.value, recurseTimes - 1);
  11052. }
  11053. if (str.indexOf('\n') > -1) {
  11054. if (array) {
  11055. str = str.split('\n').map(function(line) {
  11056. return ' ' + line;
  11057. }).join('\n').substr(2);
  11058. } else {
  11059. str = '\n' + str.split('\n').map(function(line) {
  11060. return ' ' + line;
  11061. }).join('\n');
  11062. }
  11063. }
  11064. } else {
  11065. str = ctx.stylize('[Circular]', 'special');
  11066. }
  11067. }
  11068. if (isUndefined(name)) {
  11069. if (array && key.match(/^\d+$/)) {
  11070. return str;
  11071. }
  11072. name = JSON.stringify('' + key);
  11073. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  11074. name = name.substr(1, name.length - 2);
  11075. name = ctx.stylize(name, 'name');
  11076. } else {
  11077. name = name.replace(/'/g, "\\'")
  11078. .replace(/\\"/g, '"')
  11079. .replace(/(^"|"$)/g, "'");
  11080. name = ctx.stylize(name, 'string');
  11081. }
  11082. }
  11083. return name + ': ' + str;
  11084. }
  11085. function reduceToSingleString(output, base, braces) {
  11086. var numLinesEst = 0;
  11087. var length = output.reduce(function(prev, cur) {
  11088. numLinesEst++;
  11089. if (cur.indexOf('\n') >= 0) numLinesEst++;
  11090. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  11091. }, 0);
  11092. if (length > 60) {
  11093. return braces[0] +
  11094. (base === '' ? '' : base + '\n ') +
  11095. ' ' +
  11096. output.join(',\n ') +
  11097. ' ' +
  11098. braces[1];
  11099. }
  11100. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  11101. }
  11102. // NOTE: These type checking functions intentionally don't use `instanceof`
  11103. // because it is fragile and can be easily faked with `Object.create()`.
  11104. function isArray(ar) {
  11105. return Array.isArray(ar);
  11106. }
  11107. exports.isArray = isArray;
  11108. function isBoolean(arg) {
  11109. return typeof arg === 'boolean';
  11110. }
  11111. exports.isBoolean = isBoolean;
  11112. function isNull(arg) {
  11113. return arg === null;
  11114. }
  11115. exports.isNull = isNull;
  11116. function isNullOrUndefined(arg) {
  11117. return arg == null;
  11118. }
  11119. exports.isNullOrUndefined = isNullOrUndefined;
  11120. function isNumber(arg) {
  11121. return typeof arg === 'number';
  11122. }
  11123. exports.isNumber = isNumber;
  11124. function isString(arg) {
  11125. return typeof arg === 'string';
  11126. }
  11127. exports.isString = isString;
  11128. function isSymbol(arg) {
  11129. return typeof arg === 'symbol';
  11130. }
  11131. exports.isSymbol = isSymbol;
  11132. function isUndefined(arg) {
  11133. return arg === void 0;
  11134. }
  11135. exports.isUndefined = isUndefined;
  11136. function isRegExp(re) {
  11137. return isObject(re) && objectToString(re) === '[object RegExp]';
  11138. }
  11139. exports.isRegExp = isRegExp;
  11140. function isObject(arg) {
  11141. return typeof arg === 'object' && arg !== null;
  11142. }
  11143. exports.isObject = isObject;
  11144. function isDate(d) {
  11145. return isObject(d) && objectToString(d) === '[object Date]';
  11146. }
  11147. exports.isDate = isDate;
  11148. function isError(e) {
  11149. return isObject(e) &&
  11150. (objectToString(e) === '[object Error]' || e instanceof Error);
  11151. }
  11152. exports.isError = isError;
  11153. function isFunction(arg) {
  11154. return typeof arg === 'function';
  11155. }
  11156. exports.isFunction = isFunction;
  11157. function isPrimitive(arg) {
  11158. return arg === null ||
  11159. typeof arg === 'boolean' ||
  11160. typeof arg === 'number' ||
  11161. typeof arg === 'string' ||
  11162. typeof arg === 'symbol' || // ES6 symbol
  11163. typeof arg === 'undefined';
  11164. }
  11165. exports.isPrimitive = isPrimitive;
  11166. exports.isBuffer = require('./support/isBuffer');
  11167. function objectToString(o) {
  11168. return Object.prototype.toString.call(o);
  11169. }
  11170. function pad(n) {
  11171. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  11172. }
  11173. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  11174. 'Oct', 'Nov', 'Dec'];
  11175. // 26 Feb 16:19:34
  11176. function timestamp() {
  11177. var d = new Date();
  11178. var time = [pad(d.getHours()),
  11179. pad(d.getMinutes()),
  11180. pad(d.getSeconds())].join(':');
  11181. return [d.getDate(), months[d.getMonth()], time].join(' ');
  11182. }
  11183. // log is just a thin wrapper to console.log that prepends a timestamp
  11184. exports.log = function() {
  11185. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  11186. };
  11187. /**
  11188. * Inherit the prototype methods from one constructor into another.
  11189. *
  11190. * The Function.prototype.inherits from lang.js rewritten as a standalone
  11191. * function (not on Function.prototype). NOTE: If this file is to be loaded
  11192. * during bootstrapping this function needs to be rewritten using some native
  11193. * functions as prototype setup using normal JavaScript does not work as
  11194. * expected during bootstrapping (see mirror.js in r114903).
  11195. *
  11196. * @param {function} ctor Constructor function which needs to inherit the
  11197. * prototype.
  11198. * @param {function} superCtor Constructor function to inherit prototype from.
  11199. */
  11200. exports.inherits = require('inherits');
  11201. exports._extend = function(origin, add) {
  11202. // Don't do anything if add isn't an object
  11203. if (!add || !isObject(add)) return origin;
  11204. var keys = Object.keys(add);
  11205. var i = keys.length;
  11206. while (i--) {
  11207. origin[keys[i]] = add[keys[i]];
  11208. }
  11209. return origin;
  11210. };
  11211. function hasOwnProperty(obj, prop) {
  11212. return Object.prototype.hasOwnProperty.call(obj, prop);
  11213. }
  11214. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11215. },{"./support/isBuffer":132,"_process":96,"inherits":131}],134:[function(require,module,exports){
  11216. (function (process,Buffer){(function (){
  11217. var stream = require('readable-stream')
  11218. var eos = require('end-of-stream')
  11219. var inherits = require('inherits')
  11220. var shift = require('stream-shift')
  11221. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  11222. ? Buffer.from([0])
  11223. : new Buffer([0])
  11224. var onuncork = function(self, fn) {
  11225. if (self._corked) self.once('uncork', fn)
  11226. else fn()
  11227. }
  11228. var autoDestroy = function (self, err) {
  11229. if (self._autoDestroy) self.destroy(err)
  11230. }
  11231. var destroyer = function(self, end) {
  11232. return function(err) {
  11233. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  11234. else if (end && !self._ended) self.end()
  11235. }
  11236. }
  11237. var end = function(ws, fn) {
  11238. if (!ws) return fn()
  11239. if (ws._writableState && ws._writableState.finished) return fn()
  11240. if (ws._writableState) return ws.end(fn)
  11241. ws.end()
  11242. fn()
  11243. }
  11244. var toStreams2 = function(rs) {
  11245. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  11246. }
  11247. var Duplexify = function(writable, readable, opts) {
  11248. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  11249. stream.Duplex.call(this, opts)
  11250. this._writable = null
  11251. this._readable = null
  11252. this._readable2 = null
  11253. this._autoDestroy = !opts || opts.autoDestroy !== false
  11254. this._forwardDestroy = !opts || opts.destroy !== false
  11255. this._forwardEnd = !opts || opts.end !== false
  11256. this._corked = 1 // start corked
  11257. this._ondrain = null
  11258. this._drained = false
  11259. this._forwarding = false
  11260. this._unwrite = null
  11261. this._unread = null
  11262. this._ended = false
  11263. this.destroyed = false
  11264. if (writable) this.setWritable(writable)
  11265. if (readable) this.setReadable(readable)
  11266. }
  11267. inherits(Duplexify, stream.Duplex)
  11268. Duplexify.obj = function(writable, readable, opts) {
  11269. if (!opts) opts = {}
  11270. opts.objectMode = true
  11271. opts.highWaterMark = 16
  11272. return new Duplexify(writable, readable, opts)
  11273. }
  11274. Duplexify.prototype.cork = function() {
  11275. if (++this._corked === 1) this.emit('cork')
  11276. }
  11277. Duplexify.prototype.uncork = function() {
  11278. if (this._corked && --this._corked === 0) this.emit('uncork')
  11279. }
  11280. Duplexify.prototype.setWritable = function(writable) {
  11281. if (this._unwrite) this._unwrite()
  11282. if (this.destroyed) {
  11283. if (writable && writable.destroy) writable.destroy()
  11284. return
  11285. }
  11286. if (writable === null || writable === false) {
  11287. this.end()
  11288. return
  11289. }
  11290. var self = this
  11291. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  11292. var ondrain = function() {
  11293. var ondrain = self._ondrain
  11294. self._ondrain = null
  11295. if (ondrain) ondrain()
  11296. }
  11297. var clear = function() {
  11298. self._writable.removeListener('drain', ondrain)
  11299. unend()
  11300. }
  11301. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  11302. this._writable = writable
  11303. this._writable.on('drain', ondrain)
  11304. this._unwrite = clear
  11305. this.uncork() // always uncork setWritable
  11306. }
  11307. Duplexify.prototype.setReadable = function(readable) {
  11308. if (this._unread) this._unread()
  11309. if (this.destroyed) {
  11310. if (readable && readable.destroy) readable.destroy()
  11311. return
  11312. }
  11313. if (readable === null || readable === false) {
  11314. this.push(null)
  11315. this.resume()
  11316. return
  11317. }
  11318. var self = this
  11319. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  11320. var onreadable = function() {
  11321. self._forward()
  11322. }
  11323. var onend = function() {
  11324. self.push(null)
  11325. }
  11326. var clear = function() {
  11327. self._readable2.removeListener('readable', onreadable)
  11328. self._readable2.removeListener('end', onend)
  11329. unend()
  11330. }
  11331. this._drained = true
  11332. this._readable = readable
  11333. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  11334. this._readable2.on('readable', onreadable)
  11335. this._readable2.on('end', onend)
  11336. this._unread = clear
  11337. this._forward()
  11338. }
  11339. Duplexify.prototype._read = function() {
  11340. this._drained = true
  11341. this._forward()
  11342. }
  11343. Duplexify.prototype._forward = function() {
  11344. if (this._forwarding || !this._readable2 || !this._drained) return
  11345. this._forwarding = true
  11346. var data
  11347. while (this._drained && (data = shift(this._readable2)) !== null) {
  11348. if (this.destroyed) continue
  11349. this._drained = this.push(data)
  11350. }
  11351. this._forwarding = false
  11352. }
  11353. Duplexify.prototype.destroy = function(err) {
  11354. if (this.destroyed) return
  11355. this.destroyed = true
  11356. var self = this
  11357. process.nextTick(function() {
  11358. self._destroy(err)
  11359. })
  11360. }
  11361. Duplexify.prototype._destroy = function(err) {
  11362. if (err) {
  11363. var ondrain = this._ondrain
  11364. this._ondrain = null
  11365. if (ondrain) ondrain(err)
  11366. else this.emit('error', err)
  11367. }
  11368. if (this._forwardDestroy) {
  11369. if (this._readable && this._readable.destroy) this._readable.destroy()
  11370. if (this._writable && this._writable.destroy) this._writable.destroy()
  11371. }
  11372. this.emit('close')
  11373. }
  11374. Duplexify.prototype._write = function(data, enc, cb) {
  11375. if (this.destroyed) return cb()
  11376. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  11377. if (data === SIGNAL_FLUSH) return this._finish(cb)
  11378. if (!this._writable) return cb()
  11379. if (this._writable.write(data) === false) this._ondrain = cb
  11380. else cb()
  11381. }
  11382. Duplexify.prototype._finish = function(cb) {
  11383. var self = this
  11384. this.emit('preend')
  11385. onuncork(this, function() {
  11386. end(self._forwardEnd && self._writable, function() {
  11387. // haxx to not emit prefinish twice
  11388. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  11389. self.emit('prefinish')
  11390. onuncork(self, cb)
  11391. })
  11392. })
  11393. }
  11394. Duplexify.prototype.end = function(data, enc, cb) {
  11395. if (typeof data === 'function') return this.end(null, null, data)
  11396. if (typeof enc === 'function') return this.end(data, null, enc)
  11397. this._ended = true
  11398. if (data) this.write(data)
  11399. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  11400. return stream.Writable.prototype.end.call(this, cb)
  11401. }
  11402. module.exports = Duplexify
  11403. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  11404. },{"_process":96,"buffer":12,"end-of-stream":16,"inherits":84,"readable-stream":143,"stream-shift":115}],135:[function(require,module,exports){
  11405. arguments[4][102][0].apply(exports,arguments)
  11406. },{"./_stream_readable":137,"./_stream_writable":139,"core-util-is":13,"dup":102,"inherits":84,"process-nextick-args":95}],136:[function(require,module,exports){
  11407. arguments[4][103][0].apply(exports,arguments)
  11408. },{"./_stream_transform":138,"core-util-is":13,"dup":103,"inherits":84}],137:[function(require,module,exports){
  11409. arguments[4][104][0].apply(exports,arguments)
  11410. },{"./_stream_duplex":135,"./internal/streams/BufferList":140,"./internal/streams/destroy":141,"./internal/streams/stream":142,"_process":96,"core-util-is":13,"dup":104,"events":79,"inherits":84,"isarray":86,"process-nextick-args":95,"safe-buffer":144,"string_decoder/":160,"util":11}],138:[function(require,module,exports){
  11411. arguments[4][105][0].apply(exports,arguments)
  11412. },{"./_stream_duplex":135,"core-util-is":13,"dup":105,"inherits":84}],139:[function(require,module,exports){
  11413. arguments[4][106][0].apply(exports,arguments)
  11414. },{"./_stream_duplex":135,"./internal/streams/destroy":141,"./internal/streams/stream":142,"_process":96,"core-util-is":13,"dup":106,"inherits":84,"process-nextick-args":95,"safe-buffer":144,"timers":116,"util-deprecate":130}],140:[function(require,module,exports){
  11415. arguments[4][107][0].apply(exports,arguments)
  11416. },{"dup":107,"safe-buffer":144,"util":11}],141:[function(require,module,exports){
  11417. arguments[4][108][0].apply(exports,arguments)
  11418. },{"dup":108,"process-nextick-args":95}],142:[function(require,module,exports){
  11419. arguments[4][109][0].apply(exports,arguments)
  11420. },{"dup":109,"events":79}],143:[function(require,module,exports){
  11421. arguments[4][112][0].apply(exports,arguments)
  11422. },{"./lib/_stream_duplex.js":135,"./lib/_stream_passthrough.js":136,"./lib/_stream_readable.js":137,"./lib/_stream_transform.js":138,"./lib/_stream_writable.js":139,"dup":112}],144:[function(require,module,exports){
  11423. arguments[4][110][0].apply(exports,arguments)
  11424. },{"buffer":12,"dup":110}],145:[function(require,module,exports){
  11425. 'use strict';
  11426. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  11427. var codes = {};
  11428. function createErrorType(code, message, Base) {
  11429. if (!Base) {
  11430. Base = Error;
  11431. }
  11432. function getMessage(arg1, arg2, arg3) {
  11433. if (typeof message === 'string') {
  11434. return message;
  11435. } else {
  11436. return message(arg1, arg2, arg3);
  11437. }
  11438. }
  11439. var NodeError =
  11440. /*#__PURE__*/
  11441. function (_Base) {
  11442. _inheritsLoose(NodeError, _Base);
  11443. function NodeError(arg1, arg2, arg3) {
  11444. return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
  11445. }
  11446. return NodeError;
  11447. }(Base);
  11448. NodeError.prototype.name = Base.name;
  11449. NodeError.prototype.code = code;
  11450. codes[code] = NodeError;
  11451. } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  11452. function oneOf(expected, thing) {
  11453. if (Array.isArray(expected)) {
  11454. var len = expected.length;
  11455. expected = expected.map(function (i) {
  11456. return String(i);
  11457. });
  11458. if (len > 2) {
  11459. return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
  11460. } else if (len === 2) {
  11461. return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
  11462. } else {
  11463. return "of ".concat(thing, " ").concat(expected[0]);
  11464. }
  11465. } else {
  11466. return "of ".concat(thing, " ").concat(String(expected));
  11467. }
  11468. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  11469. function startsWith(str, search, pos) {
  11470. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  11471. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  11472. function endsWith(str, search, this_len) {
  11473. if (this_len === undefined || this_len > str.length) {
  11474. this_len = str.length;
  11475. }
  11476. return str.substring(this_len - search.length, this_len) === search;
  11477. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  11478. function includes(str, search, start) {
  11479. if (typeof start !== 'number') {
  11480. start = 0;
  11481. }
  11482. if (start + search.length > str.length) {
  11483. return false;
  11484. } else {
  11485. return str.indexOf(search, start) !== -1;
  11486. }
  11487. }
  11488. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  11489. return 'The value "' + value + '" is invalid for option "' + name + '"';
  11490. }, TypeError);
  11491. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  11492. // determiner: 'must be' or 'must not be'
  11493. var determiner;
  11494. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  11495. determiner = 'must not be';
  11496. expected = expected.replace(/^not /, '');
  11497. } else {
  11498. determiner = 'must be';
  11499. }
  11500. var msg;
  11501. if (endsWith(name, ' argument')) {
  11502. // For cases like 'first argument'
  11503. msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  11504. } else {
  11505. var type = includes(name, '.') ? 'property' : 'argument';
  11506. msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  11507. }
  11508. msg += ". Received type ".concat(typeof actual);
  11509. return msg;
  11510. }, TypeError);
  11511. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  11512. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  11513. return 'The ' + name + ' method is not implemented';
  11514. });
  11515. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  11516. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  11517. return 'Cannot call ' + name + ' after a stream was destroyed';
  11518. });
  11519. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  11520. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  11521. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  11522. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  11523. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  11524. return 'Unknown encoding: ' + arg;
  11525. }, TypeError);
  11526. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  11527. module.exports.codes = codes;
  11528. },{}],146:[function(require,module,exports){
  11529. (function (process){(function (){
  11530. // Copyright Joyent, Inc. and other Node contributors.
  11531. //
  11532. // Permission is hereby granted, free of charge, to any person obtaining a
  11533. // copy of this software and associated documentation files (the
  11534. // "Software"), to deal in the Software without restriction, including
  11535. // without limitation the rights to use, copy, modify, merge, publish,
  11536. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11537. // persons to whom the Software is furnished to do so, subject to the
  11538. // following conditions:
  11539. //
  11540. // The above copyright notice and this permission notice shall be included
  11541. // in all copies or substantial portions of the Software.
  11542. //
  11543. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11544. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11545. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11546. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11547. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11548. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11549. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11550. // a duplex stream is just a stream that is both readable and writable.
  11551. // Since JS doesn't have multiple prototypal inheritance, this class
  11552. // prototypally inherits from Readable, and then parasitically from
  11553. // Writable.
  11554. 'use strict';
  11555. /*<replacement>*/
  11556. var objectKeys = Object.keys || function (obj) {
  11557. var keys = [];
  11558. for (var key in obj) {
  11559. keys.push(key);
  11560. }
  11561. return keys;
  11562. };
  11563. /*</replacement>*/
  11564. module.exports = Duplex;
  11565. var Readable = require('./_stream_readable');
  11566. var Writable = require('./_stream_writable');
  11567. require('inherits')(Duplex, Readable);
  11568. {
  11569. // Allow the keys array to be GC'ed.
  11570. var keys = objectKeys(Writable.prototype);
  11571. for (var v = 0; v < keys.length; v++) {
  11572. var method = keys[v];
  11573. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  11574. }
  11575. }
  11576. function Duplex(options) {
  11577. if (!(this instanceof Duplex)) return new Duplex(options);
  11578. Readable.call(this, options);
  11579. Writable.call(this, options);
  11580. this.allowHalfOpen = true;
  11581. if (options) {
  11582. if (options.readable === false) this.readable = false;
  11583. if (options.writable === false) this.writable = false;
  11584. if (options.allowHalfOpen === false) {
  11585. this.allowHalfOpen = false;
  11586. this.once('end', onend);
  11587. }
  11588. }
  11589. }
  11590. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  11591. // making it explicit this property is not enumerable
  11592. // because otherwise some prototype manipulation in
  11593. // userland will fail
  11594. enumerable: false,
  11595. get: function get() {
  11596. return this._writableState.highWaterMark;
  11597. }
  11598. });
  11599. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  11600. // making it explicit this property is not enumerable
  11601. // because otherwise some prototype manipulation in
  11602. // userland will fail
  11603. enumerable: false,
  11604. get: function get() {
  11605. return this._writableState && this._writableState.getBuffer();
  11606. }
  11607. });
  11608. Object.defineProperty(Duplex.prototype, 'writableLength', {
  11609. // making it explicit this property is not enumerable
  11610. // because otherwise some prototype manipulation in
  11611. // userland will fail
  11612. enumerable: false,
  11613. get: function get() {
  11614. return this._writableState.length;
  11615. }
  11616. }); // the no-half-open enforcer
  11617. function onend() {
  11618. // If the writable side ended, then we're ok.
  11619. if (this._writableState.ended) return; // no more data can be written.
  11620. // But allow more writes to happen in this tick.
  11621. process.nextTick(onEndNT, this);
  11622. }
  11623. function onEndNT(self) {
  11624. self.end();
  11625. }
  11626. Object.defineProperty(Duplex.prototype, 'destroyed', {
  11627. // making it explicit this property is not enumerable
  11628. // because otherwise some prototype manipulation in
  11629. // userland will fail
  11630. enumerable: false,
  11631. get: function get() {
  11632. if (this._readableState === undefined || this._writableState === undefined) {
  11633. return false;
  11634. }
  11635. return this._readableState.destroyed && this._writableState.destroyed;
  11636. },
  11637. set: function set(value) {
  11638. // we ignore the value if the stream
  11639. // has not been initialized yet
  11640. if (this._readableState === undefined || this._writableState === undefined) {
  11641. return;
  11642. } // backward compatibility, the user is explicitly
  11643. // managing destroyed
  11644. this._readableState.destroyed = value;
  11645. this._writableState.destroyed = value;
  11646. }
  11647. });
  11648. }).call(this)}).call(this,require('_process'))
  11649. },{"./_stream_readable":148,"./_stream_writable":150,"_process":96,"inherits":84}],147:[function(require,module,exports){
  11650. // Copyright Joyent, Inc. and other Node contributors.
  11651. //
  11652. // Permission is hereby granted, free of charge, to any person obtaining a
  11653. // copy of this software and associated documentation files (the
  11654. // "Software"), to deal in the Software without restriction, including
  11655. // without limitation the rights to use, copy, modify, merge, publish,
  11656. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11657. // persons to whom the Software is furnished to do so, subject to the
  11658. // following conditions:
  11659. //
  11660. // The above copyright notice and this permission notice shall be included
  11661. // in all copies or substantial portions of the Software.
  11662. //
  11663. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11664. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11665. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11666. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11667. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11668. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11669. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11670. // a passthrough stream.
  11671. // basically just the most minimal sort of Transform stream.
  11672. // Every written chunk gets output as-is.
  11673. 'use strict';
  11674. module.exports = PassThrough;
  11675. var Transform = require('./_stream_transform');
  11676. require('inherits')(PassThrough, Transform);
  11677. function PassThrough(options) {
  11678. if (!(this instanceof PassThrough)) return new PassThrough(options);
  11679. Transform.call(this, options);
  11680. }
  11681. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  11682. cb(null, chunk);
  11683. };
  11684. },{"./_stream_transform":149,"inherits":84}],148:[function(require,module,exports){
  11685. (function (process,global){(function (){
  11686. // Copyright Joyent, Inc. and other Node contributors.
  11687. //
  11688. // Permission is hereby granted, free of charge, to any person obtaining a
  11689. // copy of this software and associated documentation files (the
  11690. // "Software"), to deal in the Software without restriction, including
  11691. // without limitation the rights to use, copy, modify, merge, publish,
  11692. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11693. // persons to whom the Software is furnished to do so, subject to the
  11694. // following conditions:
  11695. //
  11696. // The above copyright notice and this permission notice shall be included
  11697. // in all copies or substantial portions of the Software.
  11698. //
  11699. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11700. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11701. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11702. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11703. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11704. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11705. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11706. 'use strict';
  11707. module.exports = Readable;
  11708. /*<replacement>*/
  11709. var Duplex;
  11710. /*</replacement>*/
  11711. Readable.ReadableState = ReadableState;
  11712. /*<replacement>*/
  11713. var EE = require('events').EventEmitter;
  11714. var EElistenerCount = function EElistenerCount(emitter, type) {
  11715. return emitter.listeners(type).length;
  11716. };
  11717. /*</replacement>*/
  11718. /*<replacement>*/
  11719. var Stream = require('./internal/streams/stream');
  11720. /*</replacement>*/
  11721. var Buffer = require('buffer').Buffer;
  11722. var OurUint8Array = global.Uint8Array || function () {};
  11723. function _uint8ArrayToBuffer(chunk) {
  11724. return Buffer.from(chunk);
  11725. }
  11726. function _isUint8Array(obj) {
  11727. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  11728. }
  11729. /*<replacement>*/
  11730. var debugUtil = require('util');
  11731. var debug;
  11732. if (debugUtil && debugUtil.debuglog) {
  11733. debug = debugUtil.debuglog('stream');
  11734. } else {
  11735. debug = function debug() {};
  11736. }
  11737. /*</replacement>*/
  11738. var BufferList = require('./internal/streams/buffer_list');
  11739. var destroyImpl = require('./internal/streams/destroy');
  11740. var _require = require('./internal/streams/state'),
  11741. getHighWaterMark = _require.getHighWaterMark;
  11742. var _require$codes = require('../errors').codes,
  11743. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  11744. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  11745. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  11746. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
  11747. var StringDecoder;
  11748. var createReadableStreamAsyncIterator;
  11749. var from;
  11750. require('inherits')(Readable, Stream);
  11751. var errorOrDestroy = destroyImpl.errorOrDestroy;
  11752. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  11753. function prependListener(emitter, event, fn) {
  11754. // Sadly this is not cacheable as some libraries bundle their own
  11755. // event emitter implementation with them.
  11756. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
  11757. // userland ones. NEVER DO THIS. This is here only because this code needs
  11758. // to continue to work with older versions of Node.js that do not include
  11759. // the prependListener() method. The goal is to eventually remove this hack.
  11760. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  11761. }
  11762. function ReadableState(options, stream, isDuplex) {
  11763. Duplex = Duplex || require('./_stream_duplex');
  11764. options = options || {}; // Duplex streams are both readable and writable, but share
  11765. // the same options object.
  11766. // However, some cases require setting options to different
  11767. // values for the readable and the writable sides of the duplex stream.
  11768. // These options can be provided separately as readableXXX and writableXXX.
  11769. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
  11770. // make all the buffer merging and length checks go away
  11771. this.objectMode = !!options.objectMode;
  11772. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
  11773. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  11774. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
  11775. // linked list can remove elements from the beginning faster than
  11776. // array.shift()
  11777. this.buffer = new BufferList();
  11778. this.length = 0;
  11779. this.pipes = null;
  11780. this.pipesCount = 0;
  11781. this.flowing = null;
  11782. this.ended = false;
  11783. this.endEmitted = false;
  11784. this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
  11785. // immediately, or on a later tick. We set this to true at first, because
  11786. // any actions that shouldn't happen until "later" should generally also
  11787. // not happen before the first read call.
  11788. this.sync = true; // whenever we return null, then we set a flag to say
  11789. // that we're awaiting a 'readable' event emission.
  11790. this.needReadable = false;
  11791. this.emittedReadable = false;
  11792. this.readableListening = false;
  11793. this.resumeScheduled = false;
  11794. this.paused = true; // Should close be emitted on destroy. Defaults to true.
  11795. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
  11796. this.autoDestroy = !!options.autoDestroy; // has it been destroyed
  11797. this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
  11798. // encoding is 'binary' so we have to make this configurable.
  11799. // Everything else in the universe uses 'utf8', though.
  11800. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
  11801. this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
  11802. this.readingMore = false;
  11803. this.decoder = null;
  11804. this.encoding = null;
  11805. if (options.encoding) {
  11806. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  11807. this.decoder = new StringDecoder(options.encoding);
  11808. this.encoding = options.encoding;
  11809. }
  11810. }
  11811. function Readable(options) {
  11812. Duplex = Duplex || require('./_stream_duplex');
  11813. if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
  11814. // the ReadableState constructor, at least with V8 6.5
  11815. var isDuplex = this instanceof Duplex;
  11816. this._readableState = new ReadableState(options, this, isDuplex); // legacy
  11817. this.readable = true;
  11818. if (options) {
  11819. if (typeof options.read === 'function') this._read = options.read;
  11820. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  11821. }
  11822. Stream.call(this);
  11823. }
  11824. Object.defineProperty(Readable.prototype, 'destroyed', {
  11825. // making it explicit this property is not enumerable
  11826. // because otherwise some prototype manipulation in
  11827. // userland will fail
  11828. enumerable: false,
  11829. get: function get() {
  11830. if (this._readableState === undefined) {
  11831. return false;
  11832. }
  11833. return this._readableState.destroyed;
  11834. },
  11835. set: function set(value) {
  11836. // we ignore the value if the stream
  11837. // has not been initialized yet
  11838. if (!this._readableState) {
  11839. return;
  11840. } // backward compatibility, the user is explicitly
  11841. // managing destroyed
  11842. this._readableState.destroyed = value;
  11843. }
  11844. });
  11845. Readable.prototype.destroy = destroyImpl.destroy;
  11846. Readable.prototype._undestroy = destroyImpl.undestroy;
  11847. Readable.prototype._destroy = function (err, cb) {
  11848. cb(err);
  11849. }; // Manually shove something into the read() buffer.
  11850. // This returns true if the highWaterMark has not been hit yet,
  11851. // similar to how Writable.write() returns true if you should
  11852. // write() some more.
  11853. Readable.prototype.push = function (chunk, encoding) {
  11854. var state = this._readableState;
  11855. var skipChunkCheck;
  11856. if (!state.objectMode) {
  11857. if (typeof chunk === 'string') {
  11858. encoding = encoding || state.defaultEncoding;
  11859. if (encoding !== state.encoding) {
  11860. chunk = Buffer.from(chunk, encoding);
  11861. encoding = '';
  11862. }
  11863. skipChunkCheck = true;
  11864. }
  11865. } else {
  11866. skipChunkCheck = true;
  11867. }
  11868. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  11869. }; // Unshift should *always* be something directly out of read()
  11870. Readable.prototype.unshift = function (chunk) {
  11871. return readableAddChunk(this, chunk, null, true, false);
  11872. };
  11873. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  11874. debug('readableAddChunk', chunk);
  11875. var state = stream._readableState;
  11876. if (chunk === null) {
  11877. state.reading = false;
  11878. onEofChunk(stream, state);
  11879. } else {
  11880. var er;
  11881. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  11882. if (er) {
  11883. errorOrDestroy(stream, er);
  11884. } else if (state.objectMode || chunk && chunk.length > 0) {
  11885. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  11886. chunk = _uint8ArrayToBuffer(chunk);
  11887. }
  11888. if (addToFront) {
  11889. if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  11890. } else if (state.ended) {
  11891. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  11892. } else if (state.destroyed) {
  11893. return false;
  11894. } else {
  11895. state.reading = false;
  11896. if (state.decoder && !encoding) {
  11897. chunk = state.decoder.write(chunk);
  11898. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  11899. } else {
  11900. addChunk(stream, state, chunk, false);
  11901. }
  11902. }
  11903. } else if (!addToFront) {
  11904. state.reading = false;
  11905. maybeReadMore(stream, state);
  11906. }
  11907. } // We can push more data if we are below the highWaterMark.
  11908. // Also, if we have no data yet, we can stand some more bytes.
  11909. // This is to work around cases where hwm=0, such as the repl.
  11910. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  11911. }
  11912. function addChunk(stream, state, chunk, addToFront) {
  11913. if (state.flowing && state.length === 0 && !state.sync) {
  11914. state.awaitDrain = 0;
  11915. stream.emit('data', chunk);
  11916. } else {
  11917. // update the buffer info.
  11918. state.length += state.objectMode ? 1 : chunk.length;
  11919. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  11920. if (state.needReadable) emitReadable(stream);
  11921. }
  11922. maybeReadMore(stream, state);
  11923. }
  11924. function chunkInvalid(state, chunk) {
  11925. var er;
  11926. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  11927. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  11928. }
  11929. return er;
  11930. }
  11931. Readable.prototype.isPaused = function () {
  11932. return this._readableState.flowing === false;
  11933. }; // backwards compatibility.
  11934. Readable.prototype.setEncoding = function (enc) {
  11935. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  11936. var decoder = new StringDecoder(enc);
  11937. this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
  11938. this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
  11939. var p = this._readableState.buffer.head;
  11940. var content = '';
  11941. while (p !== null) {
  11942. content += decoder.write(p.data);
  11943. p = p.next;
  11944. }
  11945. this._readableState.buffer.clear();
  11946. if (content !== '') this._readableState.buffer.push(content);
  11947. this._readableState.length = content.length;
  11948. return this;
  11949. }; // Don't raise the hwm > 1GB
  11950. var MAX_HWM = 0x40000000;
  11951. function computeNewHighWaterMark(n) {
  11952. if (n >= MAX_HWM) {
  11953. // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
  11954. n = MAX_HWM;
  11955. } else {
  11956. // Get the next highest power of 2 to prevent increasing hwm excessively in
  11957. // tiny amounts
  11958. n--;
  11959. n |= n >>> 1;
  11960. n |= n >>> 2;
  11961. n |= n >>> 4;
  11962. n |= n >>> 8;
  11963. n |= n >>> 16;
  11964. n++;
  11965. }
  11966. return n;
  11967. } // This function is designed to be inlinable, so please take care when making
  11968. // changes to the function body.
  11969. function howMuchToRead(n, state) {
  11970. if (n <= 0 || state.length === 0 && state.ended) return 0;
  11971. if (state.objectMode) return 1;
  11972. if (n !== n) {
  11973. // Only flow one buffer at a time
  11974. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  11975. } // If we're asking for more than the current hwm, then raise the hwm.
  11976. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  11977. if (n <= state.length) return n; // Don't have enough
  11978. if (!state.ended) {
  11979. state.needReadable = true;
  11980. return 0;
  11981. }
  11982. return state.length;
  11983. } // you can override either this method, or the async _read(n) below.
  11984. Readable.prototype.read = function (n) {
  11985. debug('read', n);
  11986. n = parseInt(n, 10);
  11987. var state = this._readableState;
  11988. var nOrig = n;
  11989. if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
  11990. // already have a bunch of data in the buffer, then just trigger
  11991. // the 'readable' event and move on.
  11992. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  11993. debug('read: emitReadable', state.length, state.ended);
  11994. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  11995. return null;
  11996. }
  11997. n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
  11998. if (n === 0 && state.ended) {
  11999. if (state.length === 0) endReadable(this);
  12000. return null;
  12001. } // All the actual chunk generation logic needs to be
  12002. // *below* the call to _read. The reason is that in certain
  12003. // synthetic stream cases, such as passthrough streams, _read
  12004. // may be a completely synchronous operation which may change
  12005. // the state of the read buffer, providing enough data when
  12006. // before there was *not* enough.
  12007. //
  12008. // So, the steps are:
  12009. // 1. Figure out what the state of things will be after we do
  12010. // a read from the buffer.
  12011. //
  12012. // 2. If that resulting state will trigger a _read, then call _read.
  12013. // Note that this may be asynchronous, or synchronous. Yes, it is
  12014. // deeply ugly to write APIs this way, but that still doesn't mean
  12015. // that the Readable class should behave improperly, as streams are
  12016. // designed to be sync/async agnostic.
  12017. // Take note if the _read call is sync or async (ie, if the read call
  12018. // has returned yet), so that we know whether or not it's safe to emit
  12019. // 'readable' etc.
  12020. //
  12021. // 3. Actually pull the requested chunks out of the buffer and return.
  12022. // if we need a readable event, then we need to do some reading.
  12023. var doRead = state.needReadable;
  12024. debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
  12025. if (state.length === 0 || state.length - n < state.highWaterMark) {
  12026. doRead = true;
  12027. debug('length less than watermark', doRead);
  12028. } // however, if we've ended, then there's no point, and if we're already
  12029. // reading, then it's unnecessary.
  12030. if (state.ended || state.reading) {
  12031. doRead = false;
  12032. debug('reading or ended', doRead);
  12033. } else if (doRead) {
  12034. debug('do read');
  12035. state.reading = true;
  12036. state.sync = true; // if the length is currently zero, then we *need* a readable event.
  12037. if (state.length === 0) state.needReadable = true; // call internal read method
  12038. this._read(state.highWaterMark);
  12039. state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
  12040. // and we need to re-evaluate how much data we can return to the user.
  12041. if (!state.reading) n = howMuchToRead(nOrig, state);
  12042. }
  12043. var ret;
  12044. if (n > 0) ret = fromList(n, state);else ret = null;
  12045. if (ret === null) {
  12046. state.needReadable = state.length <= state.highWaterMark;
  12047. n = 0;
  12048. } else {
  12049. state.length -= n;
  12050. state.awaitDrain = 0;
  12051. }
  12052. if (state.length === 0) {
  12053. // If we have nothing in the buffer, then we want to know
  12054. // as soon as we *do* get something into the buffer.
  12055. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
  12056. if (nOrig !== n && state.ended) endReadable(this);
  12057. }
  12058. if (ret !== null) this.emit('data', ret);
  12059. return ret;
  12060. };
  12061. function onEofChunk(stream, state) {
  12062. debug('onEofChunk');
  12063. if (state.ended) return;
  12064. if (state.decoder) {
  12065. var chunk = state.decoder.end();
  12066. if (chunk && chunk.length) {
  12067. state.buffer.push(chunk);
  12068. state.length += state.objectMode ? 1 : chunk.length;
  12069. }
  12070. }
  12071. state.ended = true;
  12072. if (state.sync) {
  12073. // if we are sync, wait until next tick to emit the data.
  12074. // Otherwise we risk emitting data in the flow()
  12075. // the readable code triggers during a read() call
  12076. emitReadable(stream);
  12077. } else {
  12078. // emit 'readable' now to make sure it gets picked up.
  12079. state.needReadable = false;
  12080. if (!state.emittedReadable) {
  12081. state.emittedReadable = true;
  12082. emitReadable_(stream);
  12083. }
  12084. }
  12085. } // Don't emit readable right away in sync mode, because this can trigger
  12086. // another read() call => stack overflow. This way, it might trigger
  12087. // a nextTick recursion warning, but that's not so bad.
  12088. function emitReadable(stream) {
  12089. var state = stream._readableState;
  12090. debug('emitReadable', state.needReadable, state.emittedReadable);
  12091. state.needReadable = false;
  12092. if (!state.emittedReadable) {
  12093. debug('emitReadable', state.flowing);
  12094. state.emittedReadable = true;
  12095. process.nextTick(emitReadable_, stream);
  12096. }
  12097. }
  12098. function emitReadable_(stream) {
  12099. var state = stream._readableState;
  12100. debug('emitReadable_', state.destroyed, state.length, state.ended);
  12101. if (!state.destroyed && (state.length || state.ended)) {
  12102. stream.emit('readable');
  12103. state.emittedReadable = false;
  12104. } // The stream needs another readable event if
  12105. // 1. It is not flowing, as the flow mechanism will take
  12106. // care of it.
  12107. // 2. It is not ended.
  12108. // 3. It is below the highWaterMark, so we can schedule
  12109. // another readable later.
  12110. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  12111. flow(stream);
  12112. } // at this point, the user has presumably seen the 'readable' event,
  12113. // and called read() to consume some data. that may have triggered
  12114. // in turn another _read(n) call, in which case reading = true if
  12115. // it's in progress.
  12116. // However, if we're not ended, or reading, and the length < hwm,
  12117. // then go ahead and try to read some more preemptively.
  12118. function maybeReadMore(stream, state) {
  12119. if (!state.readingMore) {
  12120. state.readingMore = true;
  12121. process.nextTick(maybeReadMore_, stream, state);
  12122. }
  12123. }
  12124. function maybeReadMore_(stream, state) {
  12125. // Attempt to read more data if we should.
  12126. //
  12127. // The conditions for reading more data are (one of):
  12128. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  12129. // is responsible for filling the buffer with enough data if such data
  12130. // is available. If highWaterMark is 0 and we are not in the flowing mode
  12131. // we should _not_ attempt to buffer any extra data. We'll get more data
  12132. // when the stream consumer calls read() instead.
  12133. // - No data in the buffer, and the stream is in flowing mode. In this mode
  12134. // the loop below is responsible for ensuring read() is called. Failing to
  12135. // call read here would abort the flow and there's no other mechanism for
  12136. // continuing the flow if the stream consumer has just subscribed to the
  12137. // 'data' event.
  12138. //
  12139. // In addition to the above conditions to keep reading data, the following
  12140. // conditions prevent the data from being read:
  12141. // - The stream has ended (state.ended).
  12142. // - There is already a pending 'read' operation (state.reading). This is a
  12143. // case where the the stream has called the implementation defined _read()
  12144. // method, but they are processing the call asynchronously and have _not_
  12145. // called push() with new data. In this case we skip performing more
  12146. // read()s. The execution ends in this method again after the _read() ends
  12147. // up calling push() with more data.
  12148. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  12149. var len = state.length;
  12150. debug('maybeReadMore read 0');
  12151. stream.read(0);
  12152. if (len === state.length) // didn't get any data, stop spinning.
  12153. break;
  12154. }
  12155. state.readingMore = false;
  12156. } // abstract method. to be overridden in specific implementation classes.
  12157. // call cb(er, data) where data is <= n in length.
  12158. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  12159. // arbitrary, and perhaps not very meaningful.
  12160. Readable.prototype._read = function (n) {
  12161. errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  12162. };
  12163. Readable.prototype.pipe = function (dest, pipeOpts) {
  12164. var src = this;
  12165. var state = this._readableState;
  12166. switch (state.pipesCount) {
  12167. case 0:
  12168. state.pipes = dest;
  12169. break;
  12170. case 1:
  12171. state.pipes = [state.pipes, dest];
  12172. break;
  12173. default:
  12174. state.pipes.push(dest);
  12175. break;
  12176. }
  12177. state.pipesCount += 1;
  12178. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  12179. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  12180. var endFn = doEnd ? onend : unpipe;
  12181. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  12182. dest.on('unpipe', onunpipe);
  12183. function onunpipe(readable, unpipeInfo) {
  12184. debug('onunpipe');
  12185. if (readable === src) {
  12186. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  12187. unpipeInfo.hasUnpiped = true;
  12188. cleanup();
  12189. }
  12190. }
  12191. }
  12192. function onend() {
  12193. debug('onend');
  12194. dest.end();
  12195. } // when the dest drains, it reduces the awaitDrain counter
  12196. // on the source. This would be more elegant with a .once()
  12197. // handler in flow(), but adding and removing repeatedly is
  12198. // too slow.
  12199. var ondrain = pipeOnDrain(src);
  12200. dest.on('drain', ondrain);
  12201. var cleanedUp = false;
  12202. function cleanup() {
  12203. debug('cleanup'); // cleanup event handlers once the pipe is broken
  12204. dest.removeListener('close', onclose);
  12205. dest.removeListener('finish', onfinish);
  12206. dest.removeListener('drain', ondrain);
  12207. dest.removeListener('error', onerror);
  12208. dest.removeListener('unpipe', onunpipe);
  12209. src.removeListener('end', onend);
  12210. src.removeListener('end', unpipe);
  12211. src.removeListener('data', ondata);
  12212. cleanedUp = true; // if the reader is waiting for a drain event from this
  12213. // specific writer, then it would cause it to never start
  12214. // flowing again.
  12215. // So, if this is awaiting a drain, then we just call it now.
  12216. // If we don't know, then assume that we are waiting for one.
  12217. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  12218. }
  12219. src.on('data', ondata);
  12220. function ondata(chunk) {
  12221. debug('ondata');
  12222. var ret = dest.write(chunk);
  12223. debug('dest.write', ret);
  12224. if (ret === false) {
  12225. // If the user unpiped during `dest.write()`, it is possible
  12226. // to get stuck in a permanently paused state if that write
  12227. // also returned false.
  12228. // => Check whether `dest` is still a piping destination.
  12229. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  12230. debug('false write response, pause', state.awaitDrain);
  12231. state.awaitDrain++;
  12232. }
  12233. src.pause();
  12234. }
  12235. } // if the dest has an error, then stop piping into it.
  12236. // however, don't suppress the throwing behavior for this.
  12237. function onerror(er) {
  12238. debug('onerror', er);
  12239. unpipe();
  12240. dest.removeListener('error', onerror);
  12241. if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  12242. } // Make sure our error handler is attached before userland ones.
  12243. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
  12244. function onclose() {
  12245. dest.removeListener('finish', onfinish);
  12246. unpipe();
  12247. }
  12248. dest.once('close', onclose);
  12249. function onfinish() {
  12250. debug('onfinish');
  12251. dest.removeListener('close', onclose);
  12252. unpipe();
  12253. }
  12254. dest.once('finish', onfinish);
  12255. function unpipe() {
  12256. debug('unpipe');
  12257. src.unpipe(dest);
  12258. } // tell the dest that it's being piped to
  12259. dest.emit('pipe', src); // start the flow if it hasn't been started already.
  12260. if (!state.flowing) {
  12261. debug('pipe resume');
  12262. src.resume();
  12263. }
  12264. return dest;
  12265. };
  12266. function pipeOnDrain(src) {
  12267. return function pipeOnDrainFunctionResult() {
  12268. var state = src._readableState;
  12269. debug('pipeOnDrain', state.awaitDrain);
  12270. if (state.awaitDrain) state.awaitDrain--;
  12271. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  12272. state.flowing = true;
  12273. flow(src);
  12274. }
  12275. };
  12276. }
  12277. Readable.prototype.unpipe = function (dest) {
  12278. var state = this._readableState;
  12279. var unpipeInfo = {
  12280. hasUnpiped: false
  12281. }; // if we're not piping anywhere, then do nothing.
  12282. if (state.pipesCount === 0) return this; // just one destination. most common case.
  12283. if (state.pipesCount === 1) {
  12284. // passed in one, but it's not the right one.
  12285. if (dest && dest !== state.pipes) return this;
  12286. if (!dest) dest = state.pipes; // got a match.
  12287. state.pipes = null;
  12288. state.pipesCount = 0;
  12289. state.flowing = false;
  12290. if (dest) dest.emit('unpipe', this, unpipeInfo);
  12291. return this;
  12292. } // slow case. multiple pipe destinations.
  12293. if (!dest) {
  12294. // remove all.
  12295. var dests = state.pipes;
  12296. var len = state.pipesCount;
  12297. state.pipes = null;
  12298. state.pipesCount = 0;
  12299. state.flowing = false;
  12300. for (var i = 0; i < len; i++) {
  12301. dests[i].emit('unpipe', this, {
  12302. hasUnpiped: false
  12303. });
  12304. }
  12305. return this;
  12306. } // try to find the right one.
  12307. var index = indexOf(state.pipes, dest);
  12308. if (index === -1) return this;
  12309. state.pipes.splice(index, 1);
  12310. state.pipesCount -= 1;
  12311. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  12312. dest.emit('unpipe', this, unpipeInfo);
  12313. return this;
  12314. }; // set up data events if they are asked for
  12315. // Ensure readable listeners eventually get something
  12316. Readable.prototype.on = function (ev, fn) {
  12317. var res = Stream.prototype.on.call(this, ev, fn);
  12318. var state = this._readableState;
  12319. if (ev === 'data') {
  12320. // update readableListening so that resume() may be a no-op
  12321. // a few lines down. This is needed to support once('readable').
  12322. state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
  12323. if (state.flowing !== false) this.resume();
  12324. } else if (ev === 'readable') {
  12325. if (!state.endEmitted && !state.readableListening) {
  12326. state.readableListening = state.needReadable = true;
  12327. state.flowing = false;
  12328. state.emittedReadable = false;
  12329. debug('on readable', state.length, state.reading);
  12330. if (state.length) {
  12331. emitReadable(this);
  12332. } else if (!state.reading) {
  12333. process.nextTick(nReadingNextTick, this);
  12334. }
  12335. }
  12336. }
  12337. return res;
  12338. };
  12339. Readable.prototype.addListener = Readable.prototype.on;
  12340. Readable.prototype.removeListener = function (ev, fn) {
  12341. var res = Stream.prototype.removeListener.call(this, ev, fn);
  12342. if (ev === 'readable') {
  12343. // We need to check if there is someone still listening to
  12344. // readable and reset the state. However this needs to happen
  12345. // after readable has been emitted but before I/O (nextTick) to
  12346. // support once('readable', fn) cycles. This means that calling
  12347. // resume within the same tick will have no
  12348. // effect.
  12349. process.nextTick(updateReadableListening, this);
  12350. }
  12351. return res;
  12352. };
  12353. Readable.prototype.removeAllListeners = function (ev) {
  12354. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  12355. if (ev === 'readable' || ev === undefined) {
  12356. // We need to check if there is someone still listening to
  12357. // readable and reset the state. However this needs to happen
  12358. // after readable has been emitted but before I/O (nextTick) to
  12359. // support once('readable', fn) cycles. This means that calling
  12360. // resume within the same tick will have no
  12361. // effect.
  12362. process.nextTick(updateReadableListening, this);
  12363. }
  12364. return res;
  12365. };
  12366. function updateReadableListening(self) {
  12367. var state = self._readableState;
  12368. state.readableListening = self.listenerCount('readable') > 0;
  12369. if (state.resumeScheduled && !state.paused) {
  12370. // flowing needs to be set to true now, otherwise
  12371. // the upcoming resume will not flow.
  12372. state.flowing = true; // crude way to check if we should resume
  12373. } else if (self.listenerCount('data') > 0) {
  12374. self.resume();
  12375. }
  12376. }
  12377. function nReadingNextTick(self) {
  12378. debug('readable nexttick read 0');
  12379. self.read(0);
  12380. } // pause() and resume() are remnants of the legacy readable stream API
  12381. // If the user uses them, then switch into old mode.
  12382. Readable.prototype.resume = function () {
  12383. var state = this._readableState;
  12384. if (!state.flowing) {
  12385. debug('resume'); // we flow only if there is no one listening
  12386. // for readable, but we still have to call
  12387. // resume()
  12388. state.flowing = !state.readableListening;
  12389. resume(this, state);
  12390. }
  12391. state.paused = false;
  12392. return this;
  12393. };
  12394. function resume(stream, state) {
  12395. if (!state.resumeScheduled) {
  12396. state.resumeScheduled = true;
  12397. process.nextTick(resume_, stream, state);
  12398. }
  12399. }
  12400. function resume_(stream, state) {
  12401. debug('resume', state.reading);
  12402. if (!state.reading) {
  12403. stream.read(0);
  12404. }
  12405. state.resumeScheduled = false;
  12406. stream.emit('resume');
  12407. flow(stream);
  12408. if (state.flowing && !state.reading) stream.read(0);
  12409. }
  12410. Readable.prototype.pause = function () {
  12411. debug('call pause flowing=%j', this._readableState.flowing);
  12412. if (this._readableState.flowing !== false) {
  12413. debug('pause');
  12414. this._readableState.flowing = false;
  12415. this.emit('pause');
  12416. }
  12417. this._readableState.paused = true;
  12418. return this;
  12419. };
  12420. function flow(stream) {
  12421. var state = stream._readableState;
  12422. debug('flow', state.flowing);
  12423. while (state.flowing && stream.read() !== null) {
  12424. ;
  12425. }
  12426. } // wrap an old-style stream as the async data source.
  12427. // This is *not* part of the readable stream interface.
  12428. // It is an ugly unfortunate mess of history.
  12429. Readable.prototype.wrap = function (stream) {
  12430. var _this = this;
  12431. var state = this._readableState;
  12432. var paused = false;
  12433. stream.on('end', function () {
  12434. debug('wrapped end');
  12435. if (state.decoder && !state.ended) {
  12436. var chunk = state.decoder.end();
  12437. if (chunk && chunk.length) _this.push(chunk);
  12438. }
  12439. _this.push(null);
  12440. });
  12441. stream.on('data', function (chunk) {
  12442. debug('wrapped data');
  12443. if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
  12444. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  12445. var ret = _this.push(chunk);
  12446. if (!ret) {
  12447. paused = true;
  12448. stream.pause();
  12449. }
  12450. }); // proxy all the other methods.
  12451. // important when wrapping filters and duplexes.
  12452. for (var i in stream) {
  12453. if (this[i] === undefined && typeof stream[i] === 'function') {
  12454. this[i] = function methodWrap(method) {
  12455. return function methodWrapReturnFunction() {
  12456. return stream[method].apply(stream, arguments);
  12457. };
  12458. }(i);
  12459. }
  12460. } // proxy certain important events.
  12461. for (var n = 0; n < kProxyEvents.length; n++) {
  12462. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  12463. } // when we try to consume some more bytes, simply unpause the
  12464. // underlying stream.
  12465. this._read = function (n) {
  12466. debug('wrapped _read', n);
  12467. if (paused) {
  12468. paused = false;
  12469. stream.resume();
  12470. }
  12471. };
  12472. return this;
  12473. };
  12474. if (typeof Symbol === 'function') {
  12475. Readable.prototype[Symbol.asyncIterator] = function () {
  12476. if (createReadableStreamAsyncIterator === undefined) {
  12477. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  12478. }
  12479. return createReadableStreamAsyncIterator(this);
  12480. };
  12481. }
  12482. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  12483. // making it explicit this property is not enumerable
  12484. // because otherwise some prototype manipulation in
  12485. // userland will fail
  12486. enumerable: false,
  12487. get: function get() {
  12488. return this._readableState.highWaterMark;
  12489. }
  12490. });
  12491. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  12492. // making it explicit this property is not enumerable
  12493. // because otherwise some prototype manipulation in
  12494. // userland will fail
  12495. enumerable: false,
  12496. get: function get() {
  12497. return this._readableState && this._readableState.buffer;
  12498. }
  12499. });
  12500. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  12501. // making it explicit this property is not enumerable
  12502. // because otherwise some prototype manipulation in
  12503. // userland will fail
  12504. enumerable: false,
  12505. get: function get() {
  12506. return this._readableState.flowing;
  12507. },
  12508. set: function set(state) {
  12509. if (this._readableState) {
  12510. this._readableState.flowing = state;
  12511. }
  12512. }
  12513. }); // exposed for testing purposes only.
  12514. Readable._fromList = fromList;
  12515. Object.defineProperty(Readable.prototype, 'readableLength', {
  12516. // making it explicit this property is not enumerable
  12517. // because otherwise some prototype manipulation in
  12518. // userland will fail
  12519. enumerable: false,
  12520. get: function get() {
  12521. return this._readableState.length;
  12522. }
  12523. }); // Pluck off n bytes from an array of buffers.
  12524. // Length is the combined lengths of all the buffers in the list.
  12525. // This function is designed to be inlinable, so please take care when making
  12526. // changes to the function body.
  12527. function fromList(n, state) {
  12528. // nothing buffered
  12529. if (state.length === 0) return null;
  12530. var ret;
  12531. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  12532. // read it all, truncate the list
  12533. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  12534. state.buffer.clear();
  12535. } else {
  12536. // read part of list
  12537. ret = state.buffer.consume(n, state.decoder);
  12538. }
  12539. return ret;
  12540. }
  12541. function endReadable(stream) {
  12542. var state = stream._readableState;
  12543. debug('endReadable', state.endEmitted);
  12544. if (!state.endEmitted) {
  12545. state.ended = true;
  12546. process.nextTick(endReadableNT, state, stream);
  12547. }
  12548. }
  12549. function endReadableNT(state, stream) {
  12550. debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
  12551. if (!state.endEmitted && state.length === 0) {
  12552. state.endEmitted = true;
  12553. stream.readable = false;
  12554. stream.emit('end');
  12555. if (state.autoDestroy) {
  12556. // In case of duplex streams we need a way to detect
  12557. // if the writable side is ready for autoDestroy as well
  12558. var wState = stream._writableState;
  12559. if (!wState || wState.autoDestroy && wState.finished) {
  12560. stream.destroy();
  12561. }
  12562. }
  12563. }
  12564. }
  12565. if (typeof Symbol === 'function') {
  12566. Readable.from = function (iterable, opts) {
  12567. if (from === undefined) {
  12568. from = require('./internal/streams/from');
  12569. }
  12570. return from(Readable, iterable, opts);
  12571. };
  12572. }
  12573. function indexOf(xs, x) {
  12574. for (var i = 0, l = xs.length; i < l; i++) {
  12575. if (xs[i] === x) return i;
  12576. }
  12577. return -1;
  12578. }
  12579. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12580. },{"../errors":145,"./_stream_duplex":146,"./internal/streams/async_iterator":151,"./internal/streams/buffer_list":152,"./internal/streams/destroy":153,"./internal/streams/from":155,"./internal/streams/state":157,"./internal/streams/stream":158,"_process":96,"buffer":12,"events":79,"inherits":84,"string_decoder/":160,"util":11}],149:[function(require,module,exports){
  12581. // Copyright Joyent, Inc. and other Node contributors.
  12582. //
  12583. // Permission is hereby granted, free of charge, to any person obtaining a
  12584. // copy of this software and associated documentation files (the
  12585. // "Software"), to deal in the Software without restriction, including
  12586. // without limitation the rights to use, copy, modify, merge, publish,
  12587. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12588. // persons to whom the Software is furnished to do so, subject to the
  12589. // following conditions:
  12590. //
  12591. // The above copyright notice and this permission notice shall be included
  12592. // in all copies or substantial portions of the Software.
  12593. //
  12594. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12595. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12596. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12597. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12598. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12599. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12600. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12601. // a transform stream is a readable/writable stream where you do
  12602. // something with the data. Sometimes it's called a "filter",
  12603. // but that's not a great name for it, since that implies a thing where
  12604. // some bits pass through, and others are simply ignored. (That would
  12605. // be a valid example of a transform, of course.)
  12606. //
  12607. // While the output is causally related to the input, it's not a
  12608. // necessarily symmetric or synchronous transformation. For example,
  12609. // a zlib stream might take multiple plain-text writes(), and then
  12610. // emit a single compressed chunk some time in the future.
  12611. //
  12612. // Here's how this works:
  12613. //
  12614. // The Transform stream has all the aspects of the readable and writable
  12615. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  12616. // internally, and returns false if there's a lot of pending writes
  12617. // buffered up. When you call read(), that calls _read(n) until
  12618. // there's enough pending readable data buffered up.
  12619. //
  12620. // In a transform stream, the written data is placed in a buffer. When
  12621. // _read(n) is called, it transforms the queued up data, calling the
  12622. // buffered _write cb's as it consumes chunks. If consuming a single
  12623. // written chunk would result in multiple output chunks, then the first
  12624. // outputted bit calls the readcb, and subsequent chunks just go into
  12625. // the read buffer, and will cause it to emit 'readable' if necessary.
  12626. //
  12627. // This way, back-pressure is actually determined by the reading side,
  12628. // since _read has to be called to start processing a new chunk. However,
  12629. // a pathological inflate type of transform can cause excessive buffering
  12630. // here. For example, imagine a stream where every byte of input is
  12631. // interpreted as an integer from 0-255, and then results in that many
  12632. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  12633. // 1kb of data being output. In this case, you could write a very small
  12634. // amount of input, and end up with a very large amount of output. In
  12635. // such a pathological inflating mechanism, there'd be no way to tell
  12636. // the system to stop doing the transform. A single 4MB write could
  12637. // cause the system to run out of memory.
  12638. //
  12639. // However, even in such a pathological case, only a single written chunk
  12640. // would be consumed, and then the rest would wait (un-transformed) until
  12641. // the results of the previous transformed chunk were consumed.
  12642. 'use strict';
  12643. module.exports = Transform;
  12644. var _require$codes = require('../errors').codes,
  12645. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  12646. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  12647. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  12648. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  12649. var Duplex = require('./_stream_duplex');
  12650. require('inherits')(Transform, Duplex);
  12651. function afterTransform(er, data) {
  12652. var ts = this._transformState;
  12653. ts.transforming = false;
  12654. var cb = ts.writecb;
  12655. if (cb === null) {
  12656. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  12657. }
  12658. ts.writechunk = null;
  12659. ts.writecb = null;
  12660. if (data != null) // single equals check for both `null` and `undefined`
  12661. this.push(data);
  12662. cb(er);
  12663. var rs = this._readableState;
  12664. rs.reading = false;
  12665. if (rs.needReadable || rs.length < rs.highWaterMark) {
  12666. this._read(rs.highWaterMark);
  12667. }
  12668. }
  12669. function Transform(options) {
  12670. if (!(this instanceof Transform)) return new Transform(options);
  12671. Duplex.call(this, options);
  12672. this._transformState = {
  12673. afterTransform: afterTransform.bind(this),
  12674. needTransform: false,
  12675. transforming: false,
  12676. writecb: null,
  12677. writechunk: null,
  12678. writeencoding: null
  12679. }; // start out asking for a readable event once data is transformed.
  12680. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
  12681. // that Readable wants before the first _read call, so unset the
  12682. // sync guard flag.
  12683. this._readableState.sync = false;
  12684. if (options) {
  12685. if (typeof options.transform === 'function') this._transform = options.transform;
  12686. if (typeof options.flush === 'function') this._flush = options.flush;
  12687. } // When the writable side finishes, then flush out anything remaining.
  12688. this.on('prefinish', prefinish);
  12689. }
  12690. function prefinish() {
  12691. var _this = this;
  12692. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  12693. this._flush(function (er, data) {
  12694. done(_this, er, data);
  12695. });
  12696. } else {
  12697. done(this, null, null);
  12698. }
  12699. }
  12700. Transform.prototype.push = function (chunk, encoding) {
  12701. this._transformState.needTransform = false;
  12702. return Duplex.prototype.push.call(this, chunk, encoding);
  12703. }; // This is the part where you do stuff!
  12704. // override this function in implementation classes.
  12705. // 'chunk' is an input chunk.
  12706. //
  12707. // Call `push(newChunk)` to pass along transformed output
  12708. // to the readable side. You may call 'push' zero or more times.
  12709. //
  12710. // Call `cb(err)` when you are done with this chunk. If you pass
  12711. // an error, then that'll put the hurt on the whole operation. If you
  12712. // never call cb(), then you'll never get another chunk.
  12713. Transform.prototype._transform = function (chunk, encoding, cb) {
  12714. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  12715. };
  12716. Transform.prototype._write = function (chunk, encoding, cb) {
  12717. var ts = this._transformState;
  12718. ts.writecb = cb;
  12719. ts.writechunk = chunk;
  12720. ts.writeencoding = encoding;
  12721. if (!ts.transforming) {
  12722. var rs = this._readableState;
  12723. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  12724. }
  12725. }; // Doesn't matter what the args are here.
  12726. // _transform does all the work.
  12727. // That we got here means that the readable side wants more data.
  12728. Transform.prototype._read = function (n) {
  12729. var ts = this._transformState;
  12730. if (ts.writechunk !== null && !ts.transforming) {
  12731. ts.transforming = true;
  12732. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  12733. } else {
  12734. // mark that we need a transform, so that any data that comes in
  12735. // will get processed, now that we've asked for it.
  12736. ts.needTransform = true;
  12737. }
  12738. };
  12739. Transform.prototype._destroy = function (err, cb) {
  12740. Duplex.prototype._destroy.call(this, err, function (err2) {
  12741. cb(err2);
  12742. });
  12743. };
  12744. function done(stream, er, data) {
  12745. if (er) return stream.emit('error', er);
  12746. if (data != null) // single equals check for both `null` and `undefined`
  12747. stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
  12748. // if there's nothing in the write buffer, then that means
  12749. // that nothing more will ever be provided
  12750. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  12751. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  12752. return stream.push(null);
  12753. }
  12754. },{"../errors":145,"./_stream_duplex":146,"inherits":84}],150:[function(require,module,exports){
  12755. (function (process,global){(function (){
  12756. // Copyright Joyent, Inc. and other Node contributors.
  12757. //
  12758. // Permission is hereby granted, free of charge, to any person obtaining a
  12759. // copy of this software and associated documentation files (the
  12760. // "Software"), to deal in the Software without restriction, including
  12761. // without limitation the rights to use, copy, modify, merge, publish,
  12762. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12763. // persons to whom the Software is furnished to do so, subject to the
  12764. // following conditions:
  12765. //
  12766. // The above copyright notice and this permission notice shall be included
  12767. // in all copies or substantial portions of the Software.
  12768. //
  12769. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12770. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12771. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12772. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12773. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12774. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12775. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12776. // A bit simpler than readable streams.
  12777. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  12778. // the drain event emission and buffering.
  12779. 'use strict';
  12780. module.exports = Writable;
  12781. /* <replacement> */
  12782. function WriteReq(chunk, encoding, cb) {
  12783. this.chunk = chunk;
  12784. this.encoding = encoding;
  12785. this.callback = cb;
  12786. this.next = null;
  12787. } // It seems a linked list but it is not
  12788. // there will be only 2 of these for each stream
  12789. function CorkedRequest(state) {
  12790. var _this = this;
  12791. this.next = null;
  12792. this.entry = null;
  12793. this.finish = function () {
  12794. onCorkedFinish(_this, state);
  12795. };
  12796. }
  12797. /* </replacement> */
  12798. /*<replacement>*/
  12799. var Duplex;
  12800. /*</replacement>*/
  12801. Writable.WritableState = WritableState;
  12802. /*<replacement>*/
  12803. var internalUtil = {
  12804. deprecate: require('util-deprecate')
  12805. };
  12806. /*</replacement>*/
  12807. /*<replacement>*/
  12808. var Stream = require('./internal/streams/stream');
  12809. /*</replacement>*/
  12810. var Buffer = require('buffer').Buffer;
  12811. var OurUint8Array = global.Uint8Array || function () {};
  12812. function _uint8ArrayToBuffer(chunk) {
  12813. return Buffer.from(chunk);
  12814. }
  12815. function _isUint8Array(obj) {
  12816. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  12817. }
  12818. var destroyImpl = require('./internal/streams/destroy');
  12819. var _require = require('./internal/streams/state'),
  12820. getHighWaterMark = _require.getHighWaterMark;
  12821. var _require$codes = require('../errors').codes,
  12822. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  12823. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  12824. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  12825. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  12826. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  12827. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  12828. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  12829. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  12830. var errorOrDestroy = destroyImpl.errorOrDestroy;
  12831. require('inherits')(Writable, Stream);
  12832. function nop() {}
  12833. function WritableState(options, stream, isDuplex) {
  12834. Duplex = Duplex || require('./_stream_duplex');
  12835. options = options || {}; // Duplex streams are both readable and writable, but share
  12836. // the same options object.
  12837. // However, some cases require setting options to different
  12838. // values for the readable and the writable sides of the duplex stream,
  12839. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  12840. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
  12841. // contains buffers or objects.
  12842. this.objectMode = !!options.objectMode;
  12843. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
  12844. // Note: 0 is a valid value, means that we always return false if
  12845. // the entire buffer is not flushed immediately on write()
  12846. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
  12847. this.finalCalled = false; // drain event flag.
  12848. this.needDrain = false; // at the start of calling end()
  12849. this.ending = false; // when end() has been called, and returned
  12850. this.ended = false; // when 'finish' is emitted
  12851. this.finished = false; // has it been destroyed
  12852. this.destroyed = false; // should we decode strings into buffers before passing to _write?
  12853. // this is here so that some node-core streams can optimize string
  12854. // handling at a lower level.
  12855. var noDecode = options.decodeStrings === false;
  12856. this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
  12857. // encoding is 'binary' so we have to make this configurable.
  12858. // Everything else in the universe uses 'utf8', though.
  12859. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
  12860. // of how much we're waiting to get pushed to some underlying
  12861. // socket or file.
  12862. this.length = 0; // a flag to see when we're in the middle of a write.
  12863. this.writing = false; // when true all writes will be buffered until .uncork() call
  12864. this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
  12865. // or on a later tick. We set this to true at first, because any
  12866. // actions that shouldn't happen until "later" should generally also
  12867. // not happen before the first write call.
  12868. this.sync = true; // a flag to know if we're processing previously buffered items, which
  12869. // may call the _write() callback in the same tick, so that we don't
  12870. // end up in an overlapped onwrite situation.
  12871. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
  12872. this.onwrite = function (er) {
  12873. onwrite(stream, er);
  12874. }; // the callback that the user supplies to write(chunk,encoding,cb)
  12875. this.writecb = null; // the amount that is being written when _write is called.
  12876. this.writelen = 0;
  12877. this.bufferedRequest = null;
  12878. this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
  12879. // this must be 0 before 'finish' can be emitted
  12880. this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
  12881. // This is relevant for synchronous Transform streams
  12882. this.prefinished = false; // True if the error was already emitted and should not be thrown again
  12883. this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
  12884. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
  12885. this.autoDestroy = !!options.autoDestroy; // count buffered requests
  12886. this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
  12887. // one allocated and free to use, and we maintain at most two
  12888. this.corkedRequestsFree = new CorkedRequest(this);
  12889. }
  12890. WritableState.prototype.getBuffer = function getBuffer() {
  12891. var current = this.bufferedRequest;
  12892. var out = [];
  12893. while (current) {
  12894. out.push(current);
  12895. current = current.next;
  12896. }
  12897. return out;
  12898. };
  12899. (function () {
  12900. try {
  12901. Object.defineProperty(WritableState.prototype, 'buffer', {
  12902. get: internalUtil.deprecate(function writableStateBufferGetter() {
  12903. return this.getBuffer();
  12904. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  12905. });
  12906. } catch (_) {}
  12907. })(); // Test _writableState for inheritance to account for Duplex streams,
  12908. // whose prototype chain only points to Readable.
  12909. var realHasInstance;
  12910. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  12911. realHasInstance = Function.prototype[Symbol.hasInstance];
  12912. Object.defineProperty(Writable, Symbol.hasInstance, {
  12913. value: function value(object) {
  12914. if (realHasInstance.call(this, object)) return true;
  12915. if (this !== Writable) return false;
  12916. return object && object._writableState instanceof WritableState;
  12917. }
  12918. });
  12919. } else {
  12920. realHasInstance = function realHasInstance(object) {
  12921. return object instanceof this;
  12922. };
  12923. }
  12924. function Writable(options) {
  12925. Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
  12926. // `realHasInstance` is necessary because using plain `instanceof`
  12927. // would return false, as no `_writableState` property is attached.
  12928. // Trying to use the custom `instanceof` for Writable here will also break the
  12929. // Node.js LazyTransform implementation, which has a non-trivial getter for
  12930. // `_writableState` that would lead to infinite recursion.
  12931. // Checking for a Stream.Duplex instance is faster here instead of inside
  12932. // the WritableState constructor, at least with V8 6.5
  12933. var isDuplex = this instanceof Duplex;
  12934. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  12935. this._writableState = new WritableState(options, this, isDuplex); // legacy.
  12936. this.writable = true;
  12937. if (options) {
  12938. if (typeof options.write === 'function') this._write = options.write;
  12939. if (typeof options.writev === 'function') this._writev = options.writev;
  12940. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  12941. if (typeof options.final === 'function') this._final = options.final;
  12942. }
  12943. Stream.call(this);
  12944. } // Otherwise people can pipe Writable streams, which is just wrong.
  12945. Writable.prototype.pipe = function () {
  12946. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  12947. };
  12948. function writeAfterEnd(stream, cb) {
  12949. var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
  12950. errorOrDestroy(stream, er);
  12951. process.nextTick(cb, er);
  12952. } // Checks that a user-supplied chunk is valid, especially for the particular
  12953. // mode the stream is in. Currently this means that `null` is never accepted
  12954. // and undefined/non-string values are only allowed in object mode.
  12955. function validChunk(stream, state, chunk, cb) {
  12956. var er;
  12957. if (chunk === null) {
  12958. er = new ERR_STREAM_NULL_VALUES();
  12959. } else if (typeof chunk !== 'string' && !state.objectMode) {
  12960. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  12961. }
  12962. if (er) {
  12963. errorOrDestroy(stream, er);
  12964. process.nextTick(cb, er);
  12965. return false;
  12966. }
  12967. return true;
  12968. }
  12969. Writable.prototype.write = function (chunk, encoding, cb) {
  12970. var state = this._writableState;
  12971. var ret = false;
  12972. var isBuf = !state.objectMode && _isUint8Array(chunk);
  12973. if (isBuf && !Buffer.isBuffer(chunk)) {
  12974. chunk = _uint8ArrayToBuffer(chunk);
  12975. }
  12976. if (typeof encoding === 'function') {
  12977. cb = encoding;
  12978. encoding = null;
  12979. }
  12980. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  12981. if (typeof cb !== 'function') cb = nop;
  12982. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  12983. state.pendingcb++;
  12984. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  12985. }
  12986. return ret;
  12987. };
  12988. Writable.prototype.cork = function () {
  12989. this._writableState.corked++;
  12990. };
  12991. Writable.prototype.uncork = function () {
  12992. var state = this._writableState;
  12993. if (state.corked) {
  12994. state.corked--;
  12995. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  12996. }
  12997. };
  12998. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  12999. // node::ParseEncoding() requires lower case.
  13000. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  13001. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  13002. this._writableState.defaultEncoding = encoding;
  13003. return this;
  13004. };
  13005. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  13006. // making it explicit this property is not enumerable
  13007. // because otherwise some prototype manipulation in
  13008. // userland will fail
  13009. enumerable: false,
  13010. get: function get() {
  13011. return this._writableState && this._writableState.getBuffer();
  13012. }
  13013. });
  13014. function decodeChunk(state, chunk, encoding) {
  13015. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  13016. chunk = Buffer.from(chunk, encoding);
  13017. }
  13018. return chunk;
  13019. }
  13020. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  13021. // making it explicit this property is not enumerable
  13022. // because otherwise some prototype manipulation in
  13023. // userland will fail
  13024. enumerable: false,
  13025. get: function get() {
  13026. return this._writableState.highWaterMark;
  13027. }
  13028. }); // if we're already writing something, then just put this
  13029. // in the queue, and wait our turn. Otherwise, call _write
  13030. // If we return false, then we need a drain event, so set that flag.
  13031. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  13032. if (!isBuf) {
  13033. var newChunk = decodeChunk(state, chunk, encoding);
  13034. if (chunk !== newChunk) {
  13035. isBuf = true;
  13036. encoding = 'buffer';
  13037. chunk = newChunk;
  13038. }
  13039. }
  13040. var len = state.objectMode ? 1 : chunk.length;
  13041. state.length += len;
  13042. var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
  13043. if (!ret) state.needDrain = true;
  13044. if (state.writing || state.corked) {
  13045. var last = state.lastBufferedRequest;
  13046. state.lastBufferedRequest = {
  13047. chunk: chunk,
  13048. encoding: encoding,
  13049. isBuf: isBuf,
  13050. callback: cb,
  13051. next: null
  13052. };
  13053. if (last) {
  13054. last.next = state.lastBufferedRequest;
  13055. } else {
  13056. state.bufferedRequest = state.lastBufferedRequest;
  13057. }
  13058. state.bufferedRequestCount += 1;
  13059. } else {
  13060. doWrite(stream, state, false, len, chunk, encoding, cb);
  13061. }
  13062. return ret;
  13063. }
  13064. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  13065. state.writelen = len;
  13066. state.writecb = cb;
  13067. state.writing = true;
  13068. state.sync = true;
  13069. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  13070. state.sync = false;
  13071. }
  13072. function onwriteError(stream, state, sync, er, cb) {
  13073. --state.pendingcb;
  13074. if (sync) {
  13075. // defer the callback if we are being called synchronously
  13076. // to avoid piling up things on the stack
  13077. process.nextTick(cb, er); // this can emit finish, and it will always happen
  13078. // after error
  13079. process.nextTick(finishMaybe, stream, state);
  13080. stream._writableState.errorEmitted = true;
  13081. errorOrDestroy(stream, er);
  13082. } else {
  13083. // the caller expect this to happen before if
  13084. // it is async
  13085. cb(er);
  13086. stream._writableState.errorEmitted = true;
  13087. errorOrDestroy(stream, er); // this can emit finish, but finish must
  13088. // always follow error
  13089. finishMaybe(stream, state);
  13090. }
  13091. }
  13092. function onwriteStateUpdate(state) {
  13093. state.writing = false;
  13094. state.writecb = null;
  13095. state.length -= state.writelen;
  13096. state.writelen = 0;
  13097. }
  13098. function onwrite(stream, er) {
  13099. var state = stream._writableState;
  13100. var sync = state.sync;
  13101. var cb = state.writecb;
  13102. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  13103. onwriteStateUpdate(state);
  13104. if (er) onwriteError(stream, state, sync, er, cb);else {
  13105. // Check if we're actually ready to finish, but don't emit yet
  13106. var finished = needFinish(state) || stream.destroyed;
  13107. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  13108. clearBuffer(stream, state);
  13109. }
  13110. if (sync) {
  13111. process.nextTick(afterWrite, stream, state, finished, cb);
  13112. } else {
  13113. afterWrite(stream, state, finished, cb);
  13114. }
  13115. }
  13116. }
  13117. function afterWrite(stream, state, finished, cb) {
  13118. if (!finished) onwriteDrain(stream, state);
  13119. state.pendingcb--;
  13120. cb();
  13121. finishMaybe(stream, state);
  13122. } // Must force callback to be called on nextTick, so that we don't
  13123. // emit 'drain' before the write() consumer gets the 'false' return
  13124. // value, and has a chance to attach a 'drain' listener.
  13125. function onwriteDrain(stream, state) {
  13126. if (state.length === 0 && state.needDrain) {
  13127. state.needDrain = false;
  13128. stream.emit('drain');
  13129. }
  13130. } // if there's something in the buffer waiting, then process it
  13131. function clearBuffer(stream, state) {
  13132. state.bufferProcessing = true;
  13133. var entry = state.bufferedRequest;
  13134. if (stream._writev && entry && entry.next) {
  13135. // Fast case, write everything using _writev()
  13136. var l = state.bufferedRequestCount;
  13137. var buffer = new Array(l);
  13138. var holder = state.corkedRequestsFree;
  13139. holder.entry = entry;
  13140. var count = 0;
  13141. var allBuffers = true;
  13142. while (entry) {
  13143. buffer[count] = entry;
  13144. if (!entry.isBuf) allBuffers = false;
  13145. entry = entry.next;
  13146. count += 1;
  13147. }
  13148. buffer.allBuffers = allBuffers;
  13149. doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
  13150. // as the hot path ends with doWrite
  13151. state.pendingcb++;
  13152. state.lastBufferedRequest = null;
  13153. if (holder.next) {
  13154. state.corkedRequestsFree = holder.next;
  13155. holder.next = null;
  13156. } else {
  13157. state.corkedRequestsFree = new CorkedRequest(state);
  13158. }
  13159. state.bufferedRequestCount = 0;
  13160. } else {
  13161. // Slow case, write chunks one-by-one
  13162. while (entry) {
  13163. var chunk = entry.chunk;
  13164. var encoding = entry.encoding;
  13165. var cb = entry.callback;
  13166. var len = state.objectMode ? 1 : chunk.length;
  13167. doWrite(stream, state, false, len, chunk, encoding, cb);
  13168. entry = entry.next;
  13169. state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
  13170. // it means that we need to wait until it does.
  13171. // also, that means that the chunk and cb are currently
  13172. // being processed, so move the buffer counter past them.
  13173. if (state.writing) {
  13174. break;
  13175. }
  13176. }
  13177. if (entry === null) state.lastBufferedRequest = null;
  13178. }
  13179. state.bufferedRequest = entry;
  13180. state.bufferProcessing = false;
  13181. }
  13182. Writable.prototype._write = function (chunk, encoding, cb) {
  13183. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  13184. };
  13185. Writable.prototype._writev = null;
  13186. Writable.prototype.end = function (chunk, encoding, cb) {
  13187. var state = this._writableState;
  13188. if (typeof chunk === 'function') {
  13189. cb = chunk;
  13190. chunk = null;
  13191. encoding = null;
  13192. } else if (typeof encoding === 'function') {
  13193. cb = encoding;
  13194. encoding = null;
  13195. }
  13196. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
  13197. if (state.corked) {
  13198. state.corked = 1;
  13199. this.uncork();
  13200. } // ignore unnecessary end() calls.
  13201. if (!state.ending) endWritable(this, state, cb);
  13202. return this;
  13203. };
  13204. Object.defineProperty(Writable.prototype, 'writableLength', {
  13205. // making it explicit this property is not enumerable
  13206. // because otherwise some prototype manipulation in
  13207. // userland will fail
  13208. enumerable: false,
  13209. get: function get() {
  13210. return this._writableState.length;
  13211. }
  13212. });
  13213. function needFinish(state) {
  13214. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  13215. }
  13216. function callFinal(stream, state) {
  13217. stream._final(function (err) {
  13218. state.pendingcb--;
  13219. if (err) {
  13220. errorOrDestroy(stream, err);
  13221. }
  13222. state.prefinished = true;
  13223. stream.emit('prefinish');
  13224. finishMaybe(stream, state);
  13225. });
  13226. }
  13227. function prefinish(stream, state) {
  13228. if (!state.prefinished && !state.finalCalled) {
  13229. if (typeof stream._final === 'function' && !state.destroyed) {
  13230. state.pendingcb++;
  13231. state.finalCalled = true;
  13232. process.nextTick(callFinal, stream, state);
  13233. } else {
  13234. state.prefinished = true;
  13235. stream.emit('prefinish');
  13236. }
  13237. }
  13238. }
  13239. function finishMaybe(stream, state) {
  13240. var need = needFinish(state);
  13241. if (need) {
  13242. prefinish(stream, state);
  13243. if (state.pendingcb === 0) {
  13244. state.finished = true;
  13245. stream.emit('finish');
  13246. if (state.autoDestroy) {
  13247. // In case of duplex streams we need a way to detect
  13248. // if the readable side is ready for autoDestroy as well
  13249. var rState = stream._readableState;
  13250. if (!rState || rState.autoDestroy && rState.endEmitted) {
  13251. stream.destroy();
  13252. }
  13253. }
  13254. }
  13255. }
  13256. return need;
  13257. }
  13258. function endWritable(stream, state, cb) {
  13259. state.ending = true;
  13260. finishMaybe(stream, state);
  13261. if (cb) {
  13262. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  13263. }
  13264. state.ended = true;
  13265. stream.writable = false;
  13266. }
  13267. function onCorkedFinish(corkReq, state, err) {
  13268. var entry = corkReq.entry;
  13269. corkReq.entry = null;
  13270. while (entry) {
  13271. var cb = entry.callback;
  13272. state.pendingcb--;
  13273. cb(err);
  13274. entry = entry.next;
  13275. } // reuse the free corkReq.
  13276. state.corkedRequestsFree.next = corkReq;
  13277. }
  13278. Object.defineProperty(Writable.prototype, 'destroyed', {
  13279. // making it explicit this property is not enumerable
  13280. // because otherwise some prototype manipulation in
  13281. // userland will fail
  13282. enumerable: false,
  13283. get: function get() {
  13284. if (this._writableState === undefined) {
  13285. return false;
  13286. }
  13287. return this._writableState.destroyed;
  13288. },
  13289. set: function set(value) {
  13290. // we ignore the value if the stream
  13291. // has not been initialized yet
  13292. if (!this._writableState) {
  13293. return;
  13294. } // backward compatibility, the user is explicitly
  13295. // managing destroyed
  13296. this._writableState.destroyed = value;
  13297. }
  13298. });
  13299. Writable.prototype.destroy = destroyImpl.destroy;
  13300. Writable.prototype._undestroy = destroyImpl.undestroy;
  13301. Writable.prototype._destroy = function (err, cb) {
  13302. cb(err);
  13303. };
  13304. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13305. },{"../errors":145,"./_stream_duplex":146,"./internal/streams/destroy":153,"./internal/streams/state":157,"./internal/streams/stream":158,"_process":96,"buffer":12,"inherits":84,"util-deprecate":130}],151:[function(require,module,exports){
  13306. (function (process){(function (){
  13307. 'use strict';
  13308. var _Object$setPrototypeO;
  13309. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  13310. var finished = require('./end-of-stream');
  13311. var kLastResolve = Symbol('lastResolve');
  13312. var kLastReject = Symbol('lastReject');
  13313. var kError = Symbol('error');
  13314. var kEnded = Symbol('ended');
  13315. var kLastPromise = Symbol('lastPromise');
  13316. var kHandlePromise = Symbol('handlePromise');
  13317. var kStream = Symbol('stream');
  13318. function createIterResult(value, done) {
  13319. return {
  13320. value: value,
  13321. done: done
  13322. };
  13323. }
  13324. function readAndResolve(iter) {
  13325. var resolve = iter[kLastResolve];
  13326. if (resolve !== null) {
  13327. var data = iter[kStream].read(); // we defer if data is null
  13328. // we can be expecting either 'end' or
  13329. // 'error'
  13330. if (data !== null) {
  13331. iter[kLastPromise] = null;
  13332. iter[kLastResolve] = null;
  13333. iter[kLastReject] = null;
  13334. resolve(createIterResult(data, false));
  13335. }
  13336. }
  13337. }
  13338. function onReadable(iter) {
  13339. // we wait for the next tick, because it might
  13340. // emit an error with process.nextTick
  13341. process.nextTick(readAndResolve, iter);
  13342. }
  13343. function wrapForNext(lastPromise, iter) {
  13344. return function (resolve, reject) {
  13345. lastPromise.then(function () {
  13346. if (iter[kEnded]) {
  13347. resolve(createIterResult(undefined, true));
  13348. return;
  13349. }
  13350. iter[kHandlePromise](resolve, reject);
  13351. }, reject);
  13352. };
  13353. }
  13354. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  13355. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  13356. get stream() {
  13357. return this[kStream];
  13358. },
  13359. next: function next() {
  13360. var _this = this;
  13361. // if we have detected an error in the meanwhile
  13362. // reject straight away
  13363. var error = this[kError];
  13364. if (error !== null) {
  13365. return Promise.reject(error);
  13366. }
  13367. if (this[kEnded]) {
  13368. return Promise.resolve(createIterResult(undefined, true));
  13369. }
  13370. if (this[kStream].destroyed) {
  13371. // We need to defer via nextTick because if .destroy(err) is
  13372. // called, the error will be emitted via nextTick, and
  13373. // we cannot guarantee that there is no error lingering around
  13374. // waiting to be emitted.
  13375. return new Promise(function (resolve, reject) {
  13376. process.nextTick(function () {
  13377. if (_this[kError]) {
  13378. reject(_this[kError]);
  13379. } else {
  13380. resolve(createIterResult(undefined, true));
  13381. }
  13382. });
  13383. });
  13384. } // if we have multiple next() calls
  13385. // we will wait for the previous Promise to finish
  13386. // this logic is optimized to support for await loops,
  13387. // where next() is only called once at a time
  13388. var lastPromise = this[kLastPromise];
  13389. var promise;
  13390. if (lastPromise) {
  13391. promise = new Promise(wrapForNext(lastPromise, this));
  13392. } else {
  13393. // fast path needed to support multiple this.push()
  13394. // without triggering the next() queue
  13395. var data = this[kStream].read();
  13396. if (data !== null) {
  13397. return Promise.resolve(createIterResult(data, false));
  13398. }
  13399. promise = new Promise(this[kHandlePromise]);
  13400. }
  13401. this[kLastPromise] = promise;
  13402. return promise;
  13403. }
  13404. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  13405. return this;
  13406. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  13407. var _this2 = this;
  13408. // destroy(err, cb) is a private API
  13409. // we can guarantee we have that here, because we control the
  13410. // Readable class this is attached to
  13411. return new Promise(function (resolve, reject) {
  13412. _this2[kStream].destroy(null, function (err) {
  13413. if (err) {
  13414. reject(err);
  13415. return;
  13416. }
  13417. resolve(createIterResult(undefined, true));
  13418. });
  13419. });
  13420. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  13421. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  13422. var _Object$create;
  13423. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  13424. value: stream,
  13425. writable: true
  13426. }), _defineProperty(_Object$create, kLastResolve, {
  13427. value: null,
  13428. writable: true
  13429. }), _defineProperty(_Object$create, kLastReject, {
  13430. value: null,
  13431. writable: true
  13432. }), _defineProperty(_Object$create, kError, {
  13433. value: null,
  13434. writable: true
  13435. }), _defineProperty(_Object$create, kEnded, {
  13436. value: stream._readableState.endEmitted,
  13437. writable: true
  13438. }), _defineProperty(_Object$create, kHandlePromise, {
  13439. value: function value(resolve, reject) {
  13440. var data = iterator[kStream].read();
  13441. if (data) {
  13442. iterator[kLastPromise] = null;
  13443. iterator[kLastResolve] = null;
  13444. iterator[kLastReject] = null;
  13445. resolve(createIterResult(data, false));
  13446. } else {
  13447. iterator[kLastResolve] = resolve;
  13448. iterator[kLastReject] = reject;
  13449. }
  13450. },
  13451. writable: true
  13452. }), _Object$create));
  13453. iterator[kLastPromise] = null;
  13454. finished(stream, function (err) {
  13455. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  13456. var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
  13457. // returned by next() and store the error
  13458. if (reject !== null) {
  13459. iterator[kLastPromise] = null;
  13460. iterator[kLastResolve] = null;
  13461. iterator[kLastReject] = null;
  13462. reject(err);
  13463. }
  13464. iterator[kError] = err;
  13465. return;
  13466. }
  13467. var resolve = iterator[kLastResolve];
  13468. if (resolve !== null) {
  13469. iterator[kLastPromise] = null;
  13470. iterator[kLastResolve] = null;
  13471. iterator[kLastReject] = null;
  13472. resolve(createIterResult(undefined, true));
  13473. }
  13474. iterator[kEnded] = true;
  13475. });
  13476. stream.on('readable', onReadable.bind(null, iterator));
  13477. return iterator;
  13478. };
  13479. module.exports = createReadableStreamAsyncIterator;
  13480. }).call(this)}).call(this,require('_process'))
  13481. },{"./end-of-stream":154,"_process":96}],152:[function(require,module,exports){
  13482. 'use strict';
  13483. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  13484. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  13485. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  13486. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13487. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13488. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  13489. var _require = require('buffer'),
  13490. Buffer = _require.Buffer;
  13491. var _require2 = require('util'),
  13492. inspect = _require2.inspect;
  13493. var custom = inspect && inspect.custom || 'inspect';
  13494. function copyBuffer(src, target, offset) {
  13495. Buffer.prototype.copy.call(src, target, offset);
  13496. }
  13497. module.exports =
  13498. /*#__PURE__*/
  13499. function () {
  13500. function BufferList() {
  13501. _classCallCheck(this, BufferList);
  13502. this.head = null;
  13503. this.tail = null;
  13504. this.length = 0;
  13505. }
  13506. _createClass(BufferList, [{
  13507. key: "push",
  13508. value: function push(v) {
  13509. var entry = {
  13510. data: v,
  13511. next: null
  13512. };
  13513. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  13514. this.tail = entry;
  13515. ++this.length;
  13516. }
  13517. }, {
  13518. key: "unshift",
  13519. value: function unshift(v) {
  13520. var entry = {
  13521. data: v,
  13522. next: this.head
  13523. };
  13524. if (this.length === 0) this.tail = entry;
  13525. this.head = entry;
  13526. ++this.length;
  13527. }
  13528. }, {
  13529. key: "shift",
  13530. value: function shift() {
  13531. if (this.length === 0) return;
  13532. var ret = this.head.data;
  13533. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  13534. --this.length;
  13535. return ret;
  13536. }
  13537. }, {
  13538. key: "clear",
  13539. value: function clear() {
  13540. this.head = this.tail = null;
  13541. this.length = 0;
  13542. }
  13543. }, {
  13544. key: "join",
  13545. value: function join(s) {
  13546. if (this.length === 0) return '';
  13547. var p = this.head;
  13548. var ret = '' + p.data;
  13549. while (p = p.next) {
  13550. ret += s + p.data;
  13551. }
  13552. return ret;
  13553. }
  13554. }, {
  13555. key: "concat",
  13556. value: function concat(n) {
  13557. if (this.length === 0) return Buffer.alloc(0);
  13558. var ret = Buffer.allocUnsafe(n >>> 0);
  13559. var p = this.head;
  13560. var i = 0;
  13561. while (p) {
  13562. copyBuffer(p.data, ret, i);
  13563. i += p.data.length;
  13564. p = p.next;
  13565. }
  13566. return ret;
  13567. } // Consumes a specified amount of bytes or characters from the buffered data.
  13568. }, {
  13569. key: "consume",
  13570. value: function consume(n, hasStrings) {
  13571. var ret;
  13572. if (n < this.head.data.length) {
  13573. // `slice` is the same for buffers and strings.
  13574. ret = this.head.data.slice(0, n);
  13575. this.head.data = this.head.data.slice(n);
  13576. } else if (n === this.head.data.length) {
  13577. // First chunk is a perfect match.
  13578. ret = this.shift();
  13579. } else {
  13580. // Result spans more than one buffer.
  13581. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  13582. }
  13583. return ret;
  13584. }
  13585. }, {
  13586. key: "first",
  13587. value: function first() {
  13588. return this.head.data;
  13589. } // Consumes a specified amount of characters from the buffered data.
  13590. }, {
  13591. key: "_getString",
  13592. value: function _getString(n) {
  13593. var p = this.head;
  13594. var c = 1;
  13595. var ret = p.data;
  13596. n -= ret.length;
  13597. while (p = p.next) {
  13598. var str = p.data;
  13599. var nb = n > str.length ? str.length : n;
  13600. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  13601. n -= nb;
  13602. if (n === 0) {
  13603. if (nb === str.length) {
  13604. ++c;
  13605. if (p.next) this.head = p.next;else this.head = this.tail = null;
  13606. } else {
  13607. this.head = p;
  13608. p.data = str.slice(nb);
  13609. }
  13610. break;
  13611. }
  13612. ++c;
  13613. }
  13614. this.length -= c;
  13615. return ret;
  13616. } // Consumes a specified amount of bytes from the buffered data.
  13617. }, {
  13618. key: "_getBuffer",
  13619. value: function _getBuffer(n) {
  13620. var ret = Buffer.allocUnsafe(n);
  13621. var p = this.head;
  13622. var c = 1;
  13623. p.data.copy(ret);
  13624. n -= p.data.length;
  13625. while (p = p.next) {
  13626. var buf = p.data;
  13627. var nb = n > buf.length ? buf.length : n;
  13628. buf.copy(ret, ret.length - n, 0, nb);
  13629. n -= nb;
  13630. if (n === 0) {
  13631. if (nb === buf.length) {
  13632. ++c;
  13633. if (p.next) this.head = p.next;else this.head = this.tail = null;
  13634. } else {
  13635. this.head = p;
  13636. p.data = buf.slice(nb);
  13637. }
  13638. break;
  13639. }
  13640. ++c;
  13641. }
  13642. this.length -= c;
  13643. return ret;
  13644. } // Make sure the linked list only shows the minimal necessary information.
  13645. }, {
  13646. key: custom,
  13647. value: function value(_, options) {
  13648. return inspect(this, _objectSpread({}, options, {
  13649. // Only inspect one level.
  13650. depth: 0,
  13651. // It should not recurse.
  13652. customInspect: false
  13653. }));
  13654. }
  13655. }]);
  13656. return BufferList;
  13657. }();
  13658. },{"buffer":12,"util":11}],153:[function(require,module,exports){
  13659. (function (process){(function (){
  13660. 'use strict'; // undocumented cb() API, needed for core, not for public API
  13661. function destroy(err, cb) {
  13662. var _this = this;
  13663. var readableDestroyed = this._readableState && this._readableState.destroyed;
  13664. var writableDestroyed = this._writableState && this._writableState.destroyed;
  13665. if (readableDestroyed || writableDestroyed) {
  13666. if (cb) {
  13667. cb(err);
  13668. } else if (err) {
  13669. if (!this._writableState) {
  13670. process.nextTick(emitErrorNT, this, err);
  13671. } else if (!this._writableState.errorEmitted) {
  13672. this._writableState.errorEmitted = true;
  13673. process.nextTick(emitErrorNT, this, err);
  13674. }
  13675. }
  13676. return this;
  13677. } // we set destroyed to true before firing error callbacks in order
  13678. // to make it re-entrance safe in case destroy() is called within callbacks
  13679. if (this._readableState) {
  13680. this._readableState.destroyed = true;
  13681. } // if this is a duplex stream mark the writable part as destroyed as well
  13682. if (this._writableState) {
  13683. this._writableState.destroyed = true;
  13684. }
  13685. this._destroy(err || null, function (err) {
  13686. if (!cb && err) {
  13687. if (!_this._writableState) {
  13688. process.nextTick(emitErrorAndCloseNT, _this, err);
  13689. } else if (!_this._writableState.errorEmitted) {
  13690. _this._writableState.errorEmitted = true;
  13691. process.nextTick(emitErrorAndCloseNT, _this, err);
  13692. } else {
  13693. process.nextTick(emitCloseNT, _this);
  13694. }
  13695. } else if (cb) {
  13696. process.nextTick(emitCloseNT, _this);
  13697. cb(err);
  13698. } else {
  13699. process.nextTick(emitCloseNT, _this);
  13700. }
  13701. });
  13702. return this;
  13703. }
  13704. function emitErrorAndCloseNT(self, err) {
  13705. emitErrorNT(self, err);
  13706. emitCloseNT(self);
  13707. }
  13708. function emitCloseNT(self) {
  13709. if (self._writableState && !self._writableState.emitClose) return;
  13710. if (self._readableState && !self._readableState.emitClose) return;
  13711. self.emit('close');
  13712. }
  13713. function undestroy() {
  13714. if (this._readableState) {
  13715. this._readableState.destroyed = false;
  13716. this._readableState.reading = false;
  13717. this._readableState.ended = false;
  13718. this._readableState.endEmitted = false;
  13719. }
  13720. if (this._writableState) {
  13721. this._writableState.destroyed = false;
  13722. this._writableState.ended = false;
  13723. this._writableState.ending = false;
  13724. this._writableState.finalCalled = false;
  13725. this._writableState.prefinished = false;
  13726. this._writableState.finished = false;
  13727. this._writableState.errorEmitted = false;
  13728. }
  13729. }
  13730. function emitErrorNT(self, err) {
  13731. self.emit('error', err);
  13732. }
  13733. function errorOrDestroy(stream, err) {
  13734. // We have tests that rely on errors being emitted
  13735. // in the same tick, so changing this is semver major.
  13736. // For now when you opt-in to autoDestroy we allow
  13737. // the error to be emitted nextTick. In a future
  13738. // semver major update we should change the default to this.
  13739. var rState = stream._readableState;
  13740. var wState = stream._writableState;
  13741. if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
  13742. }
  13743. module.exports = {
  13744. destroy: destroy,
  13745. undestroy: undestroy,
  13746. errorOrDestroy: errorOrDestroy
  13747. };
  13748. }).call(this)}).call(this,require('_process'))
  13749. },{"_process":96}],154:[function(require,module,exports){
  13750. // Ported from https://github.com/mafintosh/end-of-stream with
  13751. // permission from the author, Mathias Buus (@mafintosh).
  13752. 'use strict';
  13753. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  13754. function once(callback) {
  13755. var called = false;
  13756. return function () {
  13757. if (called) return;
  13758. called = true;
  13759. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  13760. args[_key] = arguments[_key];
  13761. }
  13762. callback.apply(this, args);
  13763. };
  13764. }
  13765. function noop() {}
  13766. function isRequest(stream) {
  13767. return stream.setHeader && typeof stream.abort === 'function';
  13768. }
  13769. function eos(stream, opts, callback) {
  13770. if (typeof opts === 'function') return eos(stream, null, opts);
  13771. if (!opts) opts = {};
  13772. callback = once(callback || noop);
  13773. var readable = opts.readable || opts.readable !== false && stream.readable;
  13774. var writable = opts.writable || opts.writable !== false && stream.writable;
  13775. var onlegacyfinish = function onlegacyfinish() {
  13776. if (!stream.writable) onfinish();
  13777. };
  13778. var writableEnded = stream._writableState && stream._writableState.finished;
  13779. var onfinish = function onfinish() {
  13780. writable = false;
  13781. writableEnded = true;
  13782. if (!readable) callback.call(stream);
  13783. };
  13784. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  13785. var onend = function onend() {
  13786. readable = false;
  13787. readableEnded = true;
  13788. if (!writable) callback.call(stream);
  13789. };
  13790. var onerror = function onerror(err) {
  13791. callback.call(stream, err);
  13792. };
  13793. var onclose = function onclose() {
  13794. var err;
  13795. if (readable && !readableEnded) {
  13796. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  13797. return callback.call(stream, err);
  13798. }
  13799. if (writable && !writableEnded) {
  13800. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  13801. return callback.call(stream, err);
  13802. }
  13803. };
  13804. var onrequest = function onrequest() {
  13805. stream.req.on('finish', onfinish);
  13806. };
  13807. if (isRequest(stream)) {
  13808. stream.on('complete', onfinish);
  13809. stream.on('abort', onclose);
  13810. if (stream.req) onrequest();else stream.on('request', onrequest);
  13811. } else if (writable && !stream._writableState) {
  13812. // legacy streams
  13813. stream.on('end', onlegacyfinish);
  13814. stream.on('close', onlegacyfinish);
  13815. }
  13816. stream.on('end', onend);
  13817. stream.on('finish', onfinish);
  13818. if (opts.error !== false) stream.on('error', onerror);
  13819. stream.on('close', onclose);
  13820. return function () {
  13821. stream.removeListener('complete', onfinish);
  13822. stream.removeListener('abort', onclose);
  13823. stream.removeListener('request', onrequest);
  13824. if (stream.req) stream.req.removeListener('finish', onfinish);
  13825. stream.removeListener('end', onlegacyfinish);
  13826. stream.removeListener('close', onlegacyfinish);
  13827. stream.removeListener('finish', onfinish);
  13828. stream.removeListener('end', onend);
  13829. stream.removeListener('error', onerror);
  13830. stream.removeListener('close', onclose);
  13831. };
  13832. }
  13833. module.exports = eos;
  13834. },{"../../../errors":145}],155:[function(require,module,exports){
  13835. module.exports = function () {
  13836. throw new Error('Readable.from is not available in the browser')
  13837. };
  13838. },{}],156:[function(require,module,exports){
  13839. // Ported from https://github.com/mafintosh/pump with
  13840. // permission from the author, Mathias Buus (@mafintosh).
  13841. 'use strict';
  13842. var eos;
  13843. function once(callback) {
  13844. var called = false;
  13845. return function () {
  13846. if (called) return;
  13847. called = true;
  13848. callback.apply(void 0, arguments);
  13849. };
  13850. }
  13851. var _require$codes = require('../../../errors').codes,
  13852. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  13853. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  13854. function noop(err) {
  13855. // Rethrow the error if it exists to avoid swallowing it
  13856. if (err) throw err;
  13857. }
  13858. function isRequest(stream) {
  13859. return stream.setHeader && typeof stream.abort === 'function';
  13860. }
  13861. function destroyer(stream, reading, writing, callback) {
  13862. callback = once(callback);
  13863. var closed = false;
  13864. stream.on('close', function () {
  13865. closed = true;
  13866. });
  13867. if (eos === undefined) eos = require('./end-of-stream');
  13868. eos(stream, {
  13869. readable: reading,
  13870. writable: writing
  13871. }, function (err) {
  13872. if (err) return callback(err);
  13873. closed = true;
  13874. callback();
  13875. });
  13876. var destroyed = false;
  13877. return function (err) {
  13878. if (closed) return;
  13879. if (destroyed) return;
  13880. destroyed = true; // request.destroy just do .end - .abort is what we want
  13881. if (isRequest(stream)) return stream.abort();
  13882. if (typeof stream.destroy === 'function') return stream.destroy();
  13883. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  13884. };
  13885. }
  13886. function call(fn) {
  13887. fn();
  13888. }
  13889. function pipe(from, to) {
  13890. return from.pipe(to);
  13891. }
  13892. function popCallback(streams) {
  13893. if (!streams.length) return noop;
  13894. if (typeof streams[streams.length - 1] !== 'function') return noop;
  13895. return streams.pop();
  13896. }
  13897. function pipeline() {
  13898. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  13899. streams[_key] = arguments[_key];
  13900. }
  13901. var callback = popCallback(streams);
  13902. if (Array.isArray(streams[0])) streams = streams[0];
  13903. if (streams.length < 2) {
  13904. throw new ERR_MISSING_ARGS('streams');
  13905. }
  13906. var error;
  13907. var destroys = streams.map(function (stream, i) {
  13908. var reading = i < streams.length - 1;
  13909. var writing = i > 0;
  13910. return destroyer(stream, reading, writing, function (err) {
  13911. if (!error) error = err;
  13912. if (err) destroys.forEach(call);
  13913. if (reading) return;
  13914. destroys.forEach(call);
  13915. callback(error);
  13916. });
  13917. });
  13918. return streams.reduce(pipe);
  13919. }
  13920. module.exports = pipeline;
  13921. },{"../../../errors":145,"./end-of-stream":154}],157:[function(require,module,exports){
  13922. 'use strict';
  13923. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  13924. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  13925. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  13926. }
  13927. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  13928. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  13929. if (hwm != null) {
  13930. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  13931. var name = isDuplex ? duplexKey : 'highWaterMark';
  13932. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  13933. }
  13934. return Math.floor(hwm);
  13935. } // Default value
  13936. return state.objectMode ? 16 : 16 * 1024;
  13937. }
  13938. module.exports = {
  13939. getHighWaterMark: getHighWaterMark
  13940. };
  13941. },{"../../../errors":145}],158:[function(require,module,exports){
  13942. arguments[4][109][0].apply(exports,arguments)
  13943. },{"dup":109,"events":79}],159:[function(require,module,exports){
  13944. exports = module.exports = require('./lib/_stream_readable.js');
  13945. exports.Stream = exports;
  13946. exports.Readable = exports;
  13947. exports.Writable = require('./lib/_stream_writable.js');
  13948. exports.Duplex = require('./lib/_stream_duplex.js');
  13949. exports.Transform = require('./lib/_stream_transform.js');
  13950. exports.PassThrough = require('./lib/_stream_passthrough.js');
  13951. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  13952. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  13953. },{"./lib/_stream_duplex.js":146,"./lib/_stream_passthrough.js":147,"./lib/_stream_readable.js":148,"./lib/_stream_transform.js":149,"./lib/_stream_writable.js":150,"./lib/internal/streams/end-of-stream.js":154,"./lib/internal/streams/pipeline.js":156}],160:[function(require,module,exports){
  13954. arguments[4][111][0].apply(exports,arguments)
  13955. },{"dup":111,"safe-buffer":161}],161:[function(require,module,exports){
  13956. arguments[4][110][0].apply(exports,arguments)
  13957. },{"buffer":12,"dup":110}],162:[function(require,module,exports){
  13958. (function (process,global){(function (){
  13959. 'use strict'
  13960. var Transform = require('readable-stream').Transform
  13961. var duplexify = require('duplexify')
  13962. var WS = require('ws')
  13963. var Buffer = require('safe-buffer').Buffer
  13964. module.exports = WebSocketStream
  13965. function buildProxy (options, socketWrite, socketEnd) {
  13966. var proxy = new Transform({
  13967. objectMode: options.objectMode
  13968. })
  13969. proxy._write = socketWrite
  13970. proxy._flush = socketEnd
  13971. return proxy
  13972. }
  13973. function WebSocketStream(target, protocols, options) {
  13974. var stream, socket
  13975. var isBrowser = process.title === 'browser'
  13976. var isNative = !!global.WebSocket
  13977. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  13978. if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
  13979. // accept the "options" Object as the 2nd argument
  13980. options = protocols
  13981. protocols = null
  13982. if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
  13983. protocols = options.protocol;
  13984. }
  13985. }
  13986. if (!options) options = {}
  13987. if (options.objectMode === undefined) {
  13988. options.objectMode = !(options.binary === true || options.binary === undefined)
  13989. }
  13990. var proxy = buildProxy(options, socketWrite, socketEnd)
  13991. if (!options.objectMode) {
  13992. proxy._writev = writev
  13993. }
  13994. // browser only: sets the maximum socket buffer size before throttling
  13995. var bufferSize = options.browserBufferSize || 1024 * 512
  13996. // browser only: how long to wait when throttling
  13997. var bufferTimeout = options.browserBufferTimeout || 1000
  13998. // use existing WebSocket object that was passed in
  13999. if (typeof target === 'object') {
  14000. socket = target
  14001. // otherwise make a new one
  14002. } else {
  14003. // special constructor treatment for native websockets in browsers, see
  14004. // https://github.com/maxogden/websocket-stream/issues/82
  14005. if (isNative && isBrowser) {
  14006. socket = new WS(target, protocols)
  14007. } else {
  14008. socket = new WS(target, protocols, options)
  14009. }
  14010. socket.binaryType = 'arraybuffer'
  14011. }
  14012. // was already open when passed in
  14013. if (socket.readyState === socket.OPEN) {
  14014. stream = proxy
  14015. } else if (isBrowser) {
  14016. stream = proxy
  14017. stream.cork()
  14018. socket.onopen = onopenBrowser
  14019. } else {
  14020. stream = duplexify.obj()
  14021. socket.onopen = onopen
  14022. }
  14023. stream.socket = socket
  14024. socket.onclose = onclose
  14025. socket.onerror = onerror
  14026. socket.onmessage = onmessage
  14027. proxy.on('close', destroy)
  14028. var coerceToBuffer = !options.objectMode
  14029. function socketWriteNode(chunk, enc, next) {
  14030. // avoid errors, this never happens unless
  14031. // destroy() is called
  14032. if (socket.readyState !== socket.OPEN) {
  14033. next()
  14034. return
  14035. }
  14036. if (coerceToBuffer && typeof chunk === 'string') {
  14037. chunk = Buffer.from(chunk, 'utf8')
  14038. }
  14039. socket.send(chunk, next)
  14040. }
  14041. function socketWriteBrowser(chunk, enc, next) {
  14042. if (socket.bufferedAmount > bufferSize) {
  14043. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  14044. return
  14045. }
  14046. if (coerceToBuffer && typeof chunk === 'string') {
  14047. chunk = Buffer.from(chunk, 'utf8')
  14048. }
  14049. try {
  14050. socket.send(chunk)
  14051. } catch(err) {
  14052. return next(err)
  14053. }
  14054. next()
  14055. }
  14056. function socketEnd(done) {
  14057. socket.close()
  14058. done()
  14059. }
  14060. function onopen() {
  14061. stream.setReadable(proxy)
  14062. stream.setWritable(proxy)
  14063. stream.emit('connect')
  14064. }
  14065. function onopenBrowser () {
  14066. stream.uncork()
  14067. stream.emit('connect')
  14068. }
  14069. function onclose() {
  14070. stream.end()
  14071. stream.destroy()
  14072. }
  14073. function onerror(err) {
  14074. stream.destroy(err)
  14075. }
  14076. function onmessage(event) {
  14077. var data = event.data
  14078. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  14079. else data = Buffer.from(data, 'utf8')
  14080. proxy.push(data)
  14081. }
  14082. function destroy() {
  14083. socket.close()
  14084. }
  14085. // this is to be enabled only if objectMode is false
  14086. function writev (chunks, cb) {
  14087. var buffers = new Array(chunks.length)
  14088. for (var i = 0; i < chunks.length; i++) {
  14089. if (typeof chunks[i].chunk === 'string') {
  14090. buffers[i] = Buffer.from(chunks[i], 'utf8')
  14091. } else {
  14092. buffers[i] = chunks[i].chunk
  14093. }
  14094. }
  14095. this._write(Buffer.concat(buffers), 'binary', cb)
  14096. }
  14097. return stream
  14098. }
  14099. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14100. },{"_process":96,"duplexify":134,"readable-stream":159,"safe-buffer":114,"ws":163}],163:[function(require,module,exports){
  14101. var ws = null
  14102. if (typeof WebSocket !== 'undefined') {
  14103. ws = WebSocket
  14104. } else if (typeof MozWebSocket !== 'undefined') {
  14105. ws = MozWebSocket
  14106. } else if (typeof window !== 'undefined') {
  14107. ws = window.WebSocket || window.MozWebSocket
  14108. }
  14109. module.exports = ws
  14110. },{}],164:[function(require,module,exports){
  14111. // Returns a wrapper function that returns a wrapped callback
  14112. // The wrapper function should do some stuff, and return a
  14113. // presumably different callback function.
  14114. // This makes sure that own properties are retained, so that
  14115. // decorations and such are not lost along the way.
  14116. module.exports = wrappy
  14117. function wrappy (fn, cb) {
  14118. if (fn && cb) return wrappy(fn)(cb)
  14119. if (typeof fn !== 'function')
  14120. throw new TypeError('need wrapper function')
  14121. Object.keys(fn).forEach(function (k) {
  14122. wrapper[k] = fn[k]
  14123. })
  14124. return wrapper
  14125. function wrapper() {
  14126. var args = new Array(arguments.length)
  14127. for (var i = 0; i < args.length; i++) {
  14128. args[i] = arguments[i]
  14129. }
  14130. var ret = fn.apply(this, args)
  14131. var cb = args[args.length-1]
  14132. if (typeof ret === 'function' && ret !== cb) {
  14133. Object.keys(cb).forEach(function (k) {
  14134. ret[k] = cb[k]
  14135. })
  14136. }
  14137. return ret
  14138. }
  14139. }
  14140. },{}],165:[function(require,module,exports){
  14141. module.exports = extend
  14142. var hasOwnProperty = Object.prototype.hasOwnProperty;
  14143. function extend() {
  14144. var target = {}
  14145. for (var i = 0; i < arguments.length; i++) {
  14146. var source = arguments[i]
  14147. for (var key in source) {
  14148. if (hasOwnProperty.call(source, key)) {
  14149. target[key] = source[key]
  14150. }
  14151. }
  14152. }
  14153. return target
  14154. }
  14155. },{}]},{},[8])(8)
  14156. });