mqtt.js 428 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716
  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){
  3. 'use strict'
  4. /**
  5. * Module dependencies
  6. */
  7. var EventEmitter = require('events').EventEmitter
  8. var Store = require('./store')
  9. var mqttPacket = require('mqtt-packet')
  10. var Writable = require('readable-stream').Writable
  11. var inherits = require('inherits')
  12. var reInterval = require('reinterval')
  13. var validations = require('./validations')
  14. var xtend = require('xtend')
  15. var debug = require('debug')('mqttjs:client')
  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. var socketErrors = [
  31. 'ECONNREFUSED',
  32. 'EADDRINUSE',
  33. 'ECONNRESET',
  34. 'ENOTFOUND'
  35. ]
  36. // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.
  37. var errors = {
  38. 0: '',
  39. 1: 'Unacceptable protocol version',
  40. 2: 'Identifier rejected',
  41. 3: 'Server unavailable',
  42. 4: 'Bad username or password',
  43. 5: 'Not authorized',
  44. 16: 'No matching subscribers',
  45. 17: 'No subscription existed',
  46. 128: 'Unspecified error',
  47. 129: 'Malformed Packet',
  48. 130: 'Protocol Error',
  49. 131: 'Implementation specific error',
  50. 132: 'Unsupported Protocol Version',
  51. 133: 'Client Identifier not valid',
  52. 134: 'Bad User Name or Password',
  53. 135: 'Not authorized',
  54. 136: 'Server unavailable',
  55. 137: 'Server busy',
  56. 138: 'Banned',
  57. 139: 'Server shutting down',
  58. 140: 'Bad authentication method',
  59. 141: 'Keep Alive timeout',
  60. 142: 'Session taken over',
  61. 143: 'Topic Filter invalid',
  62. 144: 'Topic Name invalid',
  63. 145: 'Packet identifier in use',
  64. 146: 'Packet Identifier not found',
  65. 147: 'Receive Maximum exceeded',
  66. 148: 'Topic Alias invalid',
  67. 149: 'Packet too large',
  68. 150: 'Message rate too high',
  69. 151: 'Quota exceeded',
  70. 152: 'Administrative action',
  71. 153: 'Payload format invalid',
  72. 154: 'Retain not supported',
  73. 155: 'QoS not supported',
  74. 156: 'Use another server',
  75. 157: 'Server moved',
  76. 158: 'Shared Subscriptions not supported',
  77. 159: 'Connection rate exceeded',
  78. 160: 'Maximum connect time',
  79. 161: 'Subscription Identifiers not supported',
  80. 162: 'Wildcard Subscriptions not supported'
  81. }
  82. function defaultId () {
  83. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  84. }
  85. function sendPacket (client, packet, cb) {
  86. debug('sendPacket :: packet: %O', packet)
  87. debug('sendPacket :: emitting `packetsend`')
  88. client.emit('packetsend', packet)
  89. debug('sendPacket :: writing to stream')
  90. var result = mqttPacket.writeToStream(packet, client.stream, client.options)
  91. debug('sendPacket :: writeToStream result %s', result)
  92. if (!result && cb) {
  93. debug('sendPacket :: handle events on `drain` once through callback.')
  94. client.stream.once('drain', cb)
  95. } else if (cb) {
  96. debug('sendPacket :: invoking cb')
  97. cb()
  98. }
  99. }
  100. function flush (queue) {
  101. if (queue) {
  102. debug('flush: queue exists? %b', !!(queue))
  103. Object.keys(queue).forEach(function (messageId) {
  104. if (typeof queue[messageId].cb === 'function') {
  105. queue[messageId].cb(new Error('Connection closed'))
  106. delete queue[messageId]
  107. }
  108. })
  109. }
  110. }
  111. function flushVolatile (queue) {
  112. if (queue) {
  113. debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')
  114. Object.keys(queue).forEach(function (messageId) {
  115. if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
  116. queue[messageId].cb(new Error('Connection closed'))
  117. delete queue[messageId]
  118. }
  119. })
  120. }
  121. }
  122. function storeAndSend (client, packet, cb, cbStorePut) {
  123. debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)
  124. client.outgoingStore.put(packet, function storedPacket (err) {
  125. if (err) {
  126. return cb && cb(err)
  127. }
  128. cbStorePut()
  129. sendPacket(client, packet, cb)
  130. })
  131. }
  132. function nop (error) {
  133. debug('nop ::', error)
  134. }
  135. /**
  136. * MqttClient constructor
  137. *
  138. * @param {Stream} stream - stream
  139. * @param {Object} [options] - connection options
  140. * (see Connection#connect)
  141. */
  142. function MqttClient (streamBuilder, options) {
  143. var k
  144. var that = this
  145. if (!(this instanceof MqttClient)) {
  146. return new MqttClient(streamBuilder, options)
  147. }
  148. this.options = options || {}
  149. // Defaults
  150. for (k in defaultConnectOptions) {
  151. if (typeof this.options[k] === 'undefined') {
  152. this.options[k] = defaultConnectOptions[k]
  153. } else {
  154. this.options[k] = options[k]
  155. }
  156. }
  157. debug('MqttClient :: options.protocol', options.protocol)
  158. debug('MqttClient :: options.protocolVersion', options.protocolVersion)
  159. debug('MqttClient :: options.username', options.username)
  160. debug('MqttClient :: options.keepalive', options.keepalive)
  161. debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)
  162. debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)
  163. this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
  164. debug('MqttClient :: clientId', this.options.clientId)
  165. this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
  166. this.streamBuilder = streamBuilder
  167. // Inflight message storages
  168. this.outgoingStore = options.outgoingStore || new Store()
  169. this.incomingStore = options.incomingStore || new Store()
  170. // Should QoS zero messages be queued when the connection is broken?
  171. this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
  172. // map of subscribed topics to support reconnection
  173. this._resubscribeTopics = {}
  174. // map of a subscribe messageId and a topic
  175. this.messageIdToTopic = {}
  176. // Ping timer, setup in _setupPingTimer
  177. this.pingTimer = null
  178. // Is the client connected?
  179. this.connected = false
  180. // Are we disconnecting?
  181. this.disconnecting = false
  182. // Packet queue
  183. this.queue = []
  184. // connack timer
  185. this.connackTimer = null
  186. // Reconnect timer
  187. this.reconnectTimer = null
  188. // Is processing store?
  189. this._storeProcessing = false
  190. // Packet Ids are put into the store during store processing
  191. this._packetIdsDuringStoreProcessing = {}
  192. /**
  193. * MessageIDs starting with 1
  194. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  195. */
  196. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  197. // Inflight callbacks
  198. this.outgoing = {}
  199. // True if connection is first time.
  200. this._firstConnection = true
  201. // Send queued packets
  202. this.on('connect', function () {
  203. var queue = this.queue
  204. function deliver () {
  205. var entry = queue.shift()
  206. debug('deliver :: entry %o', entry)
  207. var packet = null
  208. if (!entry) {
  209. return
  210. }
  211. packet = entry.packet
  212. debug('deliver :: call _sendPacket for %o', packet)
  213. that._sendPacket(
  214. packet,
  215. function (err) {
  216. if (entry.cb) {
  217. entry.cb(err)
  218. }
  219. deliver()
  220. }
  221. )
  222. }
  223. debug('connect :: sending queued packets')
  224. deliver()
  225. })
  226. this.on('close', function () {
  227. debug('close :: connected set to `false`')
  228. this.connected = false
  229. debug('close :: clearing connackTimer')
  230. clearTimeout(this.connackTimer)
  231. debug('close :: clearing ping timer')
  232. if (that.pingTimer !== null) {
  233. that.pingTimer.clear()
  234. that.pingTimer = null
  235. }
  236. debug('close :: calling _setupReconnect')
  237. this._setupReconnect()
  238. })
  239. EventEmitter.call(this)
  240. debug('MqttClient :: setting up stream')
  241. this._setupStream()
  242. }
  243. inherits(MqttClient, EventEmitter)
  244. /**
  245. * setup the event handlers in the inner stream.
  246. *
  247. * @api private
  248. */
  249. MqttClient.prototype._setupStream = function () {
  250. var connectPacket
  251. var that = this
  252. var writable = new Writable()
  253. var parser = mqttPacket.parser(this.options)
  254. var completeParse = null
  255. var packets = []
  256. debug('_setupStream :: calling method to clear reconnect')
  257. this._clearReconnect()
  258. debug('_setupStream :: using streamBuilder provided to client to create stream')
  259. this.stream = this.streamBuilder(this)
  260. parser.on('packet', function (packet) {
  261. debug('parser :: on packet push to packets array.')
  262. packets.push(packet)
  263. })
  264. function nextTickWork () {
  265. if (packets.length) {
  266. process.nextTick(work)
  267. } else {
  268. var done = completeParse
  269. completeParse = null
  270. done()
  271. }
  272. }
  273. function work () {
  274. debug('work :: getting next packet in queue')
  275. var packet = packets.shift()
  276. if (packet) {
  277. debug('work :: packet pulled from queue')
  278. that._handlePacket(packet, nextTickWork)
  279. } else {
  280. debug('work :: no packets in queue')
  281. var done = completeParse
  282. completeParse = null
  283. debug('work :: done flag is %s', !!(done))
  284. if (done) done()
  285. }
  286. }
  287. writable._write = function (buf, enc, done) {
  288. completeParse = done
  289. debug('writable stream :: parsing buffer')
  290. parser.parse(buf)
  291. work()
  292. }
  293. function streamErrorHandler (error) {
  294. debug('streamErrorHandler :: error', error.message)
  295. if (socketErrors.includes(error.code)) {
  296. // handle error
  297. debug('streamErrorHandler :: emitting error')
  298. that.emit('error', error)
  299. } else {
  300. nop(error)
  301. }
  302. }
  303. debug('_setupStream :: pipe stream to writable stream')
  304. this.stream.pipe(writable)
  305. // Suppress connection errors
  306. this.stream.on('error', streamErrorHandler)
  307. // Echo stream close
  308. this.stream.on('close', function () {
  309. debug('(%s)stream :: on close', that.options.clientId)
  310. flushVolatile(that.outgoing)
  311. debug('stream: emit close to MqttClient')
  312. that.emit('close')
  313. })
  314. // Send a connect packet
  315. debug('_setupStream: sending packet `connect`')
  316. connectPacket = Object.create(this.options)
  317. connectPacket.cmd = 'connect'
  318. // avoid message queue
  319. sendPacket(this, connectPacket)
  320. // Echo connection errors
  321. parser.on('error', this.emit.bind(this, 'error'))
  322. // auth
  323. if (this.options.properties) {
  324. if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
  325. that.end(() =>
  326. this.emit('error', new Error('Packet has no Authentication Method')
  327. ))
  328. return this
  329. }
  330. if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
  331. var authPacket = xtend({cmd: 'auth', reasonCode: 0}, this.options.authPacket)
  332. sendPacket(this, authPacket)
  333. }
  334. }
  335. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  336. this.stream.setMaxListeners(1000)
  337. clearTimeout(this.connackTimer)
  338. this.connackTimer = setTimeout(function () {
  339. debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')
  340. that._cleanUp(true)
  341. }, this.options.connectTimeout)
  342. }
  343. MqttClient.prototype._handlePacket = function (packet, done) {
  344. var options = this.options
  345. if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
  346. this.emit('error', new Error('exceeding packets size ' + packet.cmd))
  347. this.end({reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }})
  348. return this
  349. }
  350. debug('_handlePacket :: emitting packetreceive')
  351. this.emit('packetreceive', packet)
  352. switch (packet.cmd) {
  353. case 'publish':
  354. this._handlePublish(packet, done)
  355. break
  356. case 'puback':
  357. case 'pubrec':
  358. case 'pubcomp':
  359. case 'suback':
  360. case 'unsuback':
  361. this._handleAck(packet)
  362. done()
  363. break
  364. case 'pubrel':
  365. this._handlePubrel(packet, done)
  366. break
  367. case 'connack':
  368. this._handleConnack(packet)
  369. done()
  370. break
  371. case 'pingresp':
  372. this._handlePingresp(packet)
  373. done()
  374. break
  375. case 'disconnect':
  376. this._handleDisconnect(packet)
  377. done()
  378. break
  379. default:
  380. // do nothing
  381. // maybe we should do an error handling
  382. // or just log it
  383. break
  384. }
  385. }
  386. MqttClient.prototype._checkDisconnecting = function (callback) {
  387. if (this.disconnecting) {
  388. if (callback) {
  389. callback(new Error('client disconnecting'))
  390. } else {
  391. this.emit('error', new Error('client disconnecting'))
  392. }
  393. }
  394. return this.disconnecting
  395. }
  396. /**
  397. * publish - publish <message> to <topic>
  398. *
  399. * @param {String} topic - topic to publish to
  400. * @param {String, Buffer} message - message to publish
  401. * @param {Object} [opts] - publish options, includes:
  402. * {Number} qos - qos level to publish on
  403. * {Boolean} retain - whether or not to retain the message
  404. * {Boolean} dup - whether or not mark a message as duplicate
  405. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  406. * @param {Function} [callback] - function(err){}
  407. * called when publish succeeds or fails
  408. * @returns {MqttClient} this - for chaining
  409. * @api public
  410. *
  411. * @example client.publish('topic', 'message');
  412. * @example
  413. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  414. * @example client.publish('topic', 'message', console.log);
  415. */
  416. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  417. debug('publish :: message `%s` to topic `%s`', message, topic)
  418. var packet
  419. var options = this.options
  420. // .publish(topic, payload, cb);
  421. if (typeof opts === 'function') {
  422. callback = opts
  423. opts = null
  424. }
  425. // default opts
  426. var defaultOpts = {qos: 0, retain: false, dup: false}
  427. opts = xtend(defaultOpts, opts)
  428. if (this._checkDisconnecting(callback)) {
  429. return this
  430. }
  431. packet = {
  432. cmd: 'publish',
  433. topic: topic,
  434. payload: message,
  435. qos: opts.qos,
  436. retain: opts.retain,
  437. messageId: this._nextId(),
  438. dup: opts.dup
  439. }
  440. if (options.protocolVersion === 5) {
  441. packet.properties = opts.properties
  442. if ((!options.properties && packet.properties && packet.properties.topicAlias) || ((opts.properties && options.properties) &&
  443. ((opts.properties.topicAlias && options.properties.topicAliasMaximum && opts.properties.topicAlias > options.properties.topicAliasMaximum) ||
  444. (!options.properties.topicAliasMaximum && opts.properties.topicAlias)))) {
  445. /*
  446. if we are don`t setup topic alias or
  447. topic alias maximum less than topic alias or
  448. server don`t give topic alias maximum,
  449. we are removing topic alias from packet
  450. */
  451. delete packet.properties.topicAlias
  452. }
  453. }
  454. debug('publish :: qos', opts.qos)
  455. switch (opts.qos) {
  456. case 1:
  457. case 2:
  458. // Add to callbacks
  459. this.outgoing[packet.messageId] = {
  460. volatile: false,
  461. cb: callback || nop
  462. }
  463. if (this._storeProcessing) {
  464. debug('_storeProcessing enabled')
  465. this._packetIdsDuringStoreProcessing[packet.messageId] = false
  466. this._storePacket(packet, undefined, opts.cbStorePut)
  467. } else {
  468. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  469. this._sendPacket(packet, undefined, opts.cbStorePut)
  470. }
  471. break
  472. default:
  473. if (this._storeProcessing) {
  474. debug('_storeProcessing enabled')
  475. this._storePacket(packet, callback, opts.cbStorePut)
  476. } else {
  477. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  478. this._sendPacket(packet, callback, opts.cbStorePut)
  479. }
  480. break
  481. }
  482. return this
  483. }
  484. /**
  485. * subscribe - subscribe to <topic>
  486. *
  487. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  488. * @param {Object} [opts] - optional subscription options, includes:
  489. * {Number} qos - subscribe qos level
  490. * @param {Function} [callback] - function(err, granted){} where:
  491. * {Error} err - subscription error (none at the moment!)
  492. * {Array} granted - array of {topic: 't', qos: 0}
  493. * @returns {MqttClient} this - for chaining
  494. * @api public
  495. * @example client.subscribe('topic');
  496. * @example client.subscribe('topic', {qos: 1});
  497. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  498. * @example client.subscribe('topic', console.log);
  499. */
  500. MqttClient.prototype.subscribe = function () {
  501. var packet
  502. var args = new Array(arguments.length)
  503. for (var i = 0; i < arguments.length; i++) {
  504. args[i] = arguments[i]
  505. }
  506. var subs = []
  507. var obj = args.shift()
  508. var resubscribe = obj.resubscribe
  509. var callback = args.pop() || nop
  510. var opts = args.pop()
  511. var invalidTopic
  512. var that = this
  513. var version = this.options.protocolVersion
  514. delete obj.resubscribe
  515. if (typeof obj === 'string') {
  516. obj = [obj]
  517. }
  518. if (typeof callback !== 'function') {
  519. opts = callback
  520. callback = nop
  521. }
  522. invalidTopic = validations.validateTopics(obj)
  523. if (invalidTopic !== null) {
  524. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  525. return this
  526. }
  527. if (this._checkDisconnecting(callback)) {
  528. debug('subscribe: discconecting true')
  529. return this
  530. }
  531. var defaultOpts = {
  532. qos: 0
  533. }
  534. if (version === 5) {
  535. defaultOpts.nl = false
  536. defaultOpts.rap = false
  537. defaultOpts.rh = 0
  538. }
  539. opts = xtend(defaultOpts, opts)
  540. if (Array.isArray(obj)) {
  541. obj.forEach(function (topic) {
  542. debug('subscribe: array topic %s', topic)
  543. if (!that._resubscribeTopics.hasOwnProperty(topic) ||
  544. that._resubscribeTopics[topic].qos < opts.qos ||
  545. resubscribe) {
  546. var currentOpts = {
  547. topic: topic,
  548. qos: opts.qos
  549. }
  550. if (version === 5) {
  551. currentOpts.nl = opts.nl
  552. currentOpts.rap = opts.rap
  553. currentOpts.rh = opts.rh
  554. currentOpts.properties = opts.properties
  555. }
  556. debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
  557. subs.push(currentOpts)
  558. }
  559. })
  560. } else {
  561. Object
  562. .keys(obj)
  563. .forEach(function (k) {
  564. debug('subscribe: object topic %s', k)
  565. if (!that._resubscribeTopics.hasOwnProperty(k) ||
  566. that._resubscribeTopics[k].qos < obj[k].qos ||
  567. resubscribe) {
  568. var currentOpts = {
  569. topic: k,
  570. qos: obj[k].qos
  571. }
  572. if (version === 5) {
  573. currentOpts.nl = obj[k].nl
  574. currentOpts.rap = obj[k].rap
  575. currentOpts.rh = obj[k].rh
  576. currentOpts.properties = opts.properties
  577. }
  578. debug('subscribe: pushing `%s` to subs list', currentOpts)
  579. subs.push(currentOpts)
  580. }
  581. })
  582. }
  583. packet = {
  584. cmd: 'subscribe',
  585. subscriptions: subs,
  586. qos: 1,
  587. retain: false,
  588. dup: false,
  589. messageId: this._nextId()
  590. }
  591. if (opts.properties) {
  592. packet.properties = opts.properties
  593. }
  594. if (!subs.length) {
  595. callback(null, [])
  596. return
  597. }
  598. // subscriptions to resubscribe to in case of disconnect
  599. if (this.options.resubscribe) {
  600. debug('subscribe :: resubscribe true')
  601. var topics = []
  602. subs.forEach(function (sub) {
  603. if (that.options.reconnectPeriod > 0) {
  604. var topic = { qos: sub.qos }
  605. if (version === 5) {
  606. topic.nl = sub.nl || false
  607. topic.rap = sub.rap || false
  608. topic.rh = sub.rh || 0
  609. topic.properties = sub.properties
  610. }
  611. that._resubscribeTopics[sub.topic] = topic
  612. topics.push(sub.topic)
  613. }
  614. })
  615. that.messageIdToTopic[packet.messageId] = topics
  616. }
  617. this.outgoing[packet.messageId] = {
  618. volatile: true,
  619. cb: function (err, packet) {
  620. if (!err) {
  621. var granted = packet.granted
  622. for (var i = 0; i < granted.length; i += 1) {
  623. subs[i].qos = granted[i]
  624. }
  625. }
  626. callback(err, subs)
  627. }
  628. }
  629. debug('subscribe :: call _sendPacket')
  630. this._sendPacket(packet)
  631. return this
  632. }
  633. /**
  634. * unsubscribe - unsubscribe from topic(s)
  635. *
  636. * @param {String, Array} topic - topics to unsubscribe from
  637. * @param {Object} [opts] - optional subscription options, includes:
  638. * {Object} properties - properties of unsubscribe packet
  639. * @param {Function} [callback] - callback fired on unsuback
  640. * @returns {MqttClient} this - for chaining
  641. * @api public
  642. * @example client.unsubscribe('topic');
  643. * @example client.unsubscribe('topic', console.log);
  644. */
  645. MqttClient.prototype.unsubscribe = function () {
  646. var packet = {
  647. cmd: 'unsubscribe',
  648. qos: 1,
  649. messageId: this._nextId()
  650. }
  651. var that = this
  652. var args = new Array(arguments.length)
  653. for (var i = 0; i < arguments.length; i++) {
  654. args[i] = arguments[i]
  655. }
  656. var topic = args.shift()
  657. var callback = args.pop() || nop
  658. var opts = args.pop()
  659. if (typeof topic === 'string') {
  660. topic = [topic]
  661. }
  662. if (typeof callback !== 'function') {
  663. opts = callback
  664. callback = nop
  665. }
  666. if (this._checkDisconnecting(callback)) {
  667. return this
  668. }
  669. if (typeof topic === 'string') {
  670. packet.unsubscriptions = [topic]
  671. } else if (Array.isArray(topic)) {
  672. packet.unsubscriptions = topic
  673. }
  674. if (this.options.resubscribe) {
  675. packet.unsubscriptions.forEach(function (topic) {
  676. delete that._resubscribeTopics[topic]
  677. })
  678. }
  679. if (typeof opts === 'object' && opts.properties) {
  680. packet.properties = opts.properties
  681. }
  682. this.outgoing[packet.messageId] = {
  683. volatile: true,
  684. cb: callback
  685. }
  686. debug('unsubscribe: call _sendPacket')
  687. this._sendPacket(packet)
  688. return this
  689. }
  690. /**
  691. * end - close connection
  692. *
  693. * @returns {MqttClient} this - for chaining
  694. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  695. * @param {Function} cb - called when the client has been closed
  696. *
  697. * @api public
  698. */
  699. MqttClient.prototype.end = function (force, opts, cb) {
  700. var that = this
  701. debug('end :: (%s)', this.options.clientId)
  702. if (force == null || typeof force !== 'boolean') {
  703. cb = opts || nop
  704. opts = force
  705. force = false
  706. if (typeof opts !== 'object') {
  707. cb = opts
  708. opts = null
  709. if (typeof cb !== 'function') {
  710. cb = nop
  711. }
  712. }
  713. }
  714. if (typeof opts !== 'object') {
  715. cb = opts
  716. opts = null
  717. }
  718. debug('end :: cb? %s', !!cb)
  719. cb = cb || nop
  720. function closeStores () {
  721. debug('end :: closeStores: closing incoming and outgoing stores')
  722. that.disconnected = true
  723. that.incomingStore.close(function () {
  724. that.outgoingStore.close(function () {
  725. debug('end :: closeStores: emitting end')
  726. that.emit('end')
  727. if (cb) {
  728. debug('end :: closeStores: invoking callback with args')
  729. cb()
  730. }
  731. })
  732. })
  733. if (that._deferredReconnect) {
  734. that._deferredReconnect()
  735. }
  736. }
  737. function finish () {
  738. // defer closesStores of an I/O cycle,
  739. // just to make sure things are
  740. // ok for websockets
  741. debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
  742. that._cleanUp(force, () => {
  743. debug('end :: finish :: calling process.nextTick on closeStores')
  744. // var boundProcess = process.nextTick.bind(null, closeStores)
  745. process.nextTick(closeStores.bind(that))
  746. }, opts)
  747. }
  748. if (this.disconnecting) {
  749. cb()
  750. return this
  751. }
  752. this._clearReconnect()
  753. this.disconnecting = true
  754. if (!force && Object.keys(this.outgoing).length > 0) {
  755. // wait 10ms, just to be sure we received all of it
  756. debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
  757. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  758. } else {
  759. debug('end :: (%s) :: immediately calling finish', that.options.clientId)
  760. finish()
  761. }
  762. return this
  763. }
  764. /**
  765. * removeOutgoingMessage - remove a message in outgoing store
  766. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  767. *
  768. * @param {Number} messageId - messageId to remove message
  769. * @returns {MqttClient} this - for chaining
  770. * @api public
  771. *
  772. * @example client.removeOutgoingMessage(client.getLastMessageId());
  773. */
  774. MqttClient.prototype.removeOutgoingMessage = function (messageId) {
  775. var cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  776. delete this.outgoing[messageId]
  777. this.outgoingStore.del({messageId: messageId}, function () {
  778. cb(new Error('Message removed'))
  779. })
  780. return this
  781. }
  782. /**
  783. * reconnect - connect again using the same options as connect()
  784. *
  785. * @param {Object} [opts] - optional reconnect options, includes:
  786. * {Store} incomingStore - a store for the incoming packets
  787. * {Store} outgoingStore - a store for the outgoing packets
  788. * if opts is not given, current stores are used
  789. * @returns {MqttClient} this - for chaining
  790. *
  791. * @api public
  792. */
  793. MqttClient.prototype.reconnect = function (opts) {
  794. debug('client reconnect')
  795. var that = this
  796. var f = function () {
  797. if (opts) {
  798. that.options.incomingStore = opts.incomingStore
  799. that.options.outgoingStore = opts.outgoingStore
  800. } else {
  801. that.options.incomingStore = null
  802. that.options.outgoingStore = null
  803. }
  804. that.incomingStore = that.options.incomingStore || new Store()
  805. that.outgoingStore = that.options.outgoingStore || new Store()
  806. that.disconnecting = false
  807. that.disconnected = false
  808. that._deferredReconnect = null
  809. that._reconnect()
  810. }
  811. if (this.disconnecting && !this.disconnected) {
  812. this._deferredReconnect = f
  813. } else {
  814. f()
  815. }
  816. return this
  817. }
  818. /**
  819. * _reconnect - implement reconnection
  820. * @api privateish
  821. */
  822. MqttClient.prototype._reconnect = function () {
  823. debug('_reconnect: emitting reconnect to client')
  824. this.emit('reconnect')
  825. debug('_reconnect: calling _setupStream')
  826. this._setupStream()
  827. }
  828. /**
  829. * _setupReconnect - setup reconnect timer
  830. */
  831. MqttClient.prototype._setupReconnect = function () {
  832. var that = this
  833. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  834. if (!this.reconnecting) {
  835. debug('_setupReconnect :: emit `offline` state')
  836. this.emit('offline')
  837. debug('_setupReconnect :: set `reconnecting` to `true`')
  838. this.reconnecting = true
  839. }
  840. debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
  841. that.reconnectTimer = setInterval(function () {
  842. debug('reconnectTimer :: reconnect triggered!')
  843. that._reconnect()
  844. }, that.options.reconnectPeriod)
  845. } else {
  846. debug('_setupReconnect :: doing nothing...')
  847. }
  848. }
  849. /**
  850. * _clearReconnect - clear the reconnect timer
  851. */
  852. MqttClient.prototype._clearReconnect = function () {
  853. debug('_clearReconnect : clearing reconnect timer')
  854. if (this.reconnectTimer) {
  855. clearInterval(this.reconnectTimer)
  856. this.reconnectTimer = null
  857. }
  858. }
  859. /**
  860. * _cleanUp - clean up on connection end
  861. * @api private
  862. */
  863. MqttClient.prototype._cleanUp = function (forced, done) {
  864. var opts = arguments[2]
  865. if (done) {
  866. debug('_cleanUp :: done callback provided for on stream close')
  867. this.stream.on('close', done)
  868. }
  869. debug('_cleanUp :: forced? %s', forced)
  870. if (forced) {
  871. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  872. flush(this.outgoing)
  873. }
  874. debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
  875. this.stream.destroy()
  876. } else {
  877. var packet = xtend({ cmd: 'disconnect' }, opts)
  878. debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
  879. this._sendPacket(
  880. packet,
  881. setImmediate.bind(
  882. null,
  883. this.stream.end.bind(this.stream)
  884. )
  885. )
  886. }
  887. if (!this.disconnecting) {
  888. debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
  889. this._clearReconnect()
  890. this._setupReconnect()
  891. }
  892. if (this.pingTimer !== null) {
  893. debug('_cleanUp :: clearing pingTimer')
  894. this.pingTimer.clear()
  895. this.pingTimer = null
  896. }
  897. if (done && !this.connected) {
  898. debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
  899. this.stream.removeListener('close', done)
  900. done()
  901. }
  902. }
  903. /**
  904. * _sendPacket - send or queue a packet
  905. * @param {Object} packet - packet options
  906. * @param {Function} cb - callback when the packet is sent
  907. * @param {Function} cbStorePut - called when message is put into outgoingStore
  908. * @api private
  909. */
  910. MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
  911. debug('_sendPacket :: (%s) :: start', this.options.clientId)
  912. cbStorePut = cbStorePut || nop
  913. if (!this.connected) {
  914. debug('_sendPacket :: client not connected. Storing packet offline.')
  915. this._storePacket(packet, cb, cbStorePut)
  916. return
  917. }
  918. // When sending a packet, reschedule the ping timer
  919. this._shiftPingInterval()
  920. switch (packet.cmd) {
  921. case 'publish':
  922. break
  923. case 'pubrel':
  924. storeAndSend(this, packet, cb, cbStorePut)
  925. return
  926. default:
  927. sendPacket(this, packet, cb)
  928. return
  929. }
  930. switch (packet.qos) {
  931. case 2:
  932. case 1:
  933. storeAndSend(this, packet, cb, cbStorePut)
  934. break
  935. /**
  936. * no need of case here since it will be caught by default
  937. * and jshint comply that before default it must be a break
  938. * anyway it will result in -1 evaluation
  939. */
  940. case 0:
  941. /* falls through */
  942. default:
  943. sendPacket(this, packet, cb)
  944. break
  945. }
  946. debug('_sendPacket :: (%s) :: end', this.options.clientId)
  947. }
  948. /**
  949. * _storePacket - queue a packet
  950. * @param {Object} packet - packet options
  951. * @param {Function} cb - callback when the packet is sent
  952. * @param {Function} cbStorePut - called when message is put into outgoingStore
  953. * @api private
  954. */
  955. MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
  956. debug('_storePacket :: packet: %o', packet)
  957. debug('_storePacket :: cb? %s', !!cb)
  958. cbStorePut = cbStorePut || nop
  959. // check that the packet is not a qos of 0, or that the command is not a publish
  960. if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
  961. this.queue.push({ packet: packet, cb: cb })
  962. } else if (packet.qos > 0) {
  963. cb = this.outgoing[packet.messageId] ? this.outgoing[packet.messageId].cb : null
  964. this.outgoingStore.put(packet, function (err) {
  965. if (err) {
  966. return cb && cb(err)
  967. }
  968. cbStorePut()
  969. })
  970. } else if (cb) {
  971. cb(new Error('No connection to broker'))
  972. }
  973. }
  974. /**
  975. * _setupPingTimer - setup the ping timer
  976. *
  977. * @api private
  978. */
  979. MqttClient.prototype._setupPingTimer = function () {
  980. debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
  981. var that = this
  982. if (!this.pingTimer && this.options.keepalive) {
  983. this.pingResp = true
  984. this.pingTimer = reInterval(function () {
  985. that._checkPing()
  986. }, this.options.keepalive * 1000)
  987. }
  988. }
  989. /**
  990. * _shiftPingInterval - reschedule the ping interval
  991. *
  992. * @api private
  993. */
  994. MqttClient.prototype._shiftPingInterval = function () {
  995. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  996. this.pingTimer.reschedule(this.options.keepalive * 1000)
  997. }
  998. }
  999. /**
  1000. * _checkPing - check if a pingresp has come back, and ping the server again
  1001. *
  1002. * @api private
  1003. */
  1004. MqttClient.prototype._checkPing = function () {
  1005. debug('_checkPing :: checking ping...')
  1006. if (this.pingResp) {
  1007. debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
  1008. this.pingResp = false
  1009. this._sendPacket({ cmd: 'pingreq' })
  1010. } else {
  1011. // do a forced cleanup since socket will be in bad shape
  1012. debug('_checkPing :: calling _cleanUp with force true')
  1013. this._cleanUp(true)
  1014. }
  1015. }
  1016. /**
  1017. * _handlePingresp - handle a pingresp
  1018. *
  1019. * @api private
  1020. */
  1021. MqttClient.prototype._handlePingresp = function () {
  1022. this.pingResp = true
  1023. }
  1024. /**
  1025. * _handleConnack
  1026. *
  1027. * @param {Object} packet
  1028. * @api private
  1029. */
  1030. MqttClient.prototype._handleConnack = function (packet) {
  1031. debug('_handleConnack')
  1032. var options = this.options
  1033. var version = options.protocolVersion
  1034. var rc = version === 5 ? packet.reasonCode : packet.returnCode
  1035. clearTimeout(this.connackTimer)
  1036. if (packet.properties) {
  1037. if (packet.properties.topicAliasMaximum) {
  1038. if (!options.properties) { options.properties = {} }
  1039. options.properties.topicAliasMaximum = packet.properties.topicAliasMaximum
  1040. }
  1041. if (packet.properties.serverKeepAlive && options.keepalive) {
  1042. options.keepalive = packet.properties.serverKeepAlive
  1043. this._shiftPingInterval()
  1044. }
  1045. if (packet.properties.maximumPacketSize) {
  1046. if (!options.properties) { options.properties = {} }
  1047. options.properties.maximumPacketSize = packet.properties.maximumPacketSize
  1048. }
  1049. }
  1050. if (rc === 0) {
  1051. this.reconnecting = false
  1052. this._onConnect(packet)
  1053. } else if (rc > 0) {
  1054. var err = new Error('Connection refused: ' + errors[rc])
  1055. err.code = rc
  1056. this.emit('error', err)
  1057. }
  1058. }
  1059. /**
  1060. * _handlePublish
  1061. *
  1062. * @param {Object} packet
  1063. * @api private
  1064. */
  1065. /*
  1066. those late 2 case should be rewrite to comply with coding style:
  1067. case 1:
  1068. case 0:
  1069. // do not wait sending a puback
  1070. // no callback passed
  1071. if (1 === qos) {
  1072. this._sendPacket({
  1073. cmd: 'puback',
  1074. messageId: messageId
  1075. });
  1076. }
  1077. // emit the message event for both qos 1 and 0
  1078. this.emit('message', topic, message, packet);
  1079. this.handleMessage(packet, done);
  1080. break;
  1081. default:
  1082. // do nothing but every switch mus have a default
  1083. // log or throw an error about unknown qos
  1084. break;
  1085. for now i just suppressed the warnings
  1086. */
  1087. MqttClient.prototype._handlePublish = function (packet, done) {
  1088. debug('_handlePublish: packet %o', packet)
  1089. done = typeof done !== 'undefined' ? done : nop
  1090. var topic = packet.topic.toString()
  1091. var message = packet.payload
  1092. var qos = packet.qos
  1093. var messageId = packet.messageId
  1094. var that = this
  1095. var options = this.options
  1096. var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  1097. debug('_handlePublish: qos %d', qos)
  1098. switch (qos) {
  1099. case 2: {
  1100. options.customHandleAcks(topic, message, packet, function (error, code) {
  1101. if (!(error instanceof Error)) {
  1102. code = error
  1103. error = null
  1104. }
  1105. if (error) { return that.emit('error', error) }
  1106. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
  1107. if (code) {
  1108. that._sendPacket({cmd: 'pubrec', messageId: messageId, reasonCode: code}, done)
  1109. } else {
  1110. that.incomingStore.put(packet, function () {
  1111. that._sendPacket({cmd: 'pubrec', messageId: messageId}, done)
  1112. })
  1113. }
  1114. })
  1115. break
  1116. }
  1117. case 1: {
  1118. // emit the message event
  1119. options.customHandleAcks(topic, message, packet, function (error, code) {
  1120. if (!(error instanceof Error)) {
  1121. code = error
  1122. error = null
  1123. }
  1124. if (error) { return that.emit('error', error) }
  1125. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
  1126. if (!code) { that.emit('message', topic, message, packet) }
  1127. that.handleMessage(packet, function (err) {
  1128. if (err) {
  1129. return done && done(err)
  1130. }
  1131. that._sendPacket({cmd: 'puback', messageId: messageId, reasonCode: code}, done)
  1132. })
  1133. })
  1134. break
  1135. }
  1136. case 0:
  1137. // emit the message event
  1138. this.emit('message', topic, message, packet)
  1139. this.handleMessage(packet, done)
  1140. break
  1141. default:
  1142. // do nothing
  1143. debug('_handlePublish: unknown QoS. Doing nothing.')
  1144. // log or throw an error about unknown qos
  1145. break
  1146. }
  1147. }
  1148. /**
  1149. * Handle messages with backpressure support, one at a time.
  1150. * Override at will.
  1151. *
  1152. * @param Packet packet the packet
  1153. * @param Function callback call when finished
  1154. * @api public
  1155. */
  1156. MqttClient.prototype.handleMessage = function (packet, callback) {
  1157. callback()
  1158. }
  1159. /**
  1160. * _handleAck
  1161. *
  1162. * @param {Object} packet
  1163. * @api private
  1164. */
  1165. MqttClient.prototype._handleAck = function (packet) {
  1166. /* eslint no-fallthrough: "off" */
  1167. var messageId = packet.messageId
  1168. var type = packet.cmd
  1169. var response = null
  1170. var cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  1171. var that = this
  1172. var err
  1173. if (!cb) {
  1174. debug('_handleAck :: Server sent an ack in error. Ignoring.')
  1175. // Server sent an ack in error, ignore it.
  1176. return
  1177. }
  1178. // Process
  1179. debug('_handleAck :: packet type', type)
  1180. switch (type) {
  1181. case 'pubcomp':
  1182. // same thing as puback for QoS 2
  1183. case 'puback':
  1184. var pubackRC = packet.reasonCode
  1185. // Callback - we're done
  1186. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1187. err = new Error('Publish error: ' + errors[pubackRC])
  1188. err.code = pubackRC
  1189. cb(err, packet)
  1190. }
  1191. delete this.outgoing[messageId]
  1192. this.outgoingStore.del(packet, cb)
  1193. break
  1194. case 'pubrec':
  1195. response = {
  1196. cmd: 'pubrel',
  1197. qos: 2,
  1198. messageId: messageId
  1199. }
  1200. var pubrecRC = packet.reasonCode
  1201. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1202. err = new Error('Publish error: ' + errors[pubrecRC])
  1203. err.code = pubrecRC
  1204. cb(err, packet)
  1205. } else {
  1206. this._sendPacket(response)
  1207. }
  1208. break
  1209. case 'suback':
  1210. delete this.outgoing[messageId]
  1211. for (var grantedI = 0; grantedI < packet.granted.length; grantedI++) {
  1212. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1213. // suback with Failure status
  1214. var topics = this.messageIdToTopic[messageId]
  1215. if (topics) {
  1216. topics.forEach(function (topic) {
  1217. delete that._resubscribeTopics[topic]
  1218. })
  1219. }
  1220. }
  1221. }
  1222. cb(null, packet)
  1223. break
  1224. case 'unsuback':
  1225. delete this.outgoing[messageId]
  1226. cb(null)
  1227. break
  1228. default:
  1229. that.emit('error', new Error('unrecognized packet type'))
  1230. }
  1231. if (this.disconnecting &&
  1232. Object.keys(this.outgoing).length === 0) {
  1233. this.emit('outgoingEmpty')
  1234. }
  1235. }
  1236. /**
  1237. * _handlePubrel
  1238. *
  1239. * @param {Object} packet
  1240. * @api private
  1241. */
  1242. MqttClient.prototype._handlePubrel = function (packet, callback) {
  1243. debug('handling pubrel packet')
  1244. callback = typeof callback !== 'undefined' ? callback : nop
  1245. var messageId = packet.messageId
  1246. var that = this
  1247. var comp = {cmd: 'pubcomp', messageId: messageId}
  1248. that.incomingStore.get(packet, function (err, pub) {
  1249. if (!err) {
  1250. that.emit('message', pub.topic, pub.payload, pub)
  1251. that.handleMessage(pub, function (err) {
  1252. if (err) {
  1253. return callback(err)
  1254. }
  1255. that.incomingStore.del(pub, nop)
  1256. that._sendPacket(comp, callback)
  1257. })
  1258. } else {
  1259. that._sendPacket(comp, callback)
  1260. }
  1261. })
  1262. }
  1263. /**
  1264. * _handleDisconnect
  1265. *
  1266. * @param {Object} packet
  1267. * @api private
  1268. */
  1269. MqttClient.prototype._handleDisconnect = function (packet) {
  1270. this.emit('disconnect', packet)
  1271. }
  1272. /**
  1273. * _nextId
  1274. * @return unsigned int
  1275. */
  1276. MqttClient.prototype._nextId = function () {
  1277. // id becomes current state of this.nextId and increments afterwards
  1278. var id = this.nextId++
  1279. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  1280. if (this.nextId === 65536) {
  1281. this.nextId = 1
  1282. }
  1283. return id
  1284. }
  1285. /**
  1286. * getLastMessageId
  1287. * @return unsigned int
  1288. */
  1289. MqttClient.prototype.getLastMessageId = function () {
  1290. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  1291. }
  1292. /**
  1293. * _resubscribe
  1294. * @api private
  1295. */
  1296. MqttClient.prototype._resubscribe = function (connack) {
  1297. debug('_resubscribe')
  1298. var _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
  1299. if (!this._firstConnection &&
  1300. (this.options.clean || (this.options.protocolVersion === 5 && !connack.sessionPresent)) &&
  1301. _resubscribeTopicsKeys.length > 0) {
  1302. if (this.options.resubscribe) {
  1303. if (this.options.protocolVersion === 5) {
  1304. debug('_resubscribe: protocolVersion 5')
  1305. for (var topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
  1306. var resubscribeTopic = {}
  1307. resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
  1308. resubscribeTopic.resubscribe = true
  1309. this.subscribe(resubscribeTopic, {properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})
  1310. }
  1311. } else {
  1312. this._resubscribeTopics.resubscribe = true
  1313. this.subscribe(this._resubscribeTopics)
  1314. }
  1315. } else {
  1316. this._resubscribeTopics = {}
  1317. }
  1318. }
  1319. this._firstConnection = false
  1320. }
  1321. /**
  1322. * _onConnect
  1323. *
  1324. * @api private
  1325. */
  1326. MqttClient.prototype._onConnect = function (packet) {
  1327. if (this.disconnected) {
  1328. this.emit('connect', packet)
  1329. return
  1330. }
  1331. var that = this
  1332. this._setupPingTimer()
  1333. this._resubscribe(packet)
  1334. this.connected = true
  1335. function startStreamProcess () {
  1336. var outStore = that.outgoingStore.createStream()
  1337. function clearStoreProcessing () {
  1338. that._storeProcessing = false
  1339. that._packetIdsDuringStoreProcessing = {}
  1340. }
  1341. that.once('close', remove)
  1342. outStore.on('error', function (err) {
  1343. clearStoreProcessing()
  1344. that.removeListener('close', remove)
  1345. that.emit('error', err)
  1346. })
  1347. function remove () {
  1348. outStore.destroy()
  1349. outStore = null
  1350. clearStoreProcessing()
  1351. }
  1352. function storeDeliver () {
  1353. // edge case, we wrapped this twice
  1354. if (!outStore) {
  1355. return
  1356. }
  1357. that._storeProcessing = true
  1358. var packet = outStore.read(1)
  1359. var cb
  1360. if (!packet) {
  1361. // read when data is available in the future
  1362. outStore.once('readable', storeDeliver)
  1363. return
  1364. }
  1365. // Skip already processed store packets
  1366. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1367. storeDeliver()
  1368. return
  1369. }
  1370. // Avoid unnecessary stream read operations when disconnected
  1371. if (!that.disconnecting && !that.reconnectTimer) {
  1372. cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
  1373. that.outgoing[packet.messageId] = {
  1374. volatile: false,
  1375. cb: function (err, status) {
  1376. // Ensure that the original callback passed in to publish gets invoked
  1377. if (cb) {
  1378. cb(err, status)
  1379. }
  1380. storeDeliver()
  1381. }
  1382. }
  1383. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1384. that._sendPacket(packet)
  1385. } else if (outStore.destroy) {
  1386. outStore.destroy()
  1387. }
  1388. }
  1389. outStore.on('end', function () {
  1390. var allProcessed = true
  1391. for (var id in that._packetIdsDuringStoreProcessing) {
  1392. if (!that._packetIdsDuringStoreProcessing[id]) {
  1393. allProcessed = false
  1394. break
  1395. }
  1396. }
  1397. if (allProcessed) {
  1398. clearStoreProcessing()
  1399. that.removeListener('close', remove)
  1400. that.emit('connect', packet)
  1401. } else {
  1402. startStreamProcess()
  1403. }
  1404. })
  1405. storeDeliver()
  1406. }
  1407. // start flowing
  1408. startStreamProcess()
  1409. }
  1410. module.exports = MqttClient
  1411. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1412. },{"./store":7,"./validations":8,"_process":100,"debug":17,"events":83,"inherits":88,"mqtt-packet":92,"readable-stream":116,"reinterval":117,"xtend":140}],2:[function(require,module,exports){
  1413. (function (Buffer){
  1414. 'use strict'
  1415. var Transform = require('readable-stream').Transform
  1416. var duplexify = require('duplexify')
  1417. var base64 = require('base64-js')
  1418. /* global FileReader */
  1419. var my
  1420. var proxy
  1421. var stream
  1422. var isInitialized = false
  1423. function buildProxy () {
  1424. var proxy = new Transform()
  1425. proxy._write = function (chunk, encoding, next) {
  1426. my.sendSocketMessage({
  1427. data: chunk.buffer,
  1428. success: function () {
  1429. next()
  1430. },
  1431. fail: function () {
  1432. next(new Error())
  1433. }
  1434. })
  1435. }
  1436. proxy._flush = function socketEnd (done) {
  1437. my.closeSocket({
  1438. success: function () {
  1439. done()
  1440. }
  1441. })
  1442. }
  1443. return proxy
  1444. }
  1445. function setDefaultOpts (opts) {
  1446. if (!opts.hostname) {
  1447. opts.hostname = 'localhost'
  1448. }
  1449. if (!opts.path) {
  1450. opts.path = '/'
  1451. }
  1452. if (!opts.wsOptions) {
  1453. opts.wsOptions = {}
  1454. }
  1455. }
  1456. function buildUrl (opts, client) {
  1457. var protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1458. var url = protocol + '://' + opts.hostname + opts.path
  1459. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1460. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1461. }
  1462. if (typeof (opts.transformWsUrl) === 'function') {
  1463. url = opts.transformWsUrl(url, opts, client)
  1464. }
  1465. return url
  1466. }
  1467. function bindEventHandler () {
  1468. if (isInitialized) return
  1469. isInitialized = true
  1470. my.onSocketOpen(function () {
  1471. stream.setReadable(proxy)
  1472. stream.setWritable(proxy)
  1473. stream.emit('connect')
  1474. })
  1475. my.onSocketMessage(function (res) {
  1476. if (typeof res.data === 'string') {
  1477. var array = base64.toByteArray(res.data)
  1478. var buffer = Buffer.from(array)
  1479. proxy.push(buffer)
  1480. } else {
  1481. var reader = new FileReader()
  1482. reader.addEventListener('load', function () {
  1483. var data = reader.result
  1484. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1485. else data = Buffer.from(data, 'utf8')
  1486. proxy.push(data)
  1487. })
  1488. reader.readAsArrayBuffer(res.data)
  1489. }
  1490. })
  1491. my.onSocketClose(function () {
  1492. stream.end()
  1493. stream.destroy()
  1494. })
  1495. my.onSocketError(function (res) {
  1496. stream.destroy(res)
  1497. })
  1498. }
  1499. function buildStream (client, opts) {
  1500. opts.hostname = opts.hostname || opts.host
  1501. if (!opts.hostname) {
  1502. throw new Error('Could not determine host. Specify host manually.')
  1503. }
  1504. var websocketSubProtocol =
  1505. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1506. ? 'mqttv3.1'
  1507. : 'mqtt'
  1508. setDefaultOpts(opts)
  1509. var url = buildUrl(opts, client)
  1510. my = opts.my
  1511. my.connectSocket({
  1512. url: url,
  1513. protocols: websocketSubProtocol
  1514. })
  1515. proxy = buildProxy()
  1516. stream = duplexify.obj()
  1517. bindEventHandler()
  1518. return stream
  1519. }
  1520. module.exports = buildStream
  1521. }).call(this,require("buffer").Buffer)
  1522. },{"base64-js":10,"buffer":12,"duplexify":19,"readable-stream":116}],3:[function(require,module,exports){
  1523. 'use strict'
  1524. var net = require('net')
  1525. var debug = require('debug')('mqttjs:tcp')
  1526. /*
  1527. variables port and host can be removed since
  1528. you have all required information in opts object
  1529. */
  1530. function streamBuilder (client, opts) {
  1531. var port, host
  1532. opts.port = opts.port || 1883
  1533. opts.hostname = opts.hostname || opts.host || 'localhost'
  1534. port = opts.port
  1535. host = opts.hostname
  1536. debug('port %d and host %s', port, host)
  1537. return net.createConnection(port, host)
  1538. }
  1539. module.exports = streamBuilder
  1540. },{"debug":17,"net":11}],4:[function(require,module,exports){
  1541. 'use strict'
  1542. var tls = require('tls')
  1543. var debug = require('debug')('mqttjs:tls')
  1544. function buildBuilder (mqttClient, opts) {
  1545. var connection
  1546. opts.port = opts.port || 8883
  1547. opts.host = opts.hostname || opts.host || 'localhost'
  1548. opts.servername = opts.host
  1549. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1550. delete opts.path
  1551. debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)
  1552. connection = tls.connect(opts)
  1553. /* eslint no-use-before-define: [2, "nofunc"] */
  1554. connection.on('secureConnect', function () {
  1555. if (opts.rejectUnauthorized && !connection.authorized) {
  1556. connection.emit('error', new Error('TLS not authorized'))
  1557. } else {
  1558. connection.removeListener('error', handleTLSerrors)
  1559. }
  1560. })
  1561. function handleTLSerrors (err) {
  1562. // How can I get verify this error is a tls error?
  1563. if (opts.rejectUnauthorized) {
  1564. mqttClient.emit('error', err)
  1565. }
  1566. // close this connection to match the behaviour of net
  1567. // otherwise all we get is an error from the connection
  1568. // and close event doesn't fire. This is a work around
  1569. // to enable the reconnect code to work the same as with
  1570. // net.createConnection
  1571. connection.end()
  1572. }
  1573. connection.on('error', handleTLSerrors)
  1574. return connection
  1575. }
  1576. module.exports = buildBuilder
  1577. },{"debug":17,"tls":11}],5:[function(require,module,exports){
  1578. (function (process){
  1579. 'use strict'
  1580. var debug = require('debug')('mqttjs:ws')
  1581. var websocket = require('websocket-stream')
  1582. var urlModule = require('url')
  1583. var WSS_OPTIONS = [
  1584. 'rejectUnauthorized',
  1585. 'ca',
  1586. 'cert',
  1587. 'key',
  1588. 'pfx',
  1589. 'passphrase'
  1590. ]
  1591. var IS_BROWSER = process.title === 'browser'
  1592. function buildUrl (opts, client) {
  1593. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1594. if (typeof (opts.transformWsUrl) === 'function') {
  1595. url = opts.transformWsUrl(url, opts, client)
  1596. }
  1597. return url
  1598. }
  1599. function setDefaultOpts (opts) {
  1600. if (!opts.hostname) {
  1601. opts.hostname = 'localhost'
  1602. }
  1603. if (!opts.port) {
  1604. if (opts.protocol === 'wss') {
  1605. opts.port = 443
  1606. } else {
  1607. opts.port = 80
  1608. }
  1609. }
  1610. if (!opts.path) {
  1611. opts.path = '/'
  1612. }
  1613. if (!opts.wsOptions) {
  1614. opts.wsOptions = {}
  1615. }
  1616. if (!IS_BROWSER && opts.protocol === 'wss') {
  1617. // Add cert/key/ca etc options
  1618. WSS_OPTIONS.forEach(function (prop) {
  1619. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  1620. opts.wsOptions[prop] = opts[prop]
  1621. }
  1622. })
  1623. }
  1624. }
  1625. function createWebSocket (client, opts) {
  1626. debug('createWebSocket')
  1627. var websocketSubProtocol =
  1628. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1629. ? 'mqttv3.1'
  1630. : 'mqtt'
  1631. setDefaultOpts(opts)
  1632. var url = buildUrl(opts, client)
  1633. debug('url %s protocol %s', url, websocketSubProtocol)
  1634. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1635. }
  1636. function streamBuilder (client, opts) {
  1637. return createWebSocket(client, opts)
  1638. }
  1639. function browserStreamBuilder (client, opts) {
  1640. debug('browserStreamBuilder')
  1641. if (!opts.hostname) {
  1642. opts.hostname = opts.host
  1643. }
  1644. if (!opts.hostname) {
  1645. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1646. // can not determine the `hostname` automatically. If connecting to
  1647. // localhost, please supply the `hostname` as an argument.
  1648. if (typeof (document) === 'undefined') {
  1649. throw new Error('Could not determine host. Specify host manually.')
  1650. }
  1651. var parsed = urlModule.parse(document.URL)
  1652. opts.hostname = parsed.hostname
  1653. if (!opts.port) {
  1654. opts.port = parsed.port
  1655. }
  1656. }
  1657. return createWebSocket(client, opts)
  1658. }
  1659. if (IS_BROWSER) {
  1660. module.exports = browserStreamBuilder
  1661. } else {
  1662. module.exports = streamBuilder
  1663. }
  1664. }).call(this,require('_process'))
  1665. },{"_process":100,"debug":17,"url":132,"websocket-stream":137}],6:[function(require,module,exports){
  1666. (function (process,Buffer){
  1667. 'use strict'
  1668. var Transform = require('readable-stream').Transform
  1669. var duplexify = require('duplexify')
  1670. /* global wx */
  1671. var socketTask
  1672. var proxy
  1673. var stream
  1674. function buildProxy () {
  1675. var proxy = new Transform()
  1676. proxy._write = function (chunk, encoding, next) {
  1677. socketTask.send({
  1678. data: chunk.buffer,
  1679. success: function () {
  1680. next()
  1681. },
  1682. fail: function (errMsg) {
  1683. next(new Error(errMsg))
  1684. }
  1685. })
  1686. }
  1687. proxy._flush = function socketEnd (done) {
  1688. socketTask.close({
  1689. success: function () {
  1690. done()
  1691. }
  1692. })
  1693. }
  1694. return proxy
  1695. }
  1696. function setDefaultOpts (opts) {
  1697. if (!opts.hostname) {
  1698. opts.hostname = 'localhost'
  1699. }
  1700. if (!opts.path) {
  1701. opts.path = '/'
  1702. }
  1703. if (!opts.wsOptions) {
  1704. opts.wsOptions = {}
  1705. }
  1706. }
  1707. function buildUrl (opts, client) {
  1708. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1709. var url = protocol + '://' + opts.hostname + opts.path
  1710. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1711. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1712. }
  1713. if (typeof (opts.transformWsUrl) === 'function') {
  1714. url = opts.transformWsUrl(url, opts, client)
  1715. }
  1716. return url
  1717. }
  1718. function bindEventHandler () {
  1719. socketTask.onOpen(function () {
  1720. stream.setReadable(proxy)
  1721. stream.setWritable(proxy)
  1722. stream.emit('connect')
  1723. })
  1724. socketTask.onMessage(function (res) {
  1725. var data = res.data
  1726. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1727. else data = Buffer.from(data, 'utf8')
  1728. proxy.push(data)
  1729. })
  1730. socketTask.onClose(function () {
  1731. stream.end()
  1732. stream.destroy()
  1733. stream.emit('close')
  1734. })
  1735. socketTask.onError(function (res) {
  1736. stream.destroy(new Error(res.errMsg))
  1737. })
  1738. }
  1739. function buildStream (client, opts) {
  1740. opts.hostname = opts.hostname || opts.host
  1741. if (!opts.hostname) {
  1742. throw new Error('Could not determine host. Specify host manually.')
  1743. }
  1744. var websocketSubProtocol =
  1745. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1746. ? 'mqttv3.1'
  1747. : 'mqtt'
  1748. setDefaultOpts(opts)
  1749. var url = buildUrl(opts, client)
  1750. socketTask = wx.connectSocket({
  1751. url: url,
  1752. protocols: [websocketSubProtocol]
  1753. })
  1754. proxy = buildProxy()
  1755. stream = duplexify.obj()
  1756. stream._destroy = function (err, cb) {
  1757. socketTask.close({
  1758. success: function () {
  1759. cb && cb(err)
  1760. }
  1761. })
  1762. }
  1763. var destroyRef = stream.destroy
  1764. stream.destroy = function () {
  1765. stream.destroy = destroyRef
  1766. var self = this
  1767. process.nextTick(function () {
  1768. socketTask.close({
  1769. fail: function () {
  1770. self._destroy(new Error())
  1771. }
  1772. })
  1773. })
  1774. }.bind(stream)
  1775. bindEventHandler()
  1776. return stream
  1777. }
  1778. module.exports = buildStream
  1779. }).call(this,require('_process'),require("buffer").Buffer)
  1780. },{"_process":100,"buffer":12,"duplexify":19,"readable-stream":116}],7:[function(require,module,exports){
  1781. (function (process){
  1782. 'use strict'
  1783. /**
  1784. * Module dependencies
  1785. */
  1786. var xtend = require('xtend')
  1787. var Readable = require('readable-stream').Readable
  1788. var streamsOpts = { objectMode: true }
  1789. var defaultStoreOptions = {
  1790. clean: true
  1791. }
  1792. /**
  1793. * es6-map can preserve insertion order even if ES version is older.
  1794. *
  1795. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
  1796. * It should be noted that a Map which is a map of an object, especially
  1797. * a dictionary of dictionaries, will only map to the object's insertion
  1798. * order. In ES2015 this is ordered for objects but for older versions of
  1799. * ES, this may be random and not ordered.
  1800. *
  1801. */
  1802. var Map = require('es6-map')
  1803. /**
  1804. * In-memory implementation of the message store
  1805. * This can actually be saved into files.
  1806. *
  1807. * @param {Object} [options] - store options
  1808. */
  1809. function Store (options) {
  1810. if (!(this instanceof Store)) {
  1811. return new Store(options)
  1812. }
  1813. this.options = options || {}
  1814. // Defaults
  1815. this.options = xtend(defaultStoreOptions, options)
  1816. this._inflights = new Map()
  1817. }
  1818. /**
  1819. * Adds a packet to the store, a packet is
  1820. * anything that has a messageId property.
  1821. *
  1822. */
  1823. Store.prototype.put = function (packet, cb) {
  1824. this._inflights.set(packet.messageId, packet)
  1825. if (cb) {
  1826. cb()
  1827. }
  1828. return this
  1829. }
  1830. /**
  1831. * Creates a stream with all the packets in the store
  1832. *
  1833. */
  1834. Store.prototype.createStream = function () {
  1835. var stream = new Readable(streamsOpts)
  1836. var destroyed = false
  1837. var values = []
  1838. var i = 0
  1839. this._inflights.forEach(function (value, key) {
  1840. values.push(value)
  1841. })
  1842. stream._read = function () {
  1843. if (!destroyed && i < values.length) {
  1844. this.push(values[i++])
  1845. } else {
  1846. this.push(null)
  1847. }
  1848. }
  1849. stream.destroy = function () {
  1850. if (destroyed) {
  1851. return
  1852. }
  1853. var self = this
  1854. destroyed = true
  1855. process.nextTick(function () {
  1856. self.emit('close')
  1857. })
  1858. }
  1859. return stream
  1860. }
  1861. /**
  1862. * deletes a packet from the store.
  1863. */
  1864. Store.prototype.del = function (packet, cb) {
  1865. packet = this._inflights.get(packet.messageId)
  1866. if (packet) {
  1867. this._inflights.delete(packet.messageId)
  1868. cb(null, packet)
  1869. } else if (cb) {
  1870. cb(new Error('missing packet'))
  1871. }
  1872. return this
  1873. }
  1874. /**
  1875. * get a packet from the store.
  1876. */
  1877. Store.prototype.get = function (packet, cb) {
  1878. packet = this._inflights.get(packet.messageId)
  1879. if (packet) {
  1880. cb(null, packet)
  1881. } else if (cb) {
  1882. cb(new Error('missing packet'))
  1883. }
  1884. return this
  1885. }
  1886. /**
  1887. * Close the store
  1888. */
  1889. Store.prototype.close = function (cb) {
  1890. if (this.options.clean) {
  1891. this._inflights = null
  1892. }
  1893. if (cb) {
  1894. cb()
  1895. }
  1896. }
  1897. module.exports = Store
  1898. }).call(this,require('_process'))
  1899. },{"_process":100,"es6-map":68,"readable-stream":116,"xtend":140}],8:[function(require,module,exports){
  1900. 'use strict'
  1901. /**
  1902. * Validate a topic to see if it's valid or not.
  1903. * A topic is valid if it follow below rules:
  1904. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1905. * - Rule #2: Part `#` must be located at the end of the mailbox
  1906. *
  1907. * @param {String} topic - A topic
  1908. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1909. */
  1910. function validateTopic (topic) {
  1911. var parts = topic.split('/')
  1912. for (var i = 0; i < parts.length; i++) {
  1913. if (parts[i] === '+') {
  1914. continue
  1915. }
  1916. if (parts[i] === '#') {
  1917. // for Rule #2
  1918. return i === parts.length - 1
  1919. }
  1920. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1921. return false
  1922. }
  1923. }
  1924. return true
  1925. }
  1926. /**
  1927. * Validate an array of topics to see if any of them is valid or not
  1928. * @param {Array} topics - Array of topics
  1929. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1930. */
  1931. function validateTopics (topics) {
  1932. if (topics.length === 0) {
  1933. return 'empty_topic_list'
  1934. }
  1935. for (var i = 0; i < topics.length; i++) {
  1936. if (!validateTopic(topics[i])) {
  1937. return topics[i]
  1938. }
  1939. }
  1940. return null
  1941. }
  1942. module.exports = {
  1943. validateTopics: validateTopics
  1944. }
  1945. },{}],9:[function(require,module,exports){
  1946. (function (process){
  1947. 'use strict'
  1948. var MqttClient = require('../client')
  1949. var Store = require('../store')
  1950. var url = require('url')
  1951. var xtend = require('xtend')
  1952. var debug = require('debug')('mqttjs')
  1953. var protocols = {}
  1954. if (process.title !== 'browser') {
  1955. protocols.mqtt = require('./tcp')
  1956. protocols.tcp = require('./tcp')
  1957. protocols.ssl = require('./tls')
  1958. protocols.tls = require('./tls')
  1959. protocols.mqtts = require('./tls')
  1960. } else {
  1961. protocols.wx = require('./wx')
  1962. protocols.wxs = require('./wx')
  1963. protocols.ali = require('./ali')
  1964. protocols.alis = require('./ali')
  1965. }
  1966. protocols.ws = require('./ws')
  1967. protocols.wss = require('./ws')
  1968. /**
  1969. * Parse the auth attribute and merge username and password in the options object.
  1970. *
  1971. * @param {Object} [opts] option object
  1972. */
  1973. function parseAuthOptions (opts) {
  1974. var matches
  1975. if (opts.auth) {
  1976. matches = opts.auth.match(/^(.+):(.+)$/)
  1977. if (matches) {
  1978. opts.username = matches[1]
  1979. opts.password = matches[2]
  1980. } else {
  1981. opts.username = opts.auth
  1982. }
  1983. }
  1984. }
  1985. /**
  1986. * connect - connect to an MQTT broker.
  1987. *
  1988. * @param {String} [brokerUrl] - url of the broker, optional
  1989. * @param {Object} opts - see MqttClient#constructor
  1990. */
  1991. function connect (brokerUrl, opts) {
  1992. debug('connecting to an MQTT broker...')
  1993. if ((typeof brokerUrl === 'object') && !opts) {
  1994. opts = brokerUrl
  1995. brokerUrl = null
  1996. }
  1997. opts = opts || {}
  1998. if (brokerUrl) {
  1999. var parsed = url.parse(brokerUrl, true)
  2000. if (parsed.port != null) {
  2001. parsed.port = Number(parsed.port)
  2002. }
  2003. opts = xtend(parsed, opts)
  2004. if (opts.protocol === null) {
  2005. throw new Error('Missing protocol')
  2006. }
  2007. opts.protocol = opts.protocol.replace(/:$/, '')
  2008. }
  2009. // merge in the auth options if supplied
  2010. parseAuthOptions(opts)
  2011. // support clientId passed in the query string of the url
  2012. if (opts.query && typeof opts.query.clientId === 'string') {
  2013. opts.clientId = opts.query.clientId
  2014. }
  2015. if (opts.cert && opts.key) {
  2016. if (opts.protocol) {
  2017. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  2018. switch (opts.protocol) {
  2019. case 'mqtt':
  2020. opts.protocol = 'mqtts'
  2021. break
  2022. case 'ws':
  2023. opts.protocol = 'wss'
  2024. break
  2025. case 'wx':
  2026. opts.protocol = 'wxs'
  2027. break
  2028. case 'ali':
  2029. opts.protocol = 'alis'
  2030. break
  2031. default:
  2032. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  2033. }
  2034. }
  2035. } else {
  2036. // A cert and key was provided, however no protocol was specified, so we will throw an error.
  2037. throw new Error('Missing secure protocol key')
  2038. }
  2039. }
  2040. if (!protocols[opts.protocol]) {
  2041. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  2042. opts.protocol = [
  2043. 'mqtt',
  2044. 'mqtts',
  2045. 'ws',
  2046. 'wss',
  2047. 'wx',
  2048. 'wxs',
  2049. 'ali',
  2050. 'alis'
  2051. ].filter(function (key, index) {
  2052. if (isSecure && index % 2 === 0) {
  2053. // Skip insecure protocols when requesting a secure one.
  2054. return false
  2055. }
  2056. return (typeof protocols[key] === 'function')
  2057. })[0]
  2058. }
  2059. if (opts.clean === false && !opts.clientId) {
  2060. throw new Error('Missing clientId for unclean clients')
  2061. }
  2062. if (opts.protocol) {
  2063. opts.defaultProtocol = opts.protocol
  2064. }
  2065. function wrapper (client) {
  2066. if (opts.servers) {
  2067. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  2068. client._reconnectCount = 0
  2069. }
  2070. opts.host = opts.servers[client._reconnectCount].host
  2071. opts.port = opts.servers[client._reconnectCount].port
  2072. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  2073. opts.hostname = opts.host
  2074. client._reconnectCount++
  2075. }
  2076. debug('calling streambuilder for', opts.protocol)
  2077. return protocols[opts.protocol](client, opts)
  2078. }
  2079. var client = new MqttClient(wrapper, opts)
  2080. client.on('error', function () { /* Automatically set up client error handling */ })
  2081. return client
  2082. }
  2083. module.exports = connect
  2084. module.exports.connect = connect
  2085. module.exports.MqttClient = MqttClient
  2086. module.exports.Store = Store
  2087. }).call(this,require('_process'))
  2088. },{"../client":1,"../store":7,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,"_process":100,"debug":17,"url":132,"xtend":140}],10:[function(require,module,exports){
  2089. 'use strict'
  2090. exports.byteLength = byteLength
  2091. exports.toByteArray = toByteArray
  2092. exports.fromByteArray = fromByteArray
  2093. var lookup = []
  2094. var revLookup = []
  2095. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2096. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2097. for (var i = 0, len = code.length; i < len; ++i) {
  2098. lookup[i] = code[i]
  2099. revLookup[code.charCodeAt(i)] = i
  2100. }
  2101. // Support decoding URL-safe base64 strings, as Node.js does.
  2102. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2103. revLookup['-'.charCodeAt(0)] = 62
  2104. revLookup['_'.charCodeAt(0)] = 63
  2105. function getLens (b64) {
  2106. var len = b64.length
  2107. if (len % 4 > 0) {
  2108. throw new Error('Invalid string. Length must be a multiple of 4')
  2109. }
  2110. // Trim off extra bytes after placeholder bytes are found
  2111. // See: https://github.com/beatgammit/base64-js/issues/42
  2112. var validLen = b64.indexOf('=')
  2113. if (validLen === -1) validLen = len
  2114. var placeHoldersLen = validLen === len
  2115. ? 0
  2116. : 4 - (validLen % 4)
  2117. return [validLen, placeHoldersLen]
  2118. }
  2119. // base64 is 4/3 + up to two characters of the original data
  2120. function byteLength (b64) {
  2121. var lens = getLens(b64)
  2122. var validLen = lens[0]
  2123. var placeHoldersLen = lens[1]
  2124. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2125. }
  2126. function _byteLength (b64, validLen, placeHoldersLen) {
  2127. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2128. }
  2129. function toByteArray (b64) {
  2130. var tmp
  2131. var lens = getLens(b64)
  2132. var validLen = lens[0]
  2133. var placeHoldersLen = lens[1]
  2134. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2135. var curByte = 0
  2136. // if there are placeholders, only get up to the last complete 4 chars
  2137. var len = placeHoldersLen > 0
  2138. ? validLen - 4
  2139. : validLen
  2140. for (var i = 0; i < len; i += 4) {
  2141. tmp =
  2142. (revLookup[b64.charCodeAt(i)] << 18) |
  2143. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2144. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2145. revLookup[b64.charCodeAt(i + 3)]
  2146. arr[curByte++] = (tmp >> 16) & 0xFF
  2147. arr[curByte++] = (tmp >> 8) & 0xFF
  2148. arr[curByte++] = tmp & 0xFF
  2149. }
  2150. if (placeHoldersLen === 2) {
  2151. tmp =
  2152. (revLookup[b64.charCodeAt(i)] << 2) |
  2153. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2154. arr[curByte++] = tmp & 0xFF
  2155. }
  2156. if (placeHoldersLen === 1) {
  2157. tmp =
  2158. (revLookup[b64.charCodeAt(i)] << 10) |
  2159. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2160. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2161. arr[curByte++] = (tmp >> 8) & 0xFF
  2162. arr[curByte++] = tmp & 0xFF
  2163. }
  2164. return arr
  2165. }
  2166. function tripletToBase64 (num) {
  2167. return lookup[num >> 18 & 0x3F] +
  2168. lookup[num >> 12 & 0x3F] +
  2169. lookup[num >> 6 & 0x3F] +
  2170. lookup[num & 0x3F]
  2171. }
  2172. function encodeChunk (uint8, start, end) {
  2173. var tmp
  2174. var output = []
  2175. for (var i = start; i < end; i += 3) {
  2176. tmp =
  2177. ((uint8[i] << 16) & 0xFF0000) +
  2178. ((uint8[i + 1] << 8) & 0xFF00) +
  2179. (uint8[i + 2] & 0xFF)
  2180. output.push(tripletToBase64(tmp))
  2181. }
  2182. return output.join('')
  2183. }
  2184. function fromByteArray (uint8) {
  2185. var tmp
  2186. var len = uint8.length
  2187. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2188. var parts = []
  2189. var maxChunkLength = 16383 // must be multiple of 3
  2190. // go through the array every three bytes, we'll deal with trailing stuff later
  2191. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2192. parts.push(encodeChunk(
  2193. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2194. ))
  2195. }
  2196. // pad the end with zeros, but make sure to not forget the extra bytes
  2197. if (extraBytes === 1) {
  2198. tmp = uint8[len - 1]
  2199. parts.push(
  2200. lookup[tmp >> 2] +
  2201. lookup[(tmp << 4) & 0x3F] +
  2202. '=='
  2203. )
  2204. } else if (extraBytes === 2) {
  2205. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2206. parts.push(
  2207. lookup[tmp >> 10] +
  2208. lookup[(tmp >> 4) & 0x3F] +
  2209. lookup[(tmp << 2) & 0x3F] +
  2210. '='
  2211. )
  2212. }
  2213. return parts.join('')
  2214. }
  2215. },{}],11:[function(require,module,exports){
  2216. },{}],12:[function(require,module,exports){
  2217. (function (Buffer){
  2218. /*!
  2219. * The buffer module from node.js, for the browser.
  2220. *
  2221. * @author Feross Aboukhadijeh <https://feross.org>
  2222. * @license MIT
  2223. */
  2224. /* eslint-disable no-proto */
  2225. 'use strict'
  2226. var base64 = require('base64-js')
  2227. var ieee754 = require('ieee754')
  2228. exports.Buffer = Buffer
  2229. exports.SlowBuffer = SlowBuffer
  2230. exports.INSPECT_MAX_BYTES = 50
  2231. var K_MAX_LENGTH = 0x7fffffff
  2232. exports.kMaxLength = K_MAX_LENGTH
  2233. /**
  2234. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2235. * === true Use Uint8Array implementation (fastest)
  2236. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2237. * implementation (most compatible, even IE6)
  2238. *
  2239. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2240. * Opera 11.6+, iOS 4.2+.
  2241. *
  2242. * We report that the browser does not support typed arrays if the are not subclassable
  2243. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2244. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2245. * for __proto__ and has a buggy typed array implementation.
  2246. */
  2247. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2248. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2249. typeof console.error === 'function') {
  2250. console.error(
  2251. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2252. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2253. )
  2254. }
  2255. function typedArraySupport () {
  2256. // Can typed array instances can be augmented?
  2257. try {
  2258. var arr = new Uint8Array(1)
  2259. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2260. return arr.foo() === 42
  2261. } catch (e) {
  2262. return false
  2263. }
  2264. }
  2265. Object.defineProperty(Buffer.prototype, 'parent', {
  2266. enumerable: true,
  2267. get: function () {
  2268. if (!Buffer.isBuffer(this)) return undefined
  2269. return this.buffer
  2270. }
  2271. })
  2272. Object.defineProperty(Buffer.prototype, 'offset', {
  2273. enumerable: true,
  2274. get: function () {
  2275. if (!Buffer.isBuffer(this)) return undefined
  2276. return this.byteOffset
  2277. }
  2278. })
  2279. function createBuffer (length) {
  2280. if (length > K_MAX_LENGTH) {
  2281. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2282. }
  2283. // Return an augmented `Uint8Array` instance
  2284. var buf = new Uint8Array(length)
  2285. buf.__proto__ = Buffer.prototype
  2286. return buf
  2287. }
  2288. /**
  2289. * The Buffer constructor returns instances of `Uint8Array` that have their
  2290. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2291. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2292. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2293. * returns a single octet.
  2294. *
  2295. * The `Uint8Array` prototype remains unmodified.
  2296. */
  2297. function Buffer (arg, encodingOrOffset, length) {
  2298. // Common case.
  2299. if (typeof arg === 'number') {
  2300. if (typeof encodingOrOffset === 'string') {
  2301. throw new TypeError(
  2302. 'The "string" argument must be of type string. Received type number'
  2303. )
  2304. }
  2305. return allocUnsafe(arg)
  2306. }
  2307. return from(arg, encodingOrOffset, length)
  2308. }
  2309. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2310. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2311. Buffer[Symbol.species] === Buffer) {
  2312. Object.defineProperty(Buffer, Symbol.species, {
  2313. value: null,
  2314. configurable: true,
  2315. enumerable: false,
  2316. writable: false
  2317. })
  2318. }
  2319. Buffer.poolSize = 8192 // not used by this implementation
  2320. function from (value, encodingOrOffset, length) {
  2321. if (typeof value === 'string') {
  2322. return fromString(value, encodingOrOffset)
  2323. }
  2324. if (ArrayBuffer.isView(value)) {
  2325. return fromArrayLike(value)
  2326. }
  2327. if (value == null) {
  2328. throw TypeError(
  2329. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2330. 'or Array-like Object. Received type ' + (typeof value)
  2331. )
  2332. }
  2333. if (isInstance(value, ArrayBuffer) ||
  2334. (value && isInstance(value.buffer, ArrayBuffer))) {
  2335. return fromArrayBuffer(value, encodingOrOffset, length)
  2336. }
  2337. if (typeof value === 'number') {
  2338. throw new TypeError(
  2339. 'The "value" argument must not be of type number. Received type number'
  2340. )
  2341. }
  2342. var valueOf = value.valueOf && value.valueOf()
  2343. if (valueOf != null && valueOf !== value) {
  2344. return Buffer.from(valueOf, encodingOrOffset, length)
  2345. }
  2346. var b = fromObject(value)
  2347. if (b) return b
  2348. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2349. typeof value[Symbol.toPrimitive] === 'function') {
  2350. return Buffer.from(
  2351. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2352. )
  2353. }
  2354. throw new TypeError(
  2355. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2356. 'or Array-like Object. Received type ' + (typeof value)
  2357. )
  2358. }
  2359. /**
  2360. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2361. * if value is a number.
  2362. * Buffer.from(str[, encoding])
  2363. * Buffer.from(array)
  2364. * Buffer.from(buffer)
  2365. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2366. **/
  2367. Buffer.from = function (value, encodingOrOffset, length) {
  2368. return from(value, encodingOrOffset, length)
  2369. }
  2370. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2371. // https://github.com/feross/buffer/pull/148
  2372. Buffer.prototype.__proto__ = Uint8Array.prototype
  2373. Buffer.__proto__ = Uint8Array
  2374. function assertSize (size) {
  2375. if (typeof size !== 'number') {
  2376. throw new TypeError('"size" argument must be of type number')
  2377. } else if (size < 0) {
  2378. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2379. }
  2380. }
  2381. function alloc (size, fill, encoding) {
  2382. assertSize(size)
  2383. if (size <= 0) {
  2384. return createBuffer(size)
  2385. }
  2386. if (fill !== undefined) {
  2387. // Only pay attention to encoding if it's a string. This
  2388. // prevents accidentally sending in a number that would
  2389. // be interpretted as a start offset.
  2390. return typeof encoding === 'string'
  2391. ? createBuffer(size).fill(fill, encoding)
  2392. : createBuffer(size).fill(fill)
  2393. }
  2394. return createBuffer(size)
  2395. }
  2396. /**
  2397. * Creates a new filled Buffer instance.
  2398. * alloc(size[, fill[, encoding]])
  2399. **/
  2400. Buffer.alloc = function (size, fill, encoding) {
  2401. return alloc(size, fill, encoding)
  2402. }
  2403. function allocUnsafe (size) {
  2404. assertSize(size)
  2405. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2406. }
  2407. /**
  2408. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2409. * */
  2410. Buffer.allocUnsafe = function (size) {
  2411. return allocUnsafe(size)
  2412. }
  2413. /**
  2414. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2415. */
  2416. Buffer.allocUnsafeSlow = function (size) {
  2417. return allocUnsafe(size)
  2418. }
  2419. function fromString (string, encoding) {
  2420. if (typeof encoding !== 'string' || encoding === '') {
  2421. encoding = 'utf8'
  2422. }
  2423. if (!Buffer.isEncoding(encoding)) {
  2424. throw new TypeError('Unknown encoding: ' + encoding)
  2425. }
  2426. var length = byteLength(string, encoding) | 0
  2427. var buf = createBuffer(length)
  2428. var actual = buf.write(string, encoding)
  2429. if (actual !== length) {
  2430. // Writing a hex string, for example, that contains invalid characters will
  2431. // cause everything after the first invalid character to be ignored. (e.g.
  2432. // 'abxxcd' will be treated as 'ab')
  2433. buf = buf.slice(0, actual)
  2434. }
  2435. return buf
  2436. }
  2437. function fromArrayLike (array) {
  2438. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2439. var buf = createBuffer(length)
  2440. for (var i = 0; i < length; i += 1) {
  2441. buf[i] = array[i] & 255
  2442. }
  2443. return buf
  2444. }
  2445. function fromArrayBuffer (array, byteOffset, length) {
  2446. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2447. throw new RangeError('"offset" is outside of buffer bounds')
  2448. }
  2449. if (array.byteLength < byteOffset + (length || 0)) {
  2450. throw new RangeError('"length" is outside of buffer bounds')
  2451. }
  2452. var buf
  2453. if (byteOffset === undefined && length === undefined) {
  2454. buf = new Uint8Array(array)
  2455. } else if (length === undefined) {
  2456. buf = new Uint8Array(array, byteOffset)
  2457. } else {
  2458. buf = new Uint8Array(array, byteOffset, length)
  2459. }
  2460. // Return an augmented `Uint8Array` instance
  2461. buf.__proto__ = Buffer.prototype
  2462. return buf
  2463. }
  2464. function fromObject (obj) {
  2465. if (Buffer.isBuffer(obj)) {
  2466. var len = checked(obj.length) | 0
  2467. var buf = createBuffer(len)
  2468. if (buf.length === 0) {
  2469. return buf
  2470. }
  2471. obj.copy(buf, 0, 0, len)
  2472. return buf
  2473. }
  2474. if (obj.length !== undefined) {
  2475. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2476. return createBuffer(0)
  2477. }
  2478. return fromArrayLike(obj)
  2479. }
  2480. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2481. return fromArrayLike(obj.data)
  2482. }
  2483. }
  2484. function checked (length) {
  2485. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2486. // length is NaN (which is otherwise coerced to zero.)
  2487. if (length >= K_MAX_LENGTH) {
  2488. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2489. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2490. }
  2491. return length | 0
  2492. }
  2493. function SlowBuffer (length) {
  2494. if (+length != length) { // eslint-disable-line eqeqeq
  2495. length = 0
  2496. }
  2497. return Buffer.alloc(+length)
  2498. }
  2499. Buffer.isBuffer = function isBuffer (b) {
  2500. return b != null && b._isBuffer === true &&
  2501. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2502. }
  2503. Buffer.compare = function compare (a, b) {
  2504. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2505. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2506. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2507. throw new TypeError(
  2508. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2509. )
  2510. }
  2511. if (a === b) return 0
  2512. var x = a.length
  2513. var y = b.length
  2514. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2515. if (a[i] !== b[i]) {
  2516. x = a[i]
  2517. y = b[i]
  2518. break
  2519. }
  2520. }
  2521. if (x < y) return -1
  2522. if (y < x) return 1
  2523. return 0
  2524. }
  2525. Buffer.isEncoding = function isEncoding (encoding) {
  2526. switch (String(encoding).toLowerCase()) {
  2527. case 'hex':
  2528. case 'utf8':
  2529. case 'utf-8':
  2530. case 'ascii':
  2531. case 'latin1':
  2532. case 'binary':
  2533. case 'base64':
  2534. case 'ucs2':
  2535. case 'ucs-2':
  2536. case 'utf16le':
  2537. case 'utf-16le':
  2538. return true
  2539. default:
  2540. return false
  2541. }
  2542. }
  2543. Buffer.concat = function concat (list, length) {
  2544. if (!Array.isArray(list)) {
  2545. throw new TypeError('"list" argument must be an Array of Buffers')
  2546. }
  2547. if (list.length === 0) {
  2548. return Buffer.alloc(0)
  2549. }
  2550. var i
  2551. if (length === undefined) {
  2552. length = 0
  2553. for (i = 0; i < list.length; ++i) {
  2554. length += list[i].length
  2555. }
  2556. }
  2557. var buffer = Buffer.allocUnsafe(length)
  2558. var pos = 0
  2559. for (i = 0; i < list.length; ++i) {
  2560. var buf = list[i]
  2561. if (isInstance(buf, Uint8Array)) {
  2562. buf = Buffer.from(buf)
  2563. }
  2564. if (!Buffer.isBuffer(buf)) {
  2565. throw new TypeError('"list" argument must be an Array of Buffers')
  2566. }
  2567. buf.copy(buffer, pos)
  2568. pos += buf.length
  2569. }
  2570. return buffer
  2571. }
  2572. function byteLength (string, encoding) {
  2573. if (Buffer.isBuffer(string)) {
  2574. return string.length
  2575. }
  2576. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2577. return string.byteLength
  2578. }
  2579. if (typeof string !== 'string') {
  2580. throw new TypeError(
  2581. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2582. 'Received type ' + typeof string
  2583. )
  2584. }
  2585. var len = string.length
  2586. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2587. if (!mustMatch && len === 0) return 0
  2588. // Use a for loop to avoid recursion
  2589. var loweredCase = false
  2590. for (;;) {
  2591. switch (encoding) {
  2592. case 'ascii':
  2593. case 'latin1':
  2594. case 'binary':
  2595. return len
  2596. case 'utf8':
  2597. case 'utf-8':
  2598. return utf8ToBytes(string).length
  2599. case 'ucs2':
  2600. case 'ucs-2':
  2601. case 'utf16le':
  2602. case 'utf-16le':
  2603. return len * 2
  2604. case 'hex':
  2605. return len >>> 1
  2606. case 'base64':
  2607. return base64ToBytes(string).length
  2608. default:
  2609. if (loweredCase) {
  2610. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2611. }
  2612. encoding = ('' + encoding).toLowerCase()
  2613. loweredCase = true
  2614. }
  2615. }
  2616. }
  2617. Buffer.byteLength = byteLength
  2618. function slowToString (encoding, start, end) {
  2619. var loweredCase = false
  2620. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2621. // property of a typed array.
  2622. // This behaves neither like String nor Uint8Array in that we set start/end
  2623. // to their upper/lower bounds if the value passed is out of range.
  2624. // undefined is handled specially as per ECMA-262 6th Edition,
  2625. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2626. if (start === undefined || start < 0) {
  2627. start = 0
  2628. }
  2629. // Return early if start > this.length. Done here to prevent potential uint32
  2630. // coercion fail below.
  2631. if (start > this.length) {
  2632. return ''
  2633. }
  2634. if (end === undefined || end > this.length) {
  2635. end = this.length
  2636. }
  2637. if (end <= 0) {
  2638. return ''
  2639. }
  2640. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2641. end >>>= 0
  2642. start >>>= 0
  2643. if (end <= start) {
  2644. return ''
  2645. }
  2646. if (!encoding) encoding = 'utf8'
  2647. while (true) {
  2648. switch (encoding) {
  2649. case 'hex':
  2650. return hexSlice(this, start, end)
  2651. case 'utf8':
  2652. case 'utf-8':
  2653. return utf8Slice(this, start, end)
  2654. case 'ascii':
  2655. return asciiSlice(this, start, end)
  2656. case 'latin1':
  2657. case 'binary':
  2658. return latin1Slice(this, start, end)
  2659. case 'base64':
  2660. return base64Slice(this, start, end)
  2661. case 'ucs2':
  2662. case 'ucs-2':
  2663. case 'utf16le':
  2664. case 'utf-16le':
  2665. return utf16leSlice(this, start, end)
  2666. default:
  2667. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2668. encoding = (encoding + '').toLowerCase()
  2669. loweredCase = true
  2670. }
  2671. }
  2672. }
  2673. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2674. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2675. // reliably in a browserify context because there could be multiple different
  2676. // copies of the 'buffer' package in use. This method works even for Buffer
  2677. // instances that were created from another copy of the `buffer` package.
  2678. // See: https://github.com/feross/buffer/issues/154
  2679. Buffer.prototype._isBuffer = true
  2680. function swap (b, n, m) {
  2681. var i = b[n]
  2682. b[n] = b[m]
  2683. b[m] = i
  2684. }
  2685. Buffer.prototype.swap16 = function swap16 () {
  2686. var len = this.length
  2687. if (len % 2 !== 0) {
  2688. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2689. }
  2690. for (var i = 0; i < len; i += 2) {
  2691. swap(this, i, i + 1)
  2692. }
  2693. return this
  2694. }
  2695. Buffer.prototype.swap32 = function swap32 () {
  2696. var len = this.length
  2697. if (len % 4 !== 0) {
  2698. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2699. }
  2700. for (var i = 0; i < len; i += 4) {
  2701. swap(this, i, i + 3)
  2702. swap(this, i + 1, i + 2)
  2703. }
  2704. return this
  2705. }
  2706. Buffer.prototype.swap64 = function swap64 () {
  2707. var len = this.length
  2708. if (len % 8 !== 0) {
  2709. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2710. }
  2711. for (var i = 0; i < len; i += 8) {
  2712. swap(this, i, i + 7)
  2713. swap(this, i + 1, i + 6)
  2714. swap(this, i + 2, i + 5)
  2715. swap(this, i + 3, i + 4)
  2716. }
  2717. return this
  2718. }
  2719. Buffer.prototype.toString = function toString () {
  2720. var length = this.length
  2721. if (length === 0) return ''
  2722. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2723. return slowToString.apply(this, arguments)
  2724. }
  2725. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2726. Buffer.prototype.equals = function equals (b) {
  2727. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2728. if (this === b) return true
  2729. return Buffer.compare(this, b) === 0
  2730. }
  2731. Buffer.prototype.inspect = function inspect () {
  2732. var str = ''
  2733. var max = exports.INSPECT_MAX_BYTES
  2734. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2735. if (this.length > max) str += ' ... '
  2736. return '<Buffer ' + str + '>'
  2737. }
  2738. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2739. if (isInstance(target, Uint8Array)) {
  2740. target = Buffer.from(target, target.offset, target.byteLength)
  2741. }
  2742. if (!Buffer.isBuffer(target)) {
  2743. throw new TypeError(
  2744. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2745. 'Received type ' + (typeof target)
  2746. )
  2747. }
  2748. if (start === undefined) {
  2749. start = 0
  2750. }
  2751. if (end === undefined) {
  2752. end = target ? target.length : 0
  2753. }
  2754. if (thisStart === undefined) {
  2755. thisStart = 0
  2756. }
  2757. if (thisEnd === undefined) {
  2758. thisEnd = this.length
  2759. }
  2760. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2761. throw new RangeError('out of range index')
  2762. }
  2763. if (thisStart >= thisEnd && start >= end) {
  2764. return 0
  2765. }
  2766. if (thisStart >= thisEnd) {
  2767. return -1
  2768. }
  2769. if (start >= end) {
  2770. return 1
  2771. }
  2772. start >>>= 0
  2773. end >>>= 0
  2774. thisStart >>>= 0
  2775. thisEnd >>>= 0
  2776. if (this === target) return 0
  2777. var x = thisEnd - thisStart
  2778. var y = end - start
  2779. var len = Math.min(x, y)
  2780. var thisCopy = this.slice(thisStart, thisEnd)
  2781. var targetCopy = target.slice(start, end)
  2782. for (var i = 0; i < len; ++i) {
  2783. if (thisCopy[i] !== targetCopy[i]) {
  2784. x = thisCopy[i]
  2785. y = targetCopy[i]
  2786. break
  2787. }
  2788. }
  2789. if (x < y) return -1
  2790. if (y < x) return 1
  2791. return 0
  2792. }
  2793. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2794. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2795. //
  2796. // Arguments:
  2797. // - buffer - a Buffer to search
  2798. // - val - a string, Buffer, or number
  2799. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2800. // - encoding - an optional encoding, relevant is val is a string
  2801. // - dir - true for indexOf, false for lastIndexOf
  2802. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2803. // Empty buffer means no match
  2804. if (buffer.length === 0) return -1
  2805. // Normalize byteOffset
  2806. if (typeof byteOffset === 'string') {
  2807. encoding = byteOffset
  2808. byteOffset = 0
  2809. } else if (byteOffset > 0x7fffffff) {
  2810. byteOffset = 0x7fffffff
  2811. } else if (byteOffset < -0x80000000) {
  2812. byteOffset = -0x80000000
  2813. }
  2814. byteOffset = +byteOffset // Coerce to Number.
  2815. if (numberIsNaN(byteOffset)) {
  2816. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2817. byteOffset = dir ? 0 : (buffer.length - 1)
  2818. }
  2819. // Normalize byteOffset: negative offsets start from the end of the buffer
  2820. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2821. if (byteOffset >= buffer.length) {
  2822. if (dir) return -1
  2823. else byteOffset = buffer.length - 1
  2824. } else if (byteOffset < 0) {
  2825. if (dir) byteOffset = 0
  2826. else return -1
  2827. }
  2828. // Normalize val
  2829. if (typeof val === 'string') {
  2830. val = Buffer.from(val, encoding)
  2831. }
  2832. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2833. if (Buffer.isBuffer(val)) {
  2834. // Special case: looking for empty string/buffer always fails
  2835. if (val.length === 0) {
  2836. return -1
  2837. }
  2838. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2839. } else if (typeof val === 'number') {
  2840. val = val & 0xFF // Search for a byte value [0-255]
  2841. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2842. if (dir) {
  2843. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2844. } else {
  2845. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2846. }
  2847. }
  2848. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2849. }
  2850. throw new TypeError('val must be string, number or Buffer')
  2851. }
  2852. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2853. var indexSize = 1
  2854. var arrLength = arr.length
  2855. var valLength = val.length
  2856. if (encoding !== undefined) {
  2857. encoding = String(encoding).toLowerCase()
  2858. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2859. encoding === 'utf16le' || encoding === 'utf-16le') {
  2860. if (arr.length < 2 || val.length < 2) {
  2861. return -1
  2862. }
  2863. indexSize = 2
  2864. arrLength /= 2
  2865. valLength /= 2
  2866. byteOffset /= 2
  2867. }
  2868. }
  2869. function read (buf, i) {
  2870. if (indexSize === 1) {
  2871. return buf[i]
  2872. } else {
  2873. return buf.readUInt16BE(i * indexSize)
  2874. }
  2875. }
  2876. var i
  2877. if (dir) {
  2878. var foundIndex = -1
  2879. for (i = byteOffset; i < arrLength; i++) {
  2880. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2881. if (foundIndex === -1) foundIndex = i
  2882. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2883. } else {
  2884. if (foundIndex !== -1) i -= i - foundIndex
  2885. foundIndex = -1
  2886. }
  2887. }
  2888. } else {
  2889. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2890. for (i = byteOffset; i >= 0; i--) {
  2891. var found = true
  2892. for (var j = 0; j < valLength; j++) {
  2893. if (read(arr, i + j) !== read(val, j)) {
  2894. found = false
  2895. break
  2896. }
  2897. }
  2898. if (found) return i
  2899. }
  2900. }
  2901. return -1
  2902. }
  2903. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2904. return this.indexOf(val, byteOffset, encoding) !== -1
  2905. }
  2906. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2907. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2908. }
  2909. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2910. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2911. }
  2912. function hexWrite (buf, string, offset, length) {
  2913. offset = Number(offset) || 0
  2914. var remaining = buf.length - offset
  2915. if (!length) {
  2916. length = remaining
  2917. } else {
  2918. length = Number(length)
  2919. if (length > remaining) {
  2920. length = remaining
  2921. }
  2922. }
  2923. var strLen = string.length
  2924. if (length > strLen / 2) {
  2925. length = strLen / 2
  2926. }
  2927. for (var i = 0; i < length; ++i) {
  2928. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2929. if (numberIsNaN(parsed)) return i
  2930. buf[offset + i] = parsed
  2931. }
  2932. return i
  2933. }
  2934. function utf8Write (buf, string, offset, length) {
  2935. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2936. }
  2937. function asciiWrite (buf, string, offset, length) {
  2938. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2939. }
  2940. function latin1Write (buf, string, offset, length) {
  2941. return asciiWrite(buf, string, offset, length)
  2942. }
  2943. function base64Write (buf, string, offset, length) {
  2944. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2945. }
  2946. function ucs2Write (buf, string, offset, length) {
  2947. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2948. }
  2949. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2950. // Buffer#write(string)
  2951. if (offset === undefined) {
  2952. encoding = 'utf8'
  2953. length = this.length
  2954. offset = 0
  2955. // Buffer#write(string, encoding)
  2956. } else if (length === undefined && typeof offset === 'string') {
  2957. encoding = offset
  2958. length = this.length
  2959. offset = 0
  2960. // Buffer#write(string, offset[, length][, encoding])
  2961. } else if (isFinite(offset)) {
  2962. offset = offset >>> 0
  2963. if (isFinite(length)) {
  2964. length = length >>> 0
  2965. if (encoding === undefined) encoding = 'utf8'
  2966. } else {
  2967. encoding = length
  2968. length = undefined
  2969. }
  2970. } else {
  2971. throw new Error(
  2972. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2973. )
  2974. }
  2975. var remaining = this.length - offset
  2976. if (length === undefined || length > remaining) length = remaining
  2977. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2978. throw new RangeError('Attempt to write outside buffer bounds')
  2979. }
  2980. if (!encoding) encoding = 'utf8'
  2981. var loweredCase = false
  2982. for (;;) {
  2983. switch (encoding) {
  2984. case 'hex':
  2985. return hexWrite(this, string, offset, length)
  2986. case 'utf8':
  2987. case 'utf-8':
  2988. return utf8Write(this, string, offset, length)
  2989. case 'ascii':
  2990. return asciiWrite(this, string, offset, length)
  2991. case 'latin1':
  2992. case 'binary':
  2993. return latin1Write(this, string, offset, length)
  2994. case 'base64':
  2995. // Warning: maxLength not taken into account in base64Write
  2996. return base64Write(this, string, offset, length)
  2997. case 'ucs2':
  2998. case 'ucs-2':
  2999. case 'utf16le':
  3000. case 'utf-16le':
  3001. return ucs2Write(this, string, offset, length)
  3002. default:
  3003. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3004. encoding = ('' + encoding).toLowerCase()
  3005. loweredCase = true
  3006. }
  3007. }
  3008. }
  3009. Buffer.prototype.toJSON = function toJSON () {
  3010. return {
  3011. type: 'Buffer',
  3012. data: Array.prototype.slice.call(this._arr || this, 0)
  3013. }
  3014. }
  3015. function base64Slice (buf, start, end) {
  3016. if (start === 0 && end === buf.length) {
  3017. return base64.fromByteArray(buf)
  3018. } else {
  3019. return base64.fromByteArray(buf.slice(start, end))
  3020. }
  3021. }
  3022. function utf8Slice (buf, start, end) {
  3023. end = Math.min(buf.length, end)
  3024. var res = []
  3025. var i = start
  3026. while (i < end) {
  3027. var firstByte = buf[i]
  3028. var codePoint = null
  3029. var bytesPerSequence = (firstByte > 0xEF) ? 4
  3030. : (firstByte > 0xDF) ? 3
  3031. : (firstByte > 0xBF) ? 2
  3032. : 1
  3033. if (i + bytesPerSequence <= end) {
  3034. var secondByte, thirdByte, fourthByte, tempCodePoint
  3035. switch (bytesPerSequence) {
  3036. case 1:
  3037. if (firstByte < 0x80) {
  3038. codePoint = firstByte
  3039. }
  3040. break
  3041. case 2:
  3042. secondByte = buf[i + 1]
  3043. if ((secondByte & 0xC0) === 0x80) {
  3044. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  3045. if (tempCodePoint > 0x7F) {
  3046. codePoint = tempCodePoint
  3047. }
  3048. }
  3049. break
  3050. case 3:
  3051. secondByte = buf[i + 1]
  3052. thirdByte = buf[i + 2]
  3053. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3054. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  3055. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  3056. codePoint = tempCodePoint
  3057. }
  3058. }
  3059. break
  3060. case 4:
  3061. secondByte = buf[i + 1]
  3062. thirdByte = buf[i + 2]
  3063. fourthByte = buf[i + 3]
  3064. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  3065. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  3066. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3067. codePoint = tempCodePoint
  3068. }
  3069. }
  3070. }
  3071. }
  3072. if (codePoint === null) {
  3073. // we did not generate a valid codePoint so insert a
  3074. // replacement char (U+FFFD) and advance only 1 byte
  3075. codePoint = 0xFFFD
  3076. bytesPerSequence = 1
  3077. } else if (codePoint > 0xFFFF) {
  3078. // encode to utf16 (surrogate pair dance)
  3079. codePoint -= 0x10000
  3080. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  3081. codePoint = 0xDC00 | codePoint & 0x3FF
  3082. }
  3083. res.push(codePoint)
  3084. i += bytesPerSequence
  3085. }
  3086. return decodeCodePointsArray(res)
  3087. }
  3088. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3089. // the lowest limit is Chrome, with 0x10000 args.
  3090. // We go 1 magnitude less, for safety
  3091. var MAX_ARGUMENTS_LENGTH = 0x1000
  3092. function decodeCodePointsArray (codePoints) {
  3093. var len = codePoints.length
  3094. if (len <= MAX_ARGUMENTS_LENGTH) {
  3095. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3096. }
  3097. // Decode in chunks to avoid "call stack size exceeded".
  3098. var res = ''
  3099. var i = 0
  3100. while (i < len) {
  3101. res += String.fromCharCode.apply(
  3102. String,
  3103. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3104. )
  3105. }
  3106. return res
  3107. }
  3108. function asciiSlice (buf, start, end) {
  3109. var ret = ''
  3110. end = Math.min(buf.length, end)
  3111. for (var i = start; i < end; ++i) {
  3112. ret += String.fromCharCode(buf[i] & 0x7F)
  3113. }
  3114. return ret
  3115. }
  3116. function latin1Slice (buf, start, end) {
  3117. var ret = ''
  3118. end = Math.min(buf.length, end)
  3119. for (var i = start; i < end; ++i) {
  3120. ret += String.fromCharCode(buf[i])
  3121. }
  3122. return ret
  3123. }
  3124. function hexSlice (buf, start, end) {
  3125. var len = buf.length
  3126. if (!start || start < 0) start = 0
  3127. if (!end || end < 0 || end > len) end = len
  3128. var out = ''
  3129. for (var i = start; i < end; ++i) {
  3130. out += toHex(buf[i])
  3131. }
  3132. return out
  3133. }
  3134. function utf16leSlice (buf, start, end) {
  3135. var bytes = buf.slice(start, end)
  3136. var res = ''
  3137. for (var i = 0; i < bytes.length; i += 2) {
  3138. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3139. }
  3140. return res
  3141. }
  3142. Buffer.prototype.slice = function slice (start, end) {
  3143. var len = this.length
  3144. start = ~~start
  3145. end = end === undefined ? len : ~~end
  3146. if (start < 0) {
  3147. start += len
  3148. if (start < 0) start = 0
  3149. } else if (start > len) {
  3150. start = len
  3151. }
  3152. if (end < 0) {
  3153. end += len
  3154. if (end < 0) end = 0
  3155. } else if (end > len) {
  3156. end = len
  3157. }
  3158. if (end < start) end = start
  3159. var newBuf = this.subarray(start, end)
  3160. // Return an augmented `Uint8Array` instance
  3161. newBuf.__proto__ = Buffer.prototype
  3162. return newBuf
  3163. }
  3164. /*
  3165. * Need to make sure that buffer isn't trying to write out of bounds.
  3166. */
  3167. function checkOffset (offset, ext, length) {
  3168. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3169. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3170. }
  3171. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3172. offset = offset >>> 0
  3173. byteLength = byteLength >>> 0
  3174. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3175. var val = this[offset]
  3176. var mul = 1
  3177. var i = 0
  3178. while (++i < byteLength && (mul *= 0x100)) {
  3179. val += this[offset + i] * mul
  3180. }
  3181. return val
  3182. }
  3183. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3184. offset = offset >>> 0
  3185. byteLength = byteLength >>> 0
  3186. if (!noAssert) {
  3187. checkOffset(offset, byteLength, this.length)
  3188. }
  3189. var val = this[offset + --byteLength]
  3190. var mul = 1
  3191. while (byteLength > 0 && (mul *= 0x100)) {
  3192. val += this[offset + --byteLength] * mul
  3193. }
  3194. return val
  3195. }
  3196. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3197. offset = offset >>> 0
  3198. if (!noAssert) checkOffset(offset, 1, this.length)
  3199. return this[offset]
  3200. }
  3201. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3202. offset = offset >>> 0
  3203. if (!noAssert) checkOffset(offset, 2, this.length)
  3204. return this[offset] | (this[offset + 1] << 8)
  3205. }
  3206. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3207. offset = offset >>> 0
  3208. if (!noAssert) checkOffset(offset, 2, this.length)
  3209. return (this[offset] << 8) | this[offset + 1]
  3210. }
  3211. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3212. offset = offset >>> 0
  3213. if (!noAssert) checkOffset(offset, 4, this.length)
  3214. return ((this[offset]) |
  3215. (this[offset + 1] << 8) |
  3216. (this[offset + 2] << 16)) +
  3217. (this[offset + 3] * 0x1000000)
  3218. }
  3219. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3220. offset = offset >>> 0
  3221. if (!noAssert) checkOffset(offset, 4, this.length)
  3222. return (this[offset] * 0x1000000) +
  3223. ((this[offset + 1] << 16) |
  3224. (this[offset + 2] << 8) |
  3225. this[offset + 3])
  3226. }
  3227. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3228. offset = offset >>> 0
  3229. byteLength = byteLength >>> 0
  3230. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3231. var val = this[offset]
  3232. var mul = 1
  3233. var i = 0
  3234. while (++i < byteLength && (mul *= 0x100)) {
  3235. val += this[offset + i] * mul
  3236. }
  3237. mul *= 0x80
  3238. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3239. return val
  3240. }
  3241. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3242. offset = offset >>> 0
  3243. byteLength = byteLength >>> 0
  3244. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3245. var i = byteLength
  3246. var mul = 1
  3247. var val = this[offset + --i]
  3248. while (i > 0 && (mul *= 0x100)) {
  3249. val += this[offset + --i] * mul
  3250. }
  3251. mul *= 0x80
  3252. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3253. return val
  3254. }
  3255. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3256. offset = offset >>> 0
  3257. if (!noAssert) checkOffset(offset, 1, this.length)
  3258. if (!(this[offset] & 0x80)) return (this[offset])
  3259. return ((0xff - this[offset] + 1) * -1)
  3260. }
  3261. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3262. offset = offset >>> 0
  3263. if (!noAssert) checkOffset(offset, 2, this.length)
  3264. var val = this[offset] | (this[offset + 1] << 8)
  3265. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3266. }
  3267. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3268. offset = offset >>> 0
  3269. if (!noAssert) checkOffset(offset, 2, this.length)
  3270. var val = this[offset + 1] | (this[offset] << 8)
  3271. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3272. }
  3273. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3274. offset = offset >>> 0
  3275. if (!noAssert) checkOffset(offset, 4, this.length)
  3276. return (this[offset]) |
  3277. (this[offset + 1] << 8) |
  3278. (this[offset + 2] << 16) |
  3279. (this[offset + 3] << 24)
  3280. }
  3281. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3282. offset = offset >>> 0
  3283. if (!noAssert) checkOffset(offset, 4, this.length)
  3284. return (this[offset] << 24) |
  3285. (this[offset + 1] << 16) |
  3286. (this[offset + 2] << 8) |
  3287. (this[offset + 3])
  3288. }
  3289. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3290. offset = offset >>> 0
  3291. if (!noAssert) checkOffset(offset, 4, this.length)
  3292. return ieee754.read(this, offset, true, 23, 4)
  3293. }
  3294. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3295. offset = offset >>> 0
  3296. if (!noAssert) checkOffset(offset, 4, this.length)
  3297. return ieee754.read(this, offset, false, 23, 4)
  3298. }
  3299. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3300. offset = offset >>> 0
  3301. if (!noAssert) checkOffset(offset, 8, this.length)
  3302. return ieee754.read(this, offset, true, 52, 8)
  3303. }
  3304. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3305. offset = offset >>> 0
  3306. if (!noAssert) checkOffset(offset, 8, this.length)
  3307. return ieee754.read(this, offset, false, 52, 8)
  3308. }
  3309. function checkInt (buf, value, offset, ext, max, min) {
  3310. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3311. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3312. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3313. }
  3314. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3315. value = +value
  3316. offset = offset >>> 0
  3317. byteLength = byteLength >>> 0
  3318. if (!noAssert) {
  3319. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3320. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3321. }
  3322. var mul = 1
  3323. var i = 0
  3324. this[offset] = value & 0xFF
  3325. while (++i < byteLength && (mul *= 0x100)) {
  3326. this[offset + i] = (value / mul) & 0xFF
  3327. }
  3328. return offset + byteLength
  3329. }
  3330. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3331. value = +value
  3332. offset = offset >>> 0
  3333. byteLength = byteLength >>> 0
  3334. if (!noAssert) {
  3335. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3336. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3337. }
  3338. var i = byteLength - 1
  3339. var mul = 1
  3340. this[offset + i] = value & 0xFF
  3341. while (--i >= 0 && (mul *= 0x100)) {
  3342. this[offset + i] = (value / mul) & 0xFF
  3343. }
  3344. return offset + byteLength
  3345. }
  3346. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3347. value = +value
  3348. offset = offset >>> 0
  3349. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3350. this[offset] = (value & 0xff)
  3351. return offset + 1
  3352. }
  3353. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3354. value = +value
  3355. offset = offset >>> 0
  3356. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3357. this[offset] = (value & 0xff)
  3358. this[offset + 1] = (value >>> 8)
  3359. return offset + 2
  3360. }
  3361. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3362. value = +value
  3363. offset = offset >>> 0
  3364. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3365. this[offset] = (value >>> 8)
  3366. this[offset + 1] = (value & 0xff)
  3367. return offset + 2
  3368. }
  3369. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3370. value = +value
  3371. offset = offset >>> 0
  3372. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3373. this[offset + 3] = (value >>> 24)
  3374. this[offset + 2] = (value >>> 16)
  3375. this[offset + 1] = (value >>> 8)
  3376. this[offset] = (value & 0xff)
  3377. return offset + 4
  3378. }
  3379. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3380. value = +value
  3381. offset = offset >>> 0
  3382. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3383. this[offset] = (value >>> 24)
  3384. this[offset + 1] = (value >>> 16)
  3385. this[offset + 2] = (value >>> 8)
  3386. this[offset + 3] = (value & 0xff)
  3387. return offset + 4
  3388. }
  3389. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3390. value = +value
  3391. offset = offset >>> 0
  3392. if (!noAssert) {
  3393. var limit = Math.pow(2, (8 * byteLength) - 1)
  3394. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3395. }
  3396. var i = 0
  3397. var mul = 1
  3398. var sub = 0
  3399. this[offset] = value & 0xFF
  3400. while (++i < byteLength && (mul *= 0x100)) {
  3401. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3402. sub = 1
  3403. }
  3404. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3405. }
  3406. return offset + byteLength
  3407. }
  3408. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3409. value = +value
  3410. offset = offset >>> 0
  3411. if (!noAssert) {
  3412. var limit = Math.pow(2, (8 * byteLength) - 1)
  3413. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3414. }
  3415. var i = byteLength - 1
  3416. var mul = 1
  3417. var sub = 0
  3418. this[offset + i] = value & 0xFF
  3419. while (--i >= 0 && (mul *= 0x100)) {
  3420. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3421. sub = 1
  3422. }
  3423. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3424. }
  3425. return offset + byteLength
  3426. }
  3427. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3428. value = +value
  3429. offset = offset >>> 0
  3430. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3431. if (value < 0) value = 0xff + value + 1
  3432. this[offset] = (value & 0xff)
  3433. return offset + 1
  3434. }
  3435. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3436. value = +value
  3437. offset = offset >>> 0
  3438. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3439. this[offset] = (value & 0xff)
  3440. this[offset + 1] = (value >>> 8)
  3441. return offset + 2
  3442. }
  3443. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3444. value = +value
  3445. offset = offset >>> 0
  3446. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3447. this[offset] = (value >>> 8)
  3448. this[offset + 1] = (value & 0xff)
  3449. return offset + 2
  3450. }
  3451. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3452. value = +value
  3453. offset = offset >>> 0
  3454. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3455. this[offset] = (value & 0xff)
  3456. this[offset + 1] = (value >>> 8)
  3457. this[offset + 2] = (value >>> 16)
  3458. this[offset + 3] = (value >>> 24)
  3459. return offset + 4
  3460. }
  3461. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3462. value = +value
  3463. offset = offset >>> 0
  3464. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3465. if (value < 0) value = 0xffffffff + value + 1
  3466. this[offset] = (value >>> 24)
  3467. this[offset + 1] = (value >>> 16)
  3468. this[offset + 2] = (value >>> 8)
  3469. this[offset + 3] = (value & 0xff)
  3470. return offset + 4
  3471. }
  3472. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3473. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3474. if (offset < 0) throw new RangeError('Index out of range')
  3475. }
  3476. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3477. value = +value
  3478. offset = offset >>> 0
  3479. if (!noAssert) {
  3480. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3481. }
  3482. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3483. return offset + 4
  3484. }
  3485. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3486. return writeFloat(this, value, offset, true, noAssert)
  3487. }
  3488. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3489. return writeFloat(this, value, offset, false, noAssert)
  3490. }
  3491. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3492. value = +value
  3493. offset = offset >>> 0
  3494. if (!noAssert) {
  3495. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3496. }
  3497. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3498. return offset + 8
  3499. }
  3500. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3501. return writeDouble(this, value, offset, true, noAssert)
  3502. }
  3503. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3504. return writeDouble(this, value, offset, false, noAssert)
  3505. }
  3506. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3507. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3508. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3509. if (!start) start = 0
  3510. if (!end && end !== 0) end = this.length
  3511. if (targetStart >= target.length) targetStart = target.length
  3512. if (!targetStart) targetStart = 0
  3513. if (end > 0 && end < start) end = start
  3514. // Copy 0 bytes; we're done
  3515. if (end === start) return 0
  3516. if (target.length === 0 || this.length === 0) return 0
  3517. // Fatal error conditions
  3518. if (targetStart < 0) {
  3519. throw new RangeError('targetStart out of bounds')
  3520. }
  3521. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3522. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3523. // Are we oob?
  3524. if (end > this.length) end = this.length
  3525. if (target.length - targetStart < end - start) {
  3526. end = target.length - targetStart + start
  3527. }
  3528. var len = end - start
  3529. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3530. // Use built-in when available, missing from IE11
  3531. this.copyWithin(targetStart, start, end)
  3532. } else if (this === target && start < targetStart && targetStart < end) {
  3533. // descending copy from end
  3534. for (var i = len - 1; i >= 0; --i) {
  3535. target[i + targetStart] = this[i + start]
  3536. }
  3537. } else {
  3538. Uint8Array.prototype.set.call(
  3539. target,
  3540. this.subarray(start, end),
  3541. targetStart
  3542. )
  3543. }
  3544. return len
  3545. }
  3546. // Usage:
  3547. // buffer.fill(number[, offset[, end]])
  3548. // buffer.fill(buffer[, offset[, end]])
  3549. // buffer.fill(string[, offset[, end]][, encoding])
  3550. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3551. // Handle string cases:
  3552. if (typeof val === 'string') {
  3553. if (typeof start === 'string') {
  3554. encoding = start
  3555. start = 0
  3556. end = this.length
  3557. } else if (typeof end === 'string') {
  3558. encoding = end
  3559. end = this.length
  3560. }
  3561. if (encoding !== undefined && typeof encoding !== 'string') {
  3562. throw new TypeError('encoding must be a string')
  3563. }
  3564. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3565. throw new TypeError('Unknown encoding: ' + encoding)
  3566. }
  3567. if (val.length === 1) {
  3568. var code = val.charCodeAt(0)
  3569. if ((encoding === 'utf8' && code < 128) ||
  3570. encoding === 'latin1') {
  3571. // Fast path: If `val` fits into a single byte, use that numeric value.
  3572. val = code
  3573. }
  3574. }
  3575. } else if (typeof val === 'number') {
  3576. val = val & 255
  3577. }
  3578. // Invalid ranges are not set to a default, so can range check early.
  3579. if (start < 0 || this.length < start || this.length < end) {
  3580. throw new RangeError('Out of range index')
  3581. }
  3582. if (end <= start) {
  3583. return this
  3584. }
  3585. start = start >>> 0
  3586. end = end === undefined ? this.length : end >>> 0
  3587. if (!val) val = 0
  3588. var i
  3589. if (typeof val === 'number') {
  3590. for (i = start; i < end; ++i) {
  3591. this[i] = val
  3592. }
  3593. } else {
  3594. var bytes = Buffer.isBuffer(val)
  3595. ? val
  3596. : Buffer.from(val, encoding)
  3597. var len = bytes.length
  3598. if (len === 0) {
  3599. throw new TypeError('The value "' + val +
  3600. '" is invalid for argument "value"')
  3601. }
  3602. for (i = 0; i < end - start; ++i) {
  3603. this[i + start] = bytes[i % len]
  3604. }
  3605. }
  3606. return this
  3607. }
  3608. // HELPER FUNCTIONS
  3609. // ================
  3610. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3611. function base64clean (str) {
  3612. // Node takes equal signs as end of the Base64 encoding
  3613. str = str.split('=')[0]
  3614. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3615. str = str.trim().replace(INVALID_BASE64_RE, '')
  3616. // Node converts strings with length < 2 to ''
  3617. if (str.length < 2) return ''
  3618. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3619. while (str.length % 4 !== 0) {
  3620. str = str + '='
  3621. }
  3622. return str
  3623. }
  3624. function toHex (n) {
  3625. if (n < 16) return '0' + n.toString(16)
  3626. return n.toString(16)
  3627. }
  3628. function utf8ToBytes (string, units) {
  3629. units = units || Infinity
  3630. var codePoint
  3631. var length = string.length
  3632. var leadSurrogate = null
  3633. var bytes = []
  3634. for (var i = 0; i < length; ++i) {
  3635. codePoint = string.charCodeAt(i)
  3636. // is surrogate component
  3637. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3638. // last char was a lead
  3639. if (!leadSurrogate) {
  3640. // no lead yet
  3641. if (codePoint > 0xDBFF) {
  3642. // unexpected trail
  3643. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3644. continue
  3645. } else if (i + 1 === length) {
  3646. // unpaired lead
  3647. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3648. continue
  3649. }
  3650. // valid lead
  3651. leadSurrogate = codePoint
  3652. continue
  3653. }
  3654. // 2 leads in a row
  3655. if (codePoint < 0xDC00) {
  3656. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3657. leadSurrogate = codePoint
  3658. continue
  3659. }
  3660. // valid surrogate pair
  3661. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3662. } else if (leadSurrogate) {
  3663. // valid bmp char, but last char was a lead
  3664. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3665. }
  3666. leadSurrogate = null
  3667. // encode utf8
  3668. if (codePoint < 0x80) {
  3669. if ((units -= 1) < 0) break
  3670. bytes.push(codePoint)
  3671. } else if (codePoint < 0x800) {
  3672. if ((units -= 2) < 0) break
  3673. bytes.push(
  3674. codePoint >> 0x6 | 0xC0,
  3675. codePoint & 0x3F | 0x80
  3676. )
  3677. } else if (codePoint < 0x10000) {
  3678. if ((units -= 3) < 0) break
  3679. bytes.push(
  3680. codePoint >> 0xC | 0xE0,
  3681. codePoint >> 0x6 & 0x3F | 0x80,
  3682. codePoint & 0x3F | 0x80
  3683. )
  3684. } else if (codePoint < 0x110000) {
  3685. if ((units -= 4) < 0) break
  3686. bytes.push(
  3687. codePoint >> 0x12 | 0xF0,
  3688. codePoint >> 0xC & 0x3F | 0x80,
  3689. codePoint >> 0x6 & 0x3F | 0x80,
  3690. codePoint & 0x3F | 0x80
  3691. )
  3692. } else {
  3693. throw new Error('Invalid code point')
  3694. }
  3695. }
  3696. return bytes
  3697. }
  3698. function asciiToBytes (str) {
  3699. var byteArray = []
  3700. for (var i = 0; i < str.length; ++i) {
  3701. // Node's code seems to be doing this and not & 0x7F..
  3702. byteArray.push(str.charCodeAt(i) & 0xFF)
  3703. }
  3704. return byteArray
  3705. }
  3706. function utf16leToBytes (str, units) {
  3707. var c, hi, lo
  3708. var byteArray = []
  3709. for (var i = 0; i < str.length; ++i) {
  3710. if ((units -= 2) < 0) break
  3711. c = str.charCodeAt(i)
  3712. hi = c >> 8
  3713. lo = c % 256
  3714. byteArray.push(lo)
  3715. byteArray.push(hi)
  3716. }
  3717. return byteArray
  3718. }
  3719. function base64ToBytes (str) {
  3720. return base64.toByteArray(base64clean(str))
  3721. }
  3722. function blitBuffer (src, dst, offset, length) {
  3723. for (var i = 0; i < length; ++i) {
  3724. if ((i + offset >= dst.length) || (i >= src.length)) break
  3725. dst[i + offset] = src[i]
  3726. }
  3727. return i
  3728. }
  3729. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3730. // the `instanceof` check but they should be treated as of that type.
  3731. // See: https://github.com/feross/buffer/issues/166
  3732. function isInstance (obj, type) {
  3733. return obj instanceof type ||
  3734. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3735. obj.constructor.name === type.name)
  3736. }
  3737. function numberIsNaN (obj) {
  3738. // For IE11 support
  3739. return obj !== obj // eslint-disable-line no-self-compare
  3740. }
  3741. }).call(this,require("buffer").Buffer)
  3742. },{"base64-js":10,"buffer":12,"ieee754":87}],13:[function(require,module,exports){
  3743. (function (Buffer){
  3744. // Copyright Joyent, Inc. and other Node contributors.
  3745. //
  3746. // Permission is hereby granted, free of charge, to any person obtaining a
  3747. // copy of this software and associated documentation files (the
  3748. // "Software"), to deal in the Software without restriction, including
  3749. // without limitation the rights to use, copy, modify, merge, publish,
  3750. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3751. // persons to whom the Software is furnished to do so, subject to the
  3752. // following conditions:
  3753. //
  3754. // The above copyright notice and this permission notice shall be included
  3755. // in all copies or substantial portions of the Software.
  3756. //
  3757. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3758. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3759. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3760. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3761. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3762. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3763. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3764. // NOTE: These type checking functions intentionally don't use `instanceof`
  3765. // because it is fragile and can be easily faked with `Object.create()`.
  3766. function isArray(arg) {
  3767. if (Array.isArray) {
  3768. return Array.isArray(arg);
  3769. }
  3770. return objectToString(arg) === '[object Array]';
  3771. }
  3772. exports.isArray = isArray;
  3773. function isBoolean(arg) {
  3774. return typeof arg === 'boolean';
  3775. }
  3776. exports.isBoolean = isBoolean;
  3777. function isNull(arg) {
  3778. return arg === null;
  3779. }
  3780. exports.isNull = isNull;
  3781. function isNullOrUndefined(arg) {
  3782. return arg == null;
  3783. }
  3784. exports.isNullOrUndefined = isNullOrUndefined;
  3785. function isNumber(arg) {
  3786. return typeof arg === 'number';
  3787. }
  3788. exports.isNumber = isNumber;
  3789. function isString(arg) {
  3790. return typeof arg === 'string';
  3791. }
  3792. exports.isString = isString;
  3793. function isSymbol(arg) {
  3794. return typeof arg === 'symbol';
  3795. }
  3796. exports.isSymbol = isSymbol;
  3797. function isUndefined(arg) {
  3798. return arg === void 0;
  3799. }
  3800. exports.isUndefined = isUndefined;
  3801. function isRegExp(re) {
  3802. return objectToString(re) === '[object RegExp]';
  3803. }
  3804. exports.isRegExp = isRegExp;
  3805. function isObject(arg) {
  3806. return typeof arg === 'object' && arg !== null;
  3807. }
  3808. exports.isObject = isObject;
  3809. function isDate(d) {
  3810. return objectToString(d) === '[object Date]';
  3811. }
  3812. exports.isDate = isDate;
  3813. function isError(e) {
  3814. return (objectToString(e) === '[object Error]' || e instanceof Error);
  3815. }
  3816. exports.isError = isError;
  3817. function isFunction(arg) {
  3818. return typeof arg === 'function';
  3819. }
  3820. exports.isFunction = isFunction;
  3821. function isPrimitive(arg) {
  3822. return arg === null ||
  3823. typeof arg === 'boolean' ||
  3824. typeof arg === 'number' ||
  3825. typeof arg === 'string' ||
  3826. typeof arg === 'symbol' || // ES6 symbol
  3827. typeof arg === 'undefined';
  3828. }
  3829. exports.isPrimitive = isPrimitive;
  3830. exports.isBuffer = Buffer.isBuffer;
  3831. function objectToString(o) {
  3832. return Object.prototype.toString.call(o);
  3833. }
  3834. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  3835. },{"../../is-buffer/index.js":89}],14:[function(require,module,exports){
  3836. "use strict";
  3837. var isValue = require("type/value/is")
  3838. , ensureValue = require("type/value/ensure")
  3839. , ensurePlainFunction = require("type/plain-function/ensure")
  3840. , copy = require("es5-ext/object/copy")
  3841. , normalizeOptions = require("es5-ext/object/normalize-options")
  3842. , map = require("es5-ext/object/map");
  3843. var bind = Function.prototype.bind
  3844. , defineProperty = Object.defineProperty
  3845. , hasOwnProperty = Object.prototype.hasOwnProperty
  3846. , define;
  3847. define = function (name, desc, options) {
  3848. var value = ensureValue(desc) && ensurePlainFunction(desc.value), dgs;
  3849. dgs = copy(desc);
  3850. delete dgs.writable;
  3851. delete dgs.value;
  3852. dgs.get = function () {
  3853. if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
  3854. desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
  3855. defineProperty(this, name, desc);
  3856. return this[name];
  3857. };
  3858. return dgs;
  3859. };
  3860. module.exports = function (props/*, options*/) {
  3861. var options = normalizeOptions(arguments[1]);
  3862. if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext);
  3863. return map(props, function (desc, name) { return define(name, desc, options); });
  3864. };
  3865. },{"es5-ext/object/copy":41,"es5-ext/object/map":49,"es5-ext/object/normalize-options":50,"type/plain-function/ensure":126,"type/value/ensure":130,"type/value/is":131}],15:[function(require,module,exports){
  3866. "use strict";
  3867. var isValue = require("type/value/is")
  3868. , isPlainFunction = require("type/plain-function/is")
  3869. , assign = require("es5-ext/object/assign")
  3870. , normalizeOpts = require("es5-ext/object/normalize-options")
  3871. , contains = require("es5-ext/string/#/contains");
  3872. var d = (module.exports = function (dscr, value/*, options*/) {
  3873. var c, e, w, options, desc;
  3874. if (arguments.length < 2 || typeof dscr !== "string") {
  3875. options = value;
  3876. value = dscr;
  3877. dscr = null;
  3878. } else {
  3879. options = arguments[2];
  3880. }
  3881. if (isValue(dscr)) {
  3882. c = contains.call(dscr, "c");
  3883. e = contains.call(dscr, "e");
  3884. w = contains.call(dscr, "w");
  3885. } else {
  3886. c = w = true;
  3887. e = false;
  3888. }
  3889. desc = { value: value, configurable: c, enumerable: e, writable: w };
  3890. return !options ? desc : assign(normalizeOpts(options), desc);
  3891. });
  3892. d.gs = function (dscr, get, set/*, options*/) {
  3893. var c, e, options, desc;
  3894. if (typeof dscr !== "string") {
  3895. options = set;
  3896. set = get;
  3897. get = dscr;
  3898. dscr = null;
  3899. } else {
  3900. options = arguments[3];
  3901. }
  3902. if (!isValue(get)) {
  3903. get = undefined;
  3904. } else if (!isPlainFunction(get)) {
  3905. options = get;
  3906. get = set = undefined;
  3907. } else if (!isValue(set)) {
  3908. set = undefined;
  3909. } else if (!isPlainFunction(set)) {
  3910. options = set;
  3911. set = undefined;
  3912. }
  3913. if (isValue(dscr)) {
  3914. c = contains.call(dscr, "c");
  3915. e = contains.call(dscr, "e");
  3916. } else {
  3917. c = true;
  3918. e = false;
  3919. }
  3920. desc = { get: get, set: set, configurable: c, enumerable: e };
  3921. return !options ? desc : assign(normalizeOpts(options), desc);
  3922. };
  3923. },{"es5-ext/object/assign":38,"es5-ext/object/normalize-options":50,"es5-ext/string/#/contains":57,"type/plain-function/is":127,"type/value/is":131}],16:[function(require,module,exports){
  3924. /**
  3925. * Helpers.
  3926. */
  3927. var s = 1000;
  3928. var m = s * 60;
  3929. var h = m * 60;
  3930. var d = h * 24;
  3931. var w = d * 7;
  3932. var y = d * 365.25;
  3933. /**
  3934. * Parse or format the given `val`.
  3935. *
  3936. * Options:
  3937. *
  3938. * - `long` verbose formatting [false]
  3939. *
  3940. * @param {String|Number} val
  3941. * @param {Object} [options]
  3942. * @throws {Error} throw an error if val is not a non-empty string or a number
  3943. * @return {String|Number}
  3944. * @api public
  3945. */
  3946. module.exports = function(val, options) {
  3947. options = options || {};
  3948. var type = typeof val;
  3949. if (type === 'string' && val.length > 0) {
  3950. return parse(val);
  3951. } else if (type === 'number' && isFinite(val)) {
  3952. return options.long ? fmtLong(val) : fmtShort(val);
  3953. }
  3954. throw new Error(
  3955. 'val is not a non-empty string or a valid number. val=' +
  3956. JSON.stringify(val)
  3957. );
  3958. };
  3959. /**
  3960. * Parse the given `str` and return milliseconds.
  3961. *
  3962. * @param {String} str
  3963. * @return {Number}
  3964. * @api private
  3965. */
  3966. function parse(str) {
  3967. str = String(str);
  3968. if (str.length > 100) {
  3969. return;
  3970. }
  3971. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  3972. str
  3973. );
  3974. if (!match) {
  3975. return;
  3976. }
  3977. var n = parseFloat(match[1]);
  3978. var type = (match[2] || 'ms').toLowerCase();
  3979. switch (type) {
  3980. case 'years':
  3981. case 'year':
  3982. case 'yrs':
  3983. case 'yr':
  3984. case 'y':
  3985. return n * y;
  3986. case 'weeks':
  3987. case 'week':
  3988. case 'w':
  3989. return n * w;
  3990. case 'days':
  3991. case 'day':
  3992. case 'd':
  3993. return n * d;
  3994. case 'hours':
  3995. case 'hour':
  3996. case 'hrs':
  3997. case 'hr':
  3998. case 'h':
  3999. return n * h;
  4000. case 'minutes':
  4001. case 'minute':
  4002. case 'mins':
  4003. case 'min':
  4004. case 'm':
  4005. return n * m;
  4006. case 'seconds':
  4007. case 'second':
  4008. case 'secs':
  4009. case 'sec':
  4010. case 's':
  4011. return n * s;
  4012. case 'milliseconds':
  4013. case 'millisecond':
  4014. case 'msecs':
  4015. case 'msec':
  4016. case 'ms':
  4017. return n;
  4018. default:
  4019. return undefined;
  4020. }
  4021. }
  4022. /**
  4023. * Short format for `ms`.
  4024. *
  4025. * @param {Number} ms
  4026. * @return {String}
  4027. * @api private
  4028. */
  4029. function fmtShort(ms) {
  4030. var msAbs = Math.abs(ms);
  4031. if (msAbs >= d) {
  4032. return Math.round(ms / d) + 'd';
  4033. }
  4034. if (msAbs >= h) {
  4035. return Math.round(ms / h) + 'h';
  4036. }
  4037. if (msAbs >= m) {
  4038. return Math.round(ms / m) + 'm';
  4039. }
  4040. if (msAbs >= s) {
  4041. return Math.round(ms / s) + 's';
  4042. }
  4043. return ms + 'ms';
  4044. }
  4045. /**
  4046. * Long format for `ms`.
  4047. *
  4048. * @param {Number} ms
  4049. * @return {String}
  4050. * @api private
  4051. */
  4052. function fmtLong(ms) {
  4053. var msAbs = Math.abs(ms);
  4054. if (msAbs >= d) {
  4055. return plural(ms, msAbs, d, 'day');
  4056. }
  4057. if (msAbs >= h) {
  4058. return plural(ms, msAbs, h, 'hour');
  4059. }
  4060. if (msAbs >= m) {
  4061. return plural(ms, msAbs, m, 'minute');
  4062. }
  4063. if (msAbs >= s) {
  4064. return plural(ms, msAbs, s, 'second');
  4065. }
  4066. return ms + ' ms';
  4067. }
  4068. /**
  4069. * Pluralization helper.
  4070. */
  4071. function plural(ms, msAbs, n, name) {
  4072. var isPlural = msAbs >= n * 1.5;
  4073. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  4074. }
  4075. },{}],17:[function(require,module,exports){
  4076. (function (process){
  4077. /* eslint-env browser */
  4078. /**
  4079. * This is the web browser implementation of `debug()`.
  4080. */
  4081. exports.log = log;
  4082. exports.formatArgs = formatArgs;
  4083. exports.save = save;
  4084. exports.load = load;
  4085. exports.useColors = useColors;
  4086. exports.storage = localstorage();
  4087. /**
  4088. * Colors.
  4089. */
  4090. exports.colors = [
  4091. '#0000CC',
  4092. '#0000FF',
  4093. '#0033CC',
  4094. '#0033FF',
  4095. '#0066CC',
  4096. '#0066FF',
  4097. '#0099CC',
  4098. '#0099FF',
  4099. '#00CC00',
  4100. '#00CC33',
  4101. '#00CC66',
  4102. '#00CC99',
  4103. '#00CCCC',
  4104. '#00CCFF',
  4105. '#3300CC',
  4106. '#3300FF',
  4107. '#3333CC',
  4108. '#3333FF',
  4109. '#3366CC',
  4110. '#3366FF',
  4111. '#3399CC',
  4112. '#3399FF',
  4113. '#33CC00',
  4114. '#33CC33',
  4115. '#33CC66',
  4116. '#33CC99',
  4117. '#33CCCC',
  4118. '#33CCFF',
  4119. '#6600CC',
  4120. '#6600FF',
  4121. '#6633CC',
  4122. '#6633FF',
  4123. '#66CC00',
  4124. '#66CC33',
  4125. '#9900CC',
  4126. '#9900FF',
  4127. '#9933CC',
  4128. '#9933FF',
  4129. '#99CC00',
  4130. '#99CC33',
  4131. '#CC0000',
  4132. '#CC0033',
  4133. '#CC0066',
  4134. '#CC0099',
  4135. '#CC00CC',
  4136. '#CC00FF',
  4137. '#CC3300',
  4138. '#CC3333',
  4139. '#CC3366',
  4140. '#CC3399',
  4141. '#CC33CC',
  4142. '#CC33FF',
  4143. '#CC6600',
  4144. '#CC6633',
  4145. '#CC9900',
  4146. '#CC9933',
  4147. '#CCCC00',
  4148. '#CCCC33',
  4149. '#FF0000',
  4150. '#FF0033',
  4151. '#FF0066',
  4152. '#FF0099',
  4153. '#FF00CC',
  4154. '#FF00FF',
  4155. '#FF3300',
  4156. '#FF3333',
  4157. '#FF3366',
  4158. '#FF3399',
  4159. '#FF33CC',
  4160. '#FF33FF',
  4161. '#FF6600',
  4162. '#FF6633',
  4163. '#FF9900',
  4164. '#FF9933',
  4165. '#FFCC00',
  4166. '#FFCC33'
  4167. ];
  4168. /**
  4169. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  4170. * and the Firebug extension (any Firefox version) are known
  4171. * to support "%c" CSS customizations.
  4172. *
  4173. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  4174. */
  4175. // eslint-disable-next-line complexity
  4176. function useColors() {
  4177. // NB: In an Electron preload script, document will be defined but not fully
  4178. // initialized. Since we know we're in Chrome, we'll just detect this case
  4179. // explicitly
  4180. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  4181. return true;
  4182. }
  4183. // Internet Explorer and Edge do not support colors.
  4184. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  4185. return false;
  4186. }
  4187. // Is webkit? http://stackoverflow.com/a/16459606/376773
  4188. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  4189. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  4190. // Is firebug? http://stackoverflow.com/a/398120/376773
  4191. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  4192. // Is firefox >= v31?
  4193. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  4194. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  4195. // Double check webkit in userAgent just in case we are in a worker
  4196. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  4197. }
  4198. /**
  4199. * Colorize log arguments if enabled.
  4200. *
  4201. * @api public
  4202. */
  4203. function formatArgs(args) {
  4204. args[0] = (this.useColors ? '%c' : '') +
  4205. this.namespace +
  4206. (this.useColors ? ' %c' : ' ') +
  4207. args[0] +
  4208. (this.useColors ? '%c ' : ' ') +
  4209. '+' + module.exports.humanize(this.diff);
  4210. if (!this.useColors) {
  4211. return;
  4212. }
  4213. const c = 'color: ' + this.color;
  4214. args.splice(1, 0, c, 'color: inherit');
  4215. // The final "%c" is somewhat tricky, because there could be other
  4216. // arguments passed either before or after the %c, so we need to
  4217. // figure out the correct index to insert the CSS into
  4218. let index = 0;
  4219. let lastC = 0;
  4220. args[0].replace(/%[a-zA-Z%]/g, match => {
  4221. if (match === '%%') {
  4222. return;
  4223. }
  4224. index++;
  4225. if (match === '%c') {
  4226. // We only are interested in the *last* %c
  4227. // (the user may have provided their own)
  4228. lastC = index;
  4229. }
  4230. });
  4231. args.splice(lastC, 0, c);
  4232. }
  4233. /**
  4234. * Invokes `console.log()` when available.
  4235. * No-op when `console.log` is not a "function".
  4236. *
  4237. * @api public
  4238. */
  4239. function log(...args) {
  4240. // This hackery is required for IE8/9, where
  4241. // the `console.log` function doesn't have 'apply'
  4242. return typeof console === 'object' &&
  4243. console.log &&
  4244. console.log(...args);
  4245. }
  4246. /**
  4247. * Save `namespaces`.
  4248. *
  4249. * @param {String} namespaces
  4250. * @api private
  4251. */
  4252. function save(namespaces) {
  4253. try {
  4254. if (namespaces) {
  4255. exports.storage.setItem('debug', namespaces);
  4256. } else {
  4257. exports.storage.removeItem('debug');
  4258. }
  4259. } catch (error) {
  4260. // Swallow
  4261. // XXX (@Qix-) should we be logging these?
  4262. }
  4263. }
  4264. /**
  4265. * Load `namespaces`.
  4266. *
  4267. * @return {String} returns the previously persisted debug modes
  4268. * @api private
  4269. */
  4270. function load() {
  4271. let r;
  4272. try {
  4273. r = exports.storage.getItem('debug');
  4274. } catch (error) {
  4275. // Swallow
  4276. // XXX (@Qix-) should we be logging these?
  4277. }
  4278. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  4279. if (!r && typeof process !== 'undefined' && 'env' in process) {
  4280. r = process.env.DEBUG;
  4281. }
  4282. return r;
  4283. }
  4284. /**
  4285. * Localstorage attempts to return the localstorage.
  4286. *
  4287. * This is necessary because safari throws
  4288. * when a user disables cookies/localstorage
  4289. * and you attempt to access it.
  4290. *
  4291. * @return {LocalStorage}
  4292. * @api private
  4293. */
  4294. function localstorage() {
  4295. try {
  4296. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  4297. // The Browser also has localStorage in the global context.
  4298. return localStorage;
  4299. } catch (error) {
  4300. // Swallow
  4301. // XXX (@Qix-) should we be logging these?
  4302. }
  4303. }
  4304. module.exports = require('./common')(exports);
  4305. const {formatters} = module.exports;
  4306. /**
  4307. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  4308. */
  4309. formatters.j = function (v) {
  4310. try {
  4311. return JSON.stringify(v);
  4312. } catch (error) {
  4313. return '[UnexpectedJSONParseError]: ' + error.message;
  4314. }
  4315. };
  4316. }).call(this,require('_process'))
  4317. },{"./common":18,"_process":100}],18:[function(require,module,exports){
  4318. /**
  4319. * This is the common logic for both the Node.js and web browser
  4320. * implementations of `debug()`.
  4321. */
  4322. function setup(env) {
  4323. createDebug.debug = createDebug;
  4324. createDebug.default = createDebug;
  4325. createDebug.coerce = coerce;
  4326. createDebug.disable = disable;
  4327. createDebug.enable = enable;
  4328. createDebug.enabled = enabled;
  4329. createDebug.humanize = require('ms');
  4330. Object.keys(env).forEach(key => {
  4331. createDebug[key] = env[key];
  4332. });
  4333. /**
  4334. * Active `debug` instances.
  4335. */
  4336. createDebug.instances = [];
  4337. /**
  4338. * The currently active debug mode names, and names to skip.
  4339. */
  4340. createDebug.names = [];
  4341. createDebug.skips = [];
  4342. /**
  4343. * Map of special "%n" handling functions, for the debug "format" argument.
  4344. *
  4345. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  4346. */
  4347. createDebug.formatters = {};
  4348. /**
  4349. * Selects a color for a debug namespace
  4350. * @param {String} namespace The namespace string for the for the debug instance to be colored
  4351. * @return {Number|String} An ANSI color code for the given namespace
  4352. * @api private
  4353. */
  4354. function selectColor(namespace) {
  4355. let hash = 0;
  4356. for (let i = 0; i < namespace.length; i++) {
  4357. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  4358. hash |= 0; // Convert to 32bit integer
  4359. }
  4360. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  4361. }
  4362. createDebug.selectColor = selectColor;
  4363. /**
  4364. * Create a debugger with the given `namespace`.
  4365. *
  4366. * @param {String} namespace
  4367. * @return {Function}
  4368. * @api public
  4369. */
  4370. function createDebug(namespace) {
  4371. let prevTime;
  4372. function debug(...args) {
  4373. // Disabled?
  4374. if (!debug.enabled) {
  4375. return;
  4376. }
  4377. const self = debug;
  4378. // Set `diff` timestamp
  4379. const curr = Number(new Date());
  4380. const ms = curr - (prevTime || curr);
  4381. self.diff = ms;
  4382. self.prev = prevTime;
  4383. self.curr = curr;
  4384. prevTime = curr;
  4385. args[0] = createDebug.coerce(args[0]);
  4386. if (typeof args[0] !== 'string') {
  4387. // Anything else let's inspect with %O
  4388. args.unshift('%O');
  4389. }
  4390. // Apply any `formatters` transformations
  4391. let index = 0;
  4392. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  4393. // If we encounter an escaped % then don't increase the array index
  4394. if (match === '%%') {
  4395. return match;
  4396. }
  4397. index++;
  4398. const formatter = createDebug.formatters[format];
  4399. if (typeof formatter === 'function') {
  4400. const val = args[index];
  4401. match = formatter.call(self, val);
  4402. // Now we need to remove `args[index]` since it's inlined in the `format`
  4403. args.splice(index, 1);
  4404. index--;
  4405. }
  4406. return match;
  4407. });
  4408. // Apply env-specific formatting (colors, etc.)
  4409. createDebug.formatArgs.call(self, args);
  4410. const logFn = self.log || createDebug.log;
  4411. logFn.apply(self, args);
  4412. }
  4413. debug.namespace = namespace;
  4414. debug.enabled = createDebug.enabled(namespace);
  4415. debug.useColors = createDebug.useColors();
  4416. debug.color = selectColor(namespace);
  4417. debug.destroy = destroy;
  4418. debug.extend = extend;
  4419. // Debug.formatArgs = formatArgs;
  4420. // debug.rawLog = rawLog;
  4421. // env-specific initialization logic for debug instances
  4422. if (typeof createDebug.init === 'function') {
  4423. createDebug.init(debug);
  4424. }
  4425. createDebug.instances.push(debug);
  4426. return debug;
  4427. }
  4428. function destroy() {
  4429. const index = createDebug.instances.indexOf(this);
  4430. if (index !== -1) {
  4431. createDebug.instances.splice(index, 1);
  4432. return true;
  4433. }
  4434. return false;
  4435. }
  4436. function extend(namespace, delimiter) {
  4437. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  4438. newDebug.log = this.log;
  4439. return newDebug;
  4440. }
  4441. /**
  4442. * Enables a debug mode by namespaces. This can include modes
  4443. * separated by a colon and wildcards.
  4444. *
  4445. * @param {String} namespaces
  4446. * @api public
  4447. */
  4448. function enable(namespaces) {
  4449. createDebug.save(namespaces);
  4450. createDebug.names = [];
  4451. createDebug.skips = [];
  4452. let i;
  4453. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  4454. const len = split.length;
  4455. for (i = 0; i < len; i++) {
  4456. if (!split[i]) {
  4457. // ignore empty strings
  4458. continue;
  4459. }
  4460. namespaces = split[i].replace(/\*/g, '.*?');
  4461. if (namespaces[0] === '-') {
  4462. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  4463. } else {
  4464. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  4465. }
  4466. }
  4467. for (i = 0; i < createDebug.instances.length; i++) {
  4468. const instance = createDebug.instances[i];
  4469. instance.enabled = createDebug.enabled(instance.namespace);
  4470. }
  4471. }
  4472. /**
  4473. * Disable debug output.
  4474. *
  4475. * @return {String} namespaces
  4476. * @api public
  4477. */
  4478. function disable() {
  4479. const namespaces = [
  4480. ...createDebug.names.map(toNamespace),
  4481. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  4482. ].join(',');
  4483. createDebug.enable('');
  4484. return namespaces;
  4485. }
  4486. /**
  4487. * Returns true if the given mode name is enabled, false otherwise.
  4488. *
  4489. * @param {String} name
  4490. * @return {Boolean}
  4491. * @api public
  4492. */
  4493. function enabled(name) {
  4494. if (name[name.length - 1] === '*') {
  4495. return true;
  4496. }
  4497. let i;
  4498. let len;
  4499. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  4500. if (createDebug.skips[i].test(name)) {
  4501. return false;
  4502. }
  4503. }
  4504. for (i = 0, len = createDebug.names.length; i < len; i++) {
  4505. if (createDebug.names[i].test(name)) {
  4506. return true;
  4507. }
  4508. }
  4509. return false;
  4510. }
  4511. /**
  4512. * Convert regexp to namespace
  4513. *
  4514. * @param {RegExp} regxep
  4515. * @return {String} namespace
  4516. * @api private
  4517. */
  4518. function toNamespace(regexp) {
  4519. return regexp.toString()
  4520. .substring(2, regexp.toString().length - 2)
  4521. .replace(/\.\*\?$/, '*');
  4522. }
  4523. /**
  4524. * Coerce `val`.
  4525. *
  4526. * @param {Mixed} val
  4527. * @return {Mixed}
  4528. * @api private
  4529. */
  4530. function coerce(val) {
  4531. if (val instanceof Error) {
  4532. return val.stack || val.message;
  4533. }
  4534. return val;
  4535. }
  4536. createDebug.enable(createDebug.load());
  4537. return createDebug;
  4538. }
  4539. module.exports = setup;
  4540. },{"ms":16}],19:[function(require,module,exports){
  4541. (function (process,Buffer){
  4542. var stream = require('readable-stream')
  4543. var eos = require('end-of-stream')
  4544. var inherits = require('inherits')
  4545. var shift = require('stream-shift')
  4546. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  4547. ? Buffer.from([0])
  4548. : new Buffer([0])
  4549. var onuncork = function(self, fn) {
  4550. if (self._corked) self.once('uncork', fn)
  4551. else fn()
  4552. }
  4553. var autoDestroy = function (self, err) {
  4554. if (self._autoDestroy) self.destroy(err)
  4555. }
  4556. var destroyer = function(self, end) {
  4557. return function(err) {
  4558. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  4559. else if (end && !self._ended) self.end()
  4560. }
  4561. }
  4562. var end = function(ws, fn) {
  4563. if (!ws) return fn()
  4564. if (ws._writableState && ws._writableState.finished) return fn()
  4565. if (ws._writableState) return ws.end(fn)
  4566. ws.end()
  4567. fn()
  4568. }
  4569. var toStreams2 = function(rs) {
  4570. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  4571. }
  4572. var Duplexify = function(writable, readable, opts) {
  4573. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  4574. stream.Duplex.call(this, opts)
  4575. this._writable = null
  4576. this._readable = null
  4577. this._readable2 = null
  4578. this._autoDestroy = !opts || opts.autoDestroy !== false
  4579. this._forwardDestroy = !opts || opts.destroy !== false
  4580. this._forwardEnd = !opts || opts.end !== false
  4581. this._corked = 1 // start corked
  4582. this._ondrain = null
  4583. this._drained = false
  4584. this._forwarding = false
  4585. this._unwrite = null
  4586. this._unread = null
  4587. this._ended = false
  4588. this.destroyed = false
  4589. if (writable) this.setWritable(writable)
  4590. if (readable) this.setReadable(readable)
  4591. }
  4592. inherits(Duplexify, stream.Duplex)
  4593. Duplexify.obj = function(writable, readable, opts) {
  4594. if (!opts) opts = {}
  4595. opts.objectMode = true
  4596. opts.highWaterMark = 16
  4597. return new Duplexify(writable, readable, opts)
  4598. }
  4599. Duplexify.prototype.cork = function() {
  4600. if (++this._corked === 1) this.emit('cork')
  4601. }
  4602. Duplexify.prototype.uncork = function() {
  4603. if (this._corked && --this._corked === 0) this.emit('uncork')
  4604. }
  4605. Duplexify.prototype.setWritable = function(writable) {
  4606. if (this._unwrite) this._unwrite()
  4607. if (this.destroyed) {
  4608. if (writable && writable.destroy) writable.destroy()
  4609. return
  4610. }
  4611. if (writable === null || writable === false) {
  4612. this.end()
  4613. return
  4614. }
  4615. var self = this
  4616. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  4617. var ondrain = function() {
  4618. var ondrain = self._ondrain
  4619. self._ondrain = null
  4620. if (ondrain) ondrain()
  4621. }
  4622. var clear = function() {
  4623. self._writable.removeListener('drain', ondrain)
  4624. unend()
  4625. }
  4626. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  4627. this._writable = writable
  4628. this._writable.on('drain', ondrain)
  4629. this._unwrite = clear
  4630. this.uncork() // always uncork setWritable
  4631. }
  4632. Duplexify.prototype.setReadable = function(readable) {
  4633. if (this._unread) this._unread()
  4634. if (this.destroyed) {
  4635. if (readable && readable.destroy) readable.destroy()
  4636. return
  4637. }
  4638. if (readable === null || readable === false) {
  4639. this.push(null)
  4640. this.resume()
  4641. return
  4642. }
  4643. var self = this
  4644. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  4645. var onreadable = function() {
  4646. self._forward()
  4647. }
  4648. var onend = function() {
  4649. self.push(null)
  4650. }
  4651. var clear = function() {
  4652. self._readable2.removeListener('readable', onreadable)
  4653. self._readable2.removeListener('end', onend)
  4654. unend()
  4655. }
  4656. this._drained = true
  4657. this._readable = readable
  4658. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  4659. this._readable2.on('readable', onreadable)
  4660. this._readable2.on('end', onend)
  4661. this._unread = clear
  4662. this._forward()
  4663. }
  4664. Duplexify.prototype._read = function() {
  4665. this._drained = true
  4666. this._forward()
  4667. }
  4668. Duplexify.prototype._forward = function() {
  4669. if (this._forwarding || !this._readable2 || !this._drained) return
  4670. this._forwarding = true
  4671. var data
  4672. while (this._drained && (data = shift(this._readable2)) !== null) {
  4673. if (this.destroyed) continue
  4674. this._drained = this.push(data)
  4675. }
  4676. this._forwarding = false
  4677. }
  4678. Duplexify.prototype.destroy = function(err) {
  4679. if (this.destroyed) return
  4680. this.destroyed = true
  4681. var self = this
  4682. process.nextTick(function() {
  4683. self._destroy(err)
  4684. })
  4685. }
  4686. Duplexify.prototype._destroy = function(err) {
  4687. if (err) {
  4688. var ondrain = this._ondrain
  4689. this._ondrain = null
  4690. if (ondrain) ondrain(err)
  4691. else this.emit('error', err)
  4692. }
  4693. if (this._forwardDestroy) {
  4694. if (this._readable && this._readable.destroy) this._readable.destroy()
  4695. if (this._writable && this._writable.destroy) this._writable.destroy()
  4696. }
  4697. this.emit('close')
  4698. }
  4699. Duplexify.prototype._write = function(data, enc, cb) {
  4700. if (this.destroyed) return cb()
  4701. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  4702. if (data === SIGNAL_FLUSH) return this._finish(cb)
  4703. if (!this._writable) return cb()
  4704. if (this._writable.write(data) === false) this._ondrain = cb
  4705. else cb()
  4706. }
  4707. Duplexify.prototype._finish = function(cb) {
  4708. var self = this
  4709. this.emit('preend')
  4710. onuncork(this, function() {
  4711. end(self._forwardEnd && self._writable, function() {
  4712. // haxx to not emit prefinish twice
  4713. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  4714. self.emit('prefinish')
  4715. onuncork(self, cb)
  4716. })
  4717. })
  4718. }
  4719. Duplexify.prototype.end = function(data, enc, cb) {
  4720. if (typeof data === 'function') return this.end(null, null, data)
  4721. if (typeof enc === 'function') return this.end(data, null, enc)
  4722. this._ended = true
  4723. if (data) this.write(data)
  4724. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  4725. return stream.Writable.prototype.end.call(this, cb)
  4726. }
  4727. module.exports = Duplexify
  4728. }).call(this,require('_process'),require("buffer").Buffer)
  4729. },{"_process":100,"buffer":12,"end-of-stream":20,"inherits":88,"readable-stream":116,"stream-shift":119}],20:[function(require,module,exports){
  4730. var once = require('once');
  4731. var noop = function() {};
  4732. var isRequest = function(stream) {
  4733. return stream.setHeader && typeof stream.abort === 'function';
  4734. };
  4735. var isChildProcess = function(stream) {
  4736. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  4737. };
  4738. var eos = function(stream, opts, callback) {
  4739. if (typeof opts === 'function') return eos(stream, null, opts);
  4740. if (!opts) opts = {};
  4741. callback = once(callback || noop);
  4742. var ws = stream._writableState;
  4743. var rs = stream._readableState;
  4744. var readable = opts.readable || (opts.readable !== false && stream.readable);
  4745. var writable = opts.writable || (opts.writable !== false && stream.writable);
  4746. var onlegacyfinish = function() {
  4747. if (!stream.writable) onfinish();
  4748. };
  4749. var onfinish = function() {
  4750. writable = false;
  4751. if (!readable) callback.call(stream);
  4752. };
  4753. var onend = function() {
  4754. readable = false;
  4755. if (!writable) callback.call(stream);
  4756. };
  4757. var onexit = function(exitCode) {
  4758. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  4759. };
  4760. var onerror = function(err) {
  4761. callback.call(stream, err);
  4762. };
  4763. var onclose = function() {
  4764. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  4765. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  4766. };
  4767. var onrequest = function() {
  4768. stream.req.on('finish', onfinish);
  4769. };
  4770. if (isRequest(stream)) {
  4771. stream.on('complete', onfinish);
  4772. stream.on('abort', onclose);
  4773. if (stream.req) onrequest();
  4774. else stream.on('request', onrequest);
  4775. } else if (writable && !ws) { // legacy streams
  4776. stream.on('end', onlegacyfinish);
  4777. stream.on('close', onlegacyfinish);
  4778. }
  4779. if (isChildProcess(stream)) stream.on('exit', onexit);
  4780. stream.on('end', onend);
  4781. stream.on('finish', onfinish);
  4782. if (opts.error !== false) stream.on('error', onerror);
  4783. stream.on('close', onclose);
  4784. return function() {
  4785. stream.removeListener('complete', onfinish);
  4786. stream.removeListener('abort', onclose);
  4787. stream.removeListener('request', onrequest);
  4788. if (stream.req) stream.req.removeListener('finish', onfinish);
  4789. stream.removeListener('end', onlegacyfinish);
  4790. stream.removeListener('close', onlegacyfinish);
  4791. stream.removeListener('finish', onfinish);
  4792. stream.removeListener('exit', onexit);
  4793. stream.removeListener('end', onend);
  4794. stream.removeListener('error', onerror);
  4795. stream.removeListener('close', onclose);
  4796. };
  4797. };
  4798. module.exports = eos;
  4799. },{"once":98}],21:[function(require,module,exports){
  4800. // Inspired by Google Closure:
  4801. // http://closure-library.googlecode.com/svn/docs/
  4802. // closure_goog_array_array.js.html#goog.array.clear
  4803. "use strict";
  4804. var value = require("../../object/valid-value");
  4805. module.exports = function () {
  4806. value(this).length = 0;
  4807. return this;
  4808. };
  4809. },{"../../object/valid-value":56}],22:[function(require,module,exports){
  4810. "use strict";
  4811. var numberIsNaN = require("../../number/is-nan")
  4812. , toPosInt = require("../../number/to-pos-integer")
  4813. , value = require("../../object/valid-value")
  4814. , indexOf = Array.prototype.indexOf
  4815. , objHasOwnProperty = Object.prototype.hasOwnProperty
  4816. , abs = Math.abs
  4817. , floor = Math.floor;
  4818. module.exports = function (searchElement/*, fromIndex*/) {
  4819. var i, length, fromIndex, val;
  4820. if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
  4821. length = toPosInt(value(this).length);
  4822. fromIndex = arguments[1];
  4823. if (isNaN(fromIndex)) fromIndex = 0;
  4824. else if (fromIndex >= 0) fromIndex = floor(fromIndex);
  4825. else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
  4826. for (i = fromIndex; i < length; ++i) {
  4827. if (objHasOwnProperty.call(this, i)) {
  4828. val = this[i];
  4829. if (numberIsNaN(val)) return i; // Jslint: ignore
  4830. }
  4831. }
  4832. return -1;
  4833. };
  4834. },{"../../number/is-nan":32,"../../number/to-pos-integer":36,"../../object/valid-value":56}],23:[function(require,module,exports){
  4835. "use strict";
  4836. module.exports = require("./is-implemented")() ? Array.from : require("./shim");
  4837. },{"./is-implemented":24,"./shim":25}],24:[function(require,module,exports){
  4838. "use strict";
  4839. module.exports = function () {
  4840. var from = Array.from, arr, result;
  4841. if (typeof from !== "function") return false;
  4842. arr = ["raz", "dwa"];
  4843. result = from(arr);
  4844. return Boolean(result && result !== arr && result[1] === "dwa");
  4845. };
  4846. },{}],25:[function(require,module,exports){
  4847. "use strict";
  4848. var iteratorSymbol = require("es6-symbol").iterator
  4849. , isArguments = require("../../function/is-arguments")
  4850. , isFunction = require("../../function/is-function")
  4851. , toPosInt = require("../../number/to-pos-integer")
  4852. , callable = require("../../object/valid-callable")
  4853. , validValue = require("../../object/valid-value")
  4854. , isValue = require("../../object/is-value")
  4855. , isString = require("../../string/is-string")
  4856. , isArray = Array.isArray
  4857. , call = Function.prototype.call
  4858. , desc = { configurable: true, enumerable: true, writable: true, value: null }
  4859. , defineProperty = Object.defineProperty;
  4860. // eslint-disable-next-line complexity, max-lines-per-function
  4861. module.exports = function (arrayLike/*, mapFn, thisArg*/) {
  4862. var mapFn = arguments[1]
  4863. , thisArg = arguments[2]
  4864. , Context
  4865. , i
  4866. , j
  4867. , arr
  4868. , length
  4869. , code
  4870. , iterator
  4871. , result
  4872. , getIterator
  4873. , value;
  4874. arrayLike = Object(validValue(arrayLike));
  4875. if (isValue(mapFn)) callable(mapFn);
  4876. if (!this || this === Array || !isFunction(this)) {
  4877. // Result: Plain array
  4878. if (!mapFn) {
  4879. if (isArguments(arrayLike)) {
  4880. // Source: Arguments
  4881. length = arrayLike.length;
  4882. if (length !== 1) return Array.apply(null, arrayLike);
  4883. arr = new Array(1);
  4884. arr[0] = arrayLike[0];
  4885. return arr;
  4886. }
  4887. if (isArray(arrayLike)) {
  4888. // Source: Array
  4889. arr = new Array((length = arrayLike.length));
  4890. for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
  4891. return arr;
  4892. }
  4893. }
  4894. arr = [];
  4895. } else {
  4896. // Result: Non plain array
  4897. Context = this;
  4898. }
  4899. if (!isArray(arrayLike)) {
  4900. if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
  4901. // Source: Iterator
  4902. iterator = callable(getIterator).call(arrayLike);
  4903. if (Context) arr = new Context();
  4904. result = iterator.next();
  4905. i = 0;
  4906. while (!result.done) {
  4907. value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
  4908. if (Context) {
  4909. desc.value = value;
  4910. defineProperty(arr, i, desc);
  4911. } else {
  4912. arr[i] = value;
  4913. }
  4914. result = iterator.next();
  4915. ++i;
  4916. }
  4917. length = i;
  4918. } else if (isString(arrayLike)) {
  4919. // Source: String
  4920. length = arrayLike.length;
  4921. if (Context) arr = new Context();
  4922. for (i = 0, j = 0; i < length; ++i) {
  4923. value = arrayLike[i];
  4924. if (i + 1 < length) {
  4925. code = value.charCodeAt(0);
  4926. // eslint-disable-next-line max-depth
  4927. if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
  4928. }
  4929. value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
  4930. if (Context) {
  4931. desc.value = value;
  4932. defineProperty(arr, j, desc);
  4933. } else {
  4934. arr[j] = value;
  4935. }
  4936. ++j;
  4937. }
  4938. length = j;
  4939. }
  4940. }
  4941. if (length === undefined) {
  4942. // Source: array or array-like
  4943. length = toPosInt(arrayLike.length);
  4944. if (Context) arr = new Context(length);
  4945. for (i = 0; i < length; ++i) {
  4946. value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
  4947. if (Context) {
  4948. desc.value = value;
  4949. defineProperty(arr, i, desc);
  4950. } else {
  4951. arr[i] = value;
  4952. }
  4953. }
  4954. }
  4955. if (Context) {
  4956. desc.value = null;
  4957. arr.length = length;
  4958. }
  4959. return arr;
  4960. };
  4961. },{"../../function/is-arguments":26,"../../function/is-function":27,"../../number/to-pos-integer":36,"../../object/is-value":45,"../../object/valid-callable":55,"../../object/valid-value":56,"../../string/is-string":60,"es6-symbol":74}],26:[function(require,module,exports){
  4962. "use strict";
  4963. var objToString = Object.prototype.toString
  4964. , id = objToString.call((function () { return arguments; })());
  4965. module.exports = function (value) { return objToString.call(value) === id; };
  4966. },{}],27:[function(require,module,exports){
  4967. "use strict";
  4968. var objToString = Object.prototype.toString
  4969. , isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);
  4970. module.exports = function (value) {
  4971. return typeof value === "function" && isFunctionStringTag(objToString.call(value));
  4972. };
  4973. },{}],28:[function(require,module,exports){
  4974. "use strict";
  4975. // eslint-disable-next-line no-empty-function
  4976. module.exports = function () {};
  4977. },{}],29:[function(require,module,exports){
  4978. "use strict";
  4979. module.exports = require("./is-implemented")() ? Math.sign : require("./shim");
  4980. },{"./is-implemented":30,"./shim":31}],30:[function(require,module,exports){
  4981. "use strict";
  4982. module.exports = function () {
  4983. var sign = Math.sign;
  4984. if (typeof sign !== "function") return false;
  4985. return sign(10) === 1 && sign(-20) === -1;
  4986. };
  4987. },{}],31:[function(require,module,exports){
  4988. "use strict";
  4989. module.exports = function (value) {
  4990. value = Number(value);
  4991. if (isNaN(value) || value === 0) return value;
  4992. return value > 0 ? 1 : -1;
  4993. };
  4994. },{}],32:[function(require,module,exports){
  4995. "use strict";
  4996. module.exports = require("./is-implemented")() ? Number.isNaN : require("./shim");
  4997. },{"./is-implemented":33,"./shim":34}],33:[function(require,module,exports){
  4998. "use strict";
  4999. module.exports = function () {
  5000. var numberIsNaN = Number.isNaN;
  5001. if (typeof numberIsNaN !== "function") return false;
  5002. return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
  5003. };
  5004. },{}],34:[function(require,module,exports){
  5005. "use strict";
  5006. module.exports = function (value) {
  5007. // eslint-disable-next-line no-self-compare
  5008. return value !== value;
  5009. };
  5010. },{}],35:[function(require,module,exports){
  5011. "use strict";
  5012. var sign = require("../math/sign")
  5013. , abs = Math.abs
  5014. , floor = Math.floor;
  5015. module.exports = function (value) {
  5016. if (isNaN(value)) return 0;
  5017. value = Number(value);
  5018. if (value === 0 || !isFinite(value)) return value;
  5019. return sign(value) * floor(abs(value));
  5020. };
  5021. },{"../math/sign":29}],36:[function(require,module,exports){
  5022. "use strict";
  5023. var toInteger = require("./to-integer")
  5024. , max = Math.max;
  5025. module.exports = function (value) { return max(0, toInteger(value)); };
  5026. },{"./to-integer":35}],37:[function(require,module,exports){
  5027. // Internal method, used by iteration functions.
  5028. // Calls a function for each key-value pair found in object
  5029. // Optionally takes compareFn to iterate object in specific order
  5030. "use strict";
  5031. var callable = require("./valid-callable")
  5032. , value = require("./valid-value")
  5033. , bind = Function.prototype.bind
  5034. , call = Function.prototype.call
  5035. , keys = Object.keys
  5036. , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
  5037. module.exports = function (method, defVal) {
  5038. return function (obj, cb/*, thisArg, compareFn*/) {
  5039. var list, thisArg = arguments[2], compareFn = arguments[3];
  5040. obj = Object(value(obj));
  5041. callable(cb);
  5042. list = keys(obj);
  5043. if (compareFn) {
  5044. list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
  5045. }
  5046. if (typeof method !== "function") method = list[method];
  5047. return call.call(method, list, function (key, index) {
  5048. if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
  5049. return call.call(cb, thisArg, obj[key], key, obj, index);
  5050. });
  5051. };
  5052. };
  5053. },{"./valid-callable":55,"./valid-value":56}],38:[function(require,module,exports){
  5054. "use strict";
  5055. module.exports = require("./is-implemented")() ? Object.assign : require("./shim");
  5056. },{"./is-implemented":39,"./shim":40}],39:[function(require,module,exports){
  5057. "use strict";
  5058. module.exports = function () {
  5059. var assign = Object.assign, obj;
  5060. if (typeof assign !== "function") return false;
  5061. obj = { foo: "raz" };
  5062. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  5063. return obj.foo + obj.bar + obj.trzy === "razdwatrzy";
  5064. };
  5065. },{}],40:[function(require,module,exports){
  5066. "use strict";
  5067. var keys = require("../keys")
  5068. , value = require("../valid-value")
  5069. , max = Math.max;
  5070. module.exports = function (dest, src/*, …srcn*/) {
  5071. var error, i, length = max(arguments.length, 2), assign;
  5072. dest = Object(value(dest));
  5073. assign = function (key) {
  5074. try {
  5075. dest[key] = src[key];
  5076. } catch (e) {
  5077. if (!error) error = e;
  5078. }
  5079. };
  5080. for (i = 1; i < length; ++i) {
  5081. src = arguments[i];
  5082. keys(src).forEach(assign);
  5083. }
  5084. if (error !== undefined) throw error;
  5085. return dest;
  5086. };
  5087. },{"../keys":46,"../valid-value":56}],41:[function(require,module,exports){
  5088. "use strict";
  5089. var aFrom = require("../array/from")
  5090. , assign = require("./assign")
  5091. , value = require("./valid-value");
  5092. module.exports = function (obj/*, propertyNames, options*/) {
  5093. var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
  5094. if (copy !== obj && !propertyNames) return copy;
  5095. var result = {};
  5096. if (propertyNames) {
  5097. aFrom(propertyNames, function (propertyName) {
  5098. if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
  5099. });
  5100. } else {
  5101. assign(result, obj);
  5102. }
  5103. return result;
  5104. };
  5105. },{"../array/from":23,"./assign":38,"./valid-value":56}],42:[function(require,module,exports){
  5106. // Workaround for http://code.google.com/p/v8/issues/detail?id=2804
  5107. "use strict";
  5108. var create = Object.create, shim;
  5109. if (!require("./set-prototype-of/is-implemented")()) {
  5110. shim = require("./set-prototype-of/shim");
  5111. }
  5112. module.exports = (function () {
  5113. var nullObject, polyProps, desc;
  5114. if (!shim) return create;
  5115. if (shim.level !== 1) return create;
  5116. nullObject = {};
  5117. polyProps = {};
  5118. desc = { configurable: false, enumerable: false, writable: true, value: undefined };
  5119. Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
  5120. if (name === "__proto__") {
  5121. polyProps[name] = {
  5122. configurable: true,
  5123. enumerable: false,
  5124. writable: true,
  5125. value: undefined
  5126. };
  5127. return;
  5128. }
  5129. polyProps[name] = desc;
  5130. });
  5131. Object.defineProperties(nullObject, polyProps);
  5132. Object.defineProperty(shim, "nullPolyfill", {
  5133. configurable: false,
  5134. enumerable: false,
  5135. writable: false,
  5136. value: nullObject
  5137. });
  5138. return function (prototype, props) {
  5139. return create(prototype === null ? nullObject : prototype, props);
  5140. };
  5141. })();
  5142. },{"./set-prototype-of/is-implemented":53,"./set-prototype-of/shim":54}],43:[function(require,module,exports){
  5143. "use strict";
  5144. module.exports = require("./_iterate")("forEach");
  5145. },{"./_iterate":37}],44:[function(require,module,exports){
  5146. "use strict";
  5147. var isValue = require("./is-value");
  5148. var map = { function: true, object: true };
  5149. module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; };
  5150. },{"./is-value":45}],45:[function(require,module,exports){
  5151. "use strict";
  5152. var _undefined = require("../function/noop")(); // Support ES3 engines
  5153. module.exports = function (val) { return val !== _undefined && val !== null; };
  5154. },{"../function/noop":28}],46:[function(require,module,exports){
  5155. "use strict";
  5156. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  5157. },{"./is-implemented":47,"./shim":48}],47:[function(require,module,exports){
  5158. "use strict";
  5159. module.exports = function () {
  5160. try {
  5161. Object.keys("primitive");
  5162. return true;
  5163. } catch (e) {
  5164. return false;
  5165. }
  5166. };
  5167. },{}],48:[function(require,module,exports){
  5168. "use strict";
  5169. var isValue = require("../is-value");
  5170. var keys = Object.keys;
  5171. module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
  5172. },{"../is-value":45}],49:[function(require,module,exports){
  5173. "use strict";
  5174. var callable = require("./valid-callable")
  5175. , forEach = require("./for-each")
  5176. , call = Function.prototype.call;
  5177. module.exports = function (obj, cb/*, thisArg*/) {
  5178. var result = {}, thisArg = arguments[2];
  5179. callable(cb);
  5180. forEach(obj, function (value, key, targetObj, index) {
  5181. result[key] = call.call(cb, thisArg, value, key, targetObj, index);
  5182. });
  5183. return result;
  5184. };
  5185. },{"./for-each":43,"./valid-callable":55}],50:[function(require,module,exports){
  5186. "use strict";
  5187. var isValue = require("./is-value");
  5188. var forEach = Array.prototype.forEach, create = Object.create;
  5189. var process = function (src, obj) {
  5190. var key;
  5191. for (key in src) obj[key] = src[key];
  5192. };
  5193. // eslint-disable-next-line no-unused-vars
  5194. module.exports = function (opts1/*, …options*/) {
  5195. var result = create(null);
  5196. forEach.call(arguments, function (options) {
  5197. if (!isValue(options)) return;
  5198. process(Object(options), result);
  5199. });
  5200. return result;
  5201. };
  5202. },{"./is-value":45}],51:[function(require,module,exports){
  5203. "use strict";
  5204. var forEach = Array.prototype.forEach, create = Object.create;
  5205. // eslint-disable-next-line no-unused-vars
  5206. module.exports = function (arg/*, …args*/) {
  5207. var set = create(null);
  5208. forEach.call(arguments, function (name) { set[name] = true; });
  5209. return set;
  5210. };
  5211. },{}],52:[function(require,module,exports){
  5212. "use strict";
  5213. module.exports = require("./is-implemented")() ? Object.setPrototypeOf : require("./shim");
  5214. },{"./is-implemented":53,"./shim":54}],53:[function(require,module,exports){
  5215. "use strict";
  5216. var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
  5217. module.exports = function (/* CustomCreate*/) {
  5218. var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
  5219. if (typeof setPrototypeOf !== "function") return false;
  5220. return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
  5221. };
  5222. },{}],54:[function(require,module,exports){
  5223. /* eslint no-proto: "off" */
  5224. // Big thanks to @WebReflection for sorting this out
  5225. // https://gist.github.com/WebReflection/5593554
  5226. "use strict";
  5227. var isObject = require("../is-object")
  5228. , value = require("../valid-value")
  5229. , objIsPrototypeOf = Object.prototype.isPrototypeOf
  5230. , defineProperty = Object.defineProperty
  5231. , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined }
  5232. , validate;
  5233. validate = function (obj, prototype) {
  5234. value(obj);
  5235. if (prototype === null || isObject(prototype)) return obj;
  5236. throw new TypeError("Prototype must be null or an object");
  5237. };
  5238. module.exports = (function (status) {
  5239. var fn, set;
  5240. if (!status) return null;
  5241. if (status.level === 2) {
  5242. if (status.set) {
  5243. set = status.set;
  5244. fn = function (obj, prototype) {
  5245. set.call(validate(obj, prototype), prototype);
  5246. return obj;
  5247. };
  5248. } else {
  5249. fn = function (obj, prototype) {
  5250. validate(obj, prototype).__proto__ = prototype;
  5251. return obj;
  5252. };
  5253. }
  5254. } else {
  5255. fn = function self(obj, prototype) {
  5256. var isNullBase;
  5257. validate(obj, prototype);
  5258. isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
  5259. if (isNullBase) delete self.nullPolyfill.__proto__;
  5260. if (prototype === null) prototype = self.nullPolyfill;
  5261. obj.__proto__ = prototype;
  5262. if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
  5263. return obj;
  5264. };
  5265. }
  5266. return Object.defineProperty(fn, "level", {
  5267. configurable: false,
  5268. enumerable: false,
  5269. writable: false,
  5270. value: status.level
  5271. });
  5272. })(
  5273. (function () {
  5274. var tmpObj1 = Object.create(null)
  5275. , tmpObj2 = {}
  5276. , set
  5277. , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
  5278. if (desc) {
  5279. try {
  5280. set = desc.set; // Opera crashes at this point
  5281. set.call(tmpObj1, tmpObj2);
  5282. } catch (ignore) {}
  5283. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
  5284. }
  5285. tmpObj1.__proto__ = tmpObj2;
  5286. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
  5287. tmpObj1 = {};
  5288. tmpObj1.__proto__ = tmpObj2;
  5289. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
  5290. return false;
  5291. })()
  5292. );
  5293. require("../create");
  5294. },{"../create":42,"../is-object":44,"../valid-value":56}],55:[function(require,module,exports){
  5295. "use strict";
  5296. module.exports = function (fn) {
  5297. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  5298. return fn;
  5299. };
  5300. },{}],56:[function(require,module,exports){
  5301. "use strict";
  5302. var isValue = require("./is-value");
  5303. module.exports = function (value) {
  5304. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  5305. return value;
  5306. };
  5307. },{"./is-value":45}],57:[function(require,module,exports){
  5308. "use strict";
  5309. module.exports = require("./is-implemented")() ? String.prototype.contains : require("./shim");
  5310. },{"./is-implemented":58,"./shim":59}],58:[function(require,module,exports){
  5311. "use strict";
  5312. var str = "razdwatrzy";
  5313. module.exports = function () {
  5314. if (typeof str.contains !== "function") return false;
  5315. return str.contains("dwa") === true && str.contains("foo") === false;
  5316. };
  5317. },{}],59:[function(require,module,exports){
  5318. "use strict";
  5319. var indexOf = String.prototype.indexOf;
  5320. module.exports = function (searchString/*, position*/) {
  5321. return indexOf.call(this, searchString, arguments[1]) > -1;
  5322. };
  5323. },{}],60:[function(require,module,exports){
  5324. "use strict";
  5325. var objToString = Object.prototype.toString, id = objToString.call("");
  5326. module.exports = function (value) {
  5327. return (
  5328. typeof value === "string" ||
  5329. (value &&
  5330. typeof value === "object" &&
  5331. (value instanceof String || objToString.call(value) === id)) ||
  5332. false
  5333. );
  5334. };
  5335. },{}],61:[function(require,module,exports){
  5336. "use strict";
  5337. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5338. , contains = require("es5-ext/string/#/contains")
  5339. , d = require("d")
  5340. , Symbol = require("es6-symbol")
  5341. , Iterator = require("./");
  5342. var defineProperty = Object.defineProperty, ArrayIterator;
  5343. ArrayIterator = module.exports = function (arr, kind) {
  5344. if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
  5345. Iterator.call(this, arr);
  5346. if (!kind) kind = "value";
  5347. else if (contains.call(kind, "key+value")) kind = "key+value";
  5348. else if (contains.call(kind, "key")) kind = "key";
  5349. else kind = "value";
  5350. defineProperty(this, "__kind__", d("", kind));
  5351. };
  5352. if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
  5353. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5354. delete ArrayIterator.prototype.constructor;
  5355. ArrayIterator.prototype = Object.create(Iterator.prototype, {
  5356. _resolve: d(function (i) {
  5357. if (this.__kind__ === "value") return this.__list__[i];
  5358. if (this.__kind__ === "key+value") return [i, this.__list__[i]];
  5359. return i;
  5360. })
  5361. });
  5362. defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
  5363. },{"./":64,"d":15,"es5-ext/object/set-prototype-of":52,"es5-ext/string/#/contains":57,"es6-symbol":74}],62:[function(require,module,exports){
  5364. "use strict";
  5365. var isArguments = require("es5-ext/function/is-arguments")
  5366. , callable = require("es5-ext/object/valid-callable")
  5367. , isString = require("es5-ext/string/is-string")
  5368. , get = require("./get");
  5369. var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
  5370. module.exports = function (iterable, cb /*, thisArg*/) {
  5371. var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
  5372. if (isArray(iterable) || isArguments(iterable)) mode = "array";
  5373. else if (isString(iterable)) mode = "string";
  5374. else iterable = get(iterable);
  5375. callable(cb);
  5376. doBreak = function () {
  5377. broken = true;
  5378. };
  5379. if (mode === "array") {
  5380. some.call(iterable, function (value) {
  5381. call.call(cb, thisArg, value, doBreak);
  5382. return broken;
  5383. });
  5384. return;
  5385. }
  5386. if (mode === "string") {
  5387. length = iterable.length;
  5388. for (i = 0; i < length; ++i) {
  5389. char = iterable[i];
  5390. if (i + 1 < length) {
  5391. code = char.charCodeAt(0);
  5392. if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
  5393. }
  5394. call.call(cb, thisArg, char, doBreak);
  5395. if (broken) break;
  5396. }
  5397. return;
  5398. }
  5399. result = iterable.next();
  5400. while (!result.done) {
  5401. call.call(cb, thisArg, result.value, doBreak);
  5402. if (broken) return;
  5403. result = iterable.next();
  5404. }
  5405. };
  5406. },{"./get":63,"es5-ext/function/is-arguments":26,"es5-ext/object/valid-callable":55,"es5-ext/string/is-string":60}],63:[function(require,module,exports){
  5407. "use strict";
  5408. var isArguments = require("es5-ext/function/is-arguments")
  5409. , isString = require("es5-ext/string/is-string")
  5410. , ArrayIterator = require("./array")
  5411. , StringIterator = require("./string")
  5412. , iterable = require("./valid-iterable")
  5413. , iteratorSymbol = require("es6-symbol").iterator;
  5414. module.exports = function (obj) {
  5415. if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
  5416. if (isArguments(obj)) return new ArrayIterator(obj);
  5417. if (isString(obj)) return new StringIterator(obj);
  5418. return new ArrayIterator(obj);
  5419. };
  5420. },{"./array":61,"./string":66,"./valid-iterable":67,"es5-ext/function/is-arguments":26,"es5-ext/string/is-string":60,"es6-symbol":74}],64:[function(require,module,exports){
  5421. "use strict";
  5422. var clear = require("es5-ext/array/#/clear")
  5423. , assign = require("es5-ext/object/assign")
  5424. , callable = require("es5-ext/object/valid-callable")
  5425. , value = require("es5-ext/object/valid-value")
  5426. , d = require("d")
  5427. , autoBind = require("d/auto-bind")
  5428. , Symbol = require("es6-symbol");
  5429. var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
  5430. module.exports = Iterator = function (list, context) {
  5431. if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
  5432. defineProperties(this, {
  5433. __list__: d("w", value(list)),
  5434. __context__: d("w", context),
  5435. __nextIndex__: d("w", 0)
  5436. });
  5437. if (!context) return;
  5438. callable(context.on);
  5439. context.on("_add", this._onAdd);
  5440. context.on("_delete", this._onDelete);
  5441. context.on("_clear", this._onClear);
  5442. };
  5443. // Internal %IteratorPrototype% doesn't expose its constructor
  5444. delete Iterator.prototype.constructor;
  5445. defineProperties(
  5446. Iterator.prototype,
  5447. assign(
  5448. {
  5449. _next: d(function () {
  5450. var i;
  5451. if (!this.__list__) return undefined;
  5452. if (this.__redo__) {
  5453. i = this.__redo__.shift();
  5454. if (i !== undefined) return i;
  5455. }
  5456. if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
  5457. this._unBind();
  5458. return undefined;
  5459. }),
  5460. next: d(function () {
  5461. return this._createResult(this._next());
  5462. }),
  5463. _createResult: d(function (i) {
  5464. if (i === undefined) return { done: true, value: undefined };
  5465. return { done: false, value: this._resolve(i) };
  5466. }),
  5467. _resolve: d(function (i) {
  5468. return this.__list__[i];
  5469. }),
  5470. _unBind: d(function () {
  5471. this.__list__ = null;
  5472. delete this.__redo__;
  5473. if (!this.__context__) return;
  5474. this.__context__.off("_add", this._onAdd);
  5475. this.__context__.off("_delete", this._onDelete);
  5476. this.__context__.off("_clear", this._onClear);
  5477. this.__context__ = null;
  5478. }),
  5479. toString: d(function () {
  5480. return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
  5481. })
  5482. },
  5483. autoBind({
  5484. _onAdd: d(function (index) {
  5485. if (index >= this.__nextIndex__) return;
  5486. ++this.__nextIndex__;
  5487. if (!this.__redo__) {
  5488. defineProperty(this, "__redo__", d("c", [index]));
  5489. return;
  5490. }
  5491. this.__redo__.forEach(function (redo, i) {
  5492. if (redo >= index) this.__redo__[i] = ++redo;
  5493. }, this);
  5494. this.__redo__.push(index);
  5495. }),
  5496. _onDelete: d(function (index) {
  5497. var i;
  5498. if (index >= this.__nextIndex__) return;
  5499. --this.__nextIndex__;
  5500. if (!this.__redo__) return;
  5501. i = this.__redo__.indexOf(index);
  5502. if (i !== -1) this.__redo__.splice(i, 1);
  5503. this.__redo__.forEach(function (redo, j) {
  5504. if (redo > index) this.__redo__[j] = --redo;
  5505. }, this);
  5506. }),
  5507. _onClear: d(function () {
  5508. if (this.__redo__) clear.call(this.__redo__);
  5509. this.__nextIndex__ = 0;
  5510. })
  5511. })
  5512. )
  5513. );
  5514. defineProperty(
  5515. Iterator.prototype,
  5516. Symbol.iterator,
  5517. d(function () {
  5518. return this;
  5519. })
  5520. );
  5521. },{"d":15,"d/auto-bind":14,"es5-ext/array/#/clear":21,"es5-ext/object/assign":38,"es5-ext/object/valid-callable":55,"es5-ext/object/valid-value":56,"es6-symbol":74}],65:[function(require,module,exports){
  5522. "use strict";
  5523. var isArguments = require("es5-ext/function/is-arguments")
  5524. , isValue = require("es5-ext/object/is-value")
  5525. , isString = require("es5-ext/string/is-string");
  5526. var iteratorSymbol = require("es6-symbol").iterator
  5527. , isArray = Array.isArray;
  5528. module.exports = function (value) {
  5529. if (!isValue(value)) return false;
  5530. if (isArray(value)) return true;
  5531. if (isString(value)) return true;
  5532. if (isArguments(value)) return true;
  5533. return typeof value[iteratorSymbol] === "function";
  5534. };
  5535. },{"es5-ext/function/is-arguments":26,"es5-ext/object/is-value":45,"es5-ext/string/is-string":60,"es6-symbol":74}],66:[function(require,module,exports){
  5536. // Thanks @mathiasbynens
  5537. // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
  5538. "use strict";
  5539. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5540. , d = require("d")
  5541. , Symbol = require("es6-symbol")
  5542. , Iterator = require("./");
  5543. var defineProperty = Object.defineProperty, StringIterator;
  5544. StringIterator = module.exports = function (str) {
  5545. if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
  5546. str = String(str);
  5547. Iterator.call(this, str);
  5548. defineProperty(this, "__length__", d("", str.length));
  5549. };
  5550. if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
  5551. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5552. delete StringIterator.prototype.constructor;
  5553. StringIterator.prototype = Object.create(Iterator.prototype, {
  5554. _next: d(function () {
  5555. if (!this.__list__) return undefined;
  5556. if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
  5557. this._unBind();
  5558. return undefined;
  5559. }),
  5560. _resolve: d(function (i) {
  5561. var char = this.__list__[i], code;
  5562. if (this.__nextIndex__ === this.__length__) return char;
  5563. code = char.charCodeAt(0);
  5564. if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
  5565. return char;
  5566. })
  5567. });
  5568. defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
  5569. },{"./":64,"d":15,"es5-ext/object/set-prototype-of":52,"es6-symbol":74}],67:[function(require,module,exports){
  5570. "use strict";
  5571. var isIterable = require("./is-iterable");
  5572. module.exports = function (value) {
  5573. if (!isIterable(value)) throw new TypeError(value + " is not iterable");
  5574. return value;
  5575. };
  5576. },{"./is-iterable":65}],68:[function(require,module,exports){
  5577. 'use strict';
  5578. module.exports = require('./is-implemented')() ? Map : require('./polyfill');
  5579. },{"./is-implemented":69,"./polyfill":73}],69:[function(require,module,exports){
  5580. 'use strict';
  5581. module.exports = function () {
  5582. var map, iterator, result;
  5583. if (typeof Map !== 'function') return false;
  5584. try {
  5585. // WebKit doesn't support arguments and crashes
  5586. map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
  5587. } catch (e) {
  5588. return false;
  5589. }
  5590. if (String(map) !== '[object Map]') return false;
  5591. if (map.size !== 3) return false;
  5592. if (typeof map.clear !== 'function') return false;
  5593. if (typeof map.delete !== 'function') return false;
  5594. if (typeof map.entries !== 'function') return false;
  5595. if (typeof map.forEach !== 'function') return false;
  5596. if (typeof map.get !== 'function') return false;
  5597. if (typeof map.has !== 'function') return false;
  5598. if (typeof map.keys !== 'function') return false;
  5599. if (typeof map.set !== 'function') return false;
  5600. if (typeof map.values !== 'function') return false;
  5601. iterator = map.entries();
  5602. result = iterator.next();
  5603. if (result.done !== false) return false;
  5604. if (!result.value) return false;
  5605. if (result.value[0] !== 'raz') return false;
  5606. if (result.value[1] !== 'one') return false;
  5607. return true;
  5608. };
  5609. },{}],70:[function(require,module,exports){
  5610. // Exports true if environment provides native `Map` implementation,
  5611. // whatever that is.
  5612. 'use strict';
  5613. module.exports = (function () {
  5614. if (typeof Map === 'undefined') return false;
  5615. return (Object.prototype.toString.call(new Map()) === '[object Map]');
  5616. }());
  5617. },{}],71:[function(require,module,exports){
  5618. 'use strict';
  5619. module.exports = require('es5-ext/object/primitive-set')('key',
  5620. 'value', 'key+value');
  5621. },{"es5-ext/object/primitive-set":51}],72:[function(require,module,exports){
  5622. 'use strict';
  5623. var setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5624. , d = require('d')
  5625. , Iterator = require('es6-iterator')
  5626. , toStringTagSymbol = require('es6-symbol').toStringTag
  5627. , kinds = require('./iterator-kinds')
  5628. , defineProperties = Object.defineProperties
  5629. , unBind = Iterator.prototype._unBind
  5630. , MapIterator;
  5631. MapIterator = module.exports = function (map, kind) {
  5632. if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
  5633. Iterator.call(this, map.__mapKeysData__, map);
  5634. if (!kind || !kinds[kind]) kind = 'key+value';
  5635. defineProperties(this, {
  5636. __kind__: d('', kind),
  5637. __values__: d('w', map.__mapValuesData__)
  5638. });
  5639. };
  5640. if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
  5641. MapIterator.prototype = Object.create(Iterator.prototype, {
  5642. constructor: d(MapIterator),
  5643. _resolve: d(function (i) {
  5644. if (this.__kind__ === 'value') return this.__values__[i];
  5645. if (this.__kind__ === 'key') return this.__list__[i];
  5646. return [this.__list__[i], this.__values__[i]];
  5647. }),
  5648. _unBind: d(function () {
  5649. this.__values__ = null;
  5650. unBind.call(this);
  5651. }),
  5652. toString: d(function () { return '[object Map Iterator]'; })
  5653. });
  5654. Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
  5655. d('c', 'Map Iterator'));
  5656. },{"./iterator-kinds":71,"d":15,"es5-ext/object/set-prototype-of":52,"es6-iterator":64,"es6-symbol":74}],73:[function(require,module,exports){
  5657. 'use strict';
  5658. var clear = require('es5-ext/array/#/clear')
  5659. , eIndexOf = require('es5-ext/array/#/e-index-of')
  5660. , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5661. , callable = require('es5-ext/object/valid-callable')
  5662. , validValue = require('es5-ext/object/valid-value')
  5663. , d = require('d')
  5664. , ee = require('event-emitter')
  5665. , Symbol = require('es6-symbol')
  5666. , iterator = require('es6-iterator/valid-iterable')
  5667. , forOf = require('es6-iterator/for-of')
  5668. , Iterator = require('./lib/iterator')
  5669. , isNative = require('./is-native-implemented')
  5670. , call = Function.prototype.call
  5671. , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf
  5672. , MapPoly;
  5673. module.exports = MapPoly = function (/*iterable*/) {
  5674. var iterable = arguments[0], keys, values, self;
  5675. if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\'');
  5676. if (isNative && setPrototypeOf && (Map !== MapPoly)) {
  5677. self = setPrototypeOf(new Map(), getPrototypeOf(this));
  5678. } else {
  5679. self = this;
  5680. }
  5681. if (iterable != null) iterator(iterable);
  5682. defineProperties(self, {
  5683. __mapKeysData__: d('c', keys = []),
  5684. __mapValuesData__: d('c', values = [])
  5685. });
  5686. if (!iterable) return self;
  5687. forOf(iterable, function (value) {
  5688. var key = validValue(value)[0];
  5689. value = value[1];
  5690. if (eIndexOf.call(keys, key) !== -1) return;
  5691. keys.push(key);
  5692. values.push(value);
  5693. }, self);
  5694. return self;
  5695. };
  5696. if (isNative) {
  5697. if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
  5698. MapPoly.prototype = Object.create(Map.prototype, {
  5699. constructor: d(MapPoly)
  5700. });
  5701. }
  5702. ee(defineProperties(MapPoly.prototype, {
  5703. clear: d(function () {
  5704. if (!this.__mapKeysData__.length) return;
  5705. clear.call(this.__mapKeysData__);
  5706. clear.call(this.__mapValuesData__);
  5707. this.emit('_clear');
  5708. }),
  5709. delete: d(function (key) {
  5710. var index = eIndexOf.call(this.__mapKeysData__, key);
  5711. if (index === -1) return false;
  5712. this.__mapKeysData__.splice(index, 1);
  5713. this.__mapValuesData__.splice(index, 1);
  5714. this.emit('_delete', index, key);
  5715. return true;
  5716. }),
  5717. entries: d(function () { return new Iterator(this, 'key+value'); }),
  5718. forEach: d(function (cb/*, thisArg*/) {
  5719. var thisArg = arguments[1], iterator, result;
  5720. callable(cb);
  5721. iterator = this.entries();
  5722. result = iterator._next();
  5723. while (result !== undefined) {
  5724. call.call(cb, thisArg, this.__mapValuesData__[result],
  5725. this.__mapKeysData__[result], this);
  5726. result = iterator._next();
  5727. }
  5728. }),
  5729. get: d(function (key) {
  5730. var index = eIndexOf.call(this.__mapKeysData__, key);
  5731. if (index === -1) return;
  5732. return this.__mapValuesData__[index];
  5733. }),
  5734. has: d(function (key) {
  5735. return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
  5736. }),
  5737. keys: d(function () { return new Iterator(this, 'key'); }),
  5738. set: d(function (key, value) {
  5739. var index = eIndexOf.call(this.__mapKeysData__, key), emit;
  5740. if (index === -1) {
  5741. index = this.__mapKeysData__.push(key) - 1;
  5742. emit = true;
  5743. }
  5744. this.__mapValuesData__[index] = value;
  5745. if (emit) this.emit('_add', index, key);
  5746. return this;
  5747. }),
  5748. size: d.gs(function () { return this.__mapKeysData__.length; }),
  5749. values: d(function () { return new Iterator(this, 'value'); }),
  5750. toString: d(function () { return '[object Map]'; })
  5751. }));
  5752. Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
  5753. return this.entries();
  5754. }));
  5755. Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
  5756. },{"./is-native-implemented":70,"./lib/iterator":72,"d":15,"es5-ext/array/#/clear":21,"es5-ext/array/#/e-index-of":22,"es5-ext/object/set-prototype-of":52,"es5-ext/object/valid-callable":55,"es5-ext/object/valid-value":56,"es6-iterator/for-of":62,"es6-iterator/valid-iterable":67,"es6-symbol":74,"event-emitter":82}],74:[function(require,module,exports){
  5757. "use strict";
  5758. module.exports = require("./is-implemented")()
  5759. ? require("ext/global-this").Symbol
  5760. : require("./polyfill");
  5761. },{"./is-implemented":75,"./polyfill":80,"ext/global-this":85}],75:[function(require,module,exports){
  5762. "use strict";
  5763. var global = require("ext/global-this")
  5764. , validTypes = { object: true, symbol: true };
  5765. module.exports = function () {
  5766. var Symbol = global.Symbol;
  5767. var symbol;
  5768. if (typeof Symbol !== "function") return false;
  5769. symbol = Symbol("test symbol");
  5770. try { String(symbol); }
  5771. catch (e) { return false; }
  5772. // Return 'true' also for polyfills
  5773. if (!validTypes[typeof Symbol.iterator]) return false;
  5774. if (!validTypes[typeof Symbol.toPrimitive]) return false;
  5775. if (!validTypes[typeof Symbol.toStringTag]) return false;
  5776. return true;
  5777. };
  5778. },{"ext/global-this":85}],76:[function(require,module,exports){
  5779. "use strict";
  5780. module.exports = function (value) {
  5781. if (!value) return false;
  5782. if (typeof value === "symbol") return true;
  5783. if (!value.constructor) return false;
  5784. if (value.constructor.name !== "Symbol") return false;
  5785. return value[value.constructor.toStringTag] === "Symbol";
  5786. };
  5787. },{}],77:[function(require,module,exports){
  5788. "use strict";
  5789. var d = require("d");
  5790. var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype;
  5791. var created = create(null);
  5792. module.exports = function (desc) {
  5793. var postfix = 0, name, ie11BugWorkaround;
  5794. while (created[desc + (postfix || "")]) ++postfix;
  5795. desc += postfix || "";
  5796. created[desc] = true;
  5797. name = "@@" + desc;
  5798. defineProperty(
  5799. objPrototype,
  5800. name,
  5801. d.gs(null, function (value) {
  5802. // For IE11 issue see:
  5803. // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
  5804. // ie11-broken-getters-on-dom-objects
  5805. // https://github.com/medikoo/es6-symbol/issues/12
  5806. if (ie11BugWorkaround) return;
  5807. ie11BugWorkaround = true;
  5808. defineProperty(this, name, d(value));
  5809. ie11BugWorkaround = false;
  5810. })
  5811. );
  5812. return name;
  5813. };
  5814. },{"d":15}],78:[function(require,module,exports){
  5815. "use strict";
  5816. var d = require("d")
  5817. , NativeSymbol = require("ext/global-this").Symbol;
  5818. module.exports = function (SymbolPolyfill) {
  5819. return Object.defineProperties(SymbolPolyfill, {
  5820. // To ensure proper interoperability with other native functions (e.g. Array.from)
  5821. // fallback to eventual native implementation of given symbol
  5822. hasInstance: d(
  5823. "", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance")
  5824. ),
  5825. isConcatSpreadable: d(
  5826. "",
  5827. (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
  5828. SymbolPolyfill("isConcatSpreadable")
  5829. ),
  5830. iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")),
  5831. match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")),
  5832. replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")),
  5833. search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")),
  5834. species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")),
  5835. split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")),
  5836. toPrimitive: d(
  5837. "", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive")
  5838. ),
  5839. toStringTag: d(
  5840. "", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag")
  5841. ),
  5842. unscopables: d(
  5843. "", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables")
  5844. )
  5845. });
  5846. };
  5847. },{"d":15,"ext/global-this":85}],79:[function(require,module,exports){
  5848. "use strict";
  5849. var d = require("d")
  5850. , validateSymbol = require("../../../validate-symbol");
  5851. var registry = Object.create(null);
  5852. module.exports = function (SymbolPolyfill) {
  5853. return Object.defineProperties(SymbolPolyfill, {
  5854. for: d(function (key) {
  5855. if (registry[key]) return registry[key];
  5856. return (registry[key] = SymbolPolyfill(String(key)));
  5857. }),
  5858. keyFor: d(function (symbol) {
  5859. var key;
  5860. validateSymbol(symbol);
  5861. for (key in registry) {
  5862. if (registry[key] === symbol) return key;
  5863. }
  5864. return undefined;
  5865. })
  5866. });
  5867. };
  5868. },{"../../../validate-symbol":81,"d":15}],80:[function(require,module,exports){
  5869. // ES2015 Symbol polyfill for environments that do not (or partially) support it
  5870. "use strict";
  5871. var d = require("d")
  5872. , validateSymbol = require("./validate-symbol")
  5873. , NativeSymbol = require("ext/global-this").Symbol
  5874. , generateName = require("./lib/private/generate-name")
  5875. , setupStandardSymbols = require("./lib/private/setup/standard-symbols")
  5876. , setupSymbolRegistry = require("./lib/private/setup/symbol-registry");
  5877. var create = Object.create
  5878. , defineProperties = Object.defineProperties
  5879. , defineProperty = Object.defineProperty;
  5880. var SymbolPolyfill, HiddenSymbol, isNativeSafe;
  5881. if (typeof NativeSymbol === "function") {
  5882. try {
  5883. String(NativeSymbol());
  5884. isNativeSafe = true;
  5885. } catch (ignore) {}
  5886. } else {
  5887. NativeSymbol = null;
  5888. }
  5889. // Internal constructor (not one exposed) for creating Symbol instances.
  5890. // This one is used to ensure that `someSymbol instanceof Symbol` always return false
  5891. HiddenSymbol = function Symbol(description) {
  5892. if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor");
  5893. return SymbolPolyfill(description);
  5894. };
  5895. // Exposed `Symbol` constructor
  5896. // (returns instances of HiddenSymbol)
  5897. module.exports = SymbolPolyfill = function Symbol(description) {
  5898. var symbol;
  5899. if (this instanceof Symbol) throw new TypeError("Symbol is not a constructor");
  5900. if (isNativeSafe) return NativeSymbol(description);
  5901. symbol = create(HiddenSymbol.prototype);
  5902. description = description === undefined ? "" : String(description);
  5903. return defineProperties(symbol, {
  5904. __description__: d("", description),
  5905. __name__: d("", generateName(description))
  5906. });
  5907. };
  5908. setupStandardSymbols(SymbolPolyfill);
  5909. setupSymbolRegistry(SymbolPolyfill);
  5910. // Internal tweaks for real symbol producer
  5911. defineProperties(HiddenSymbol.prototype, {
  5912. constructor: d(SymbolPolyfill),
  5913. toString: d("", function () { return this.__name__; })
  5914. });
  5915. // Proper implementation of methods exposed on Symbol.prototype
  5916. // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
  5917. defineProperties(SymbolPolyfill.prototype, {
  5918. toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }),
  5919. valueOf: d(function () { return validateSymbol(this); })
  5920. });
  5921. defineProperty(
  5922. SymbolPolyfill.prototype,
  5923. SymbolPolyfill.toPrimitive,
  5924. d("", function () {
  5925. var symbol = validateSymbol(this);
  5926. if (typeof symbol === "symbol") return symbol;
  5927. return symbol.toString();
  5928. })
  5929. );
  5930. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol"));
  5931. // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
  5932. defineProperty(
  5933. HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
  5934. d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])
  5935. );
  5936. // Note: It's important to define `toPrimitive` as last one, as some implementations
  5937. // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
  5938. // And that may invoke error in definition flow:
  5939. // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
  5940. defineProperty(
  5941. HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
  5942. d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])
  5943. );
  5944. },{"./lib/private/generate-name":77,"./lib/private/setup/standard-symbols":78,"./lib/private/setup/symbol-registry":79,"./validate-symbol":81,"d":15,"ext/global-this":85}],81:[function(require,module,exports){
  5945. "use strict";
  5946. var isSymbol = require("./is-symbol");
  5947. module.exports = function (value) {
  5948. if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
  5949. return value;
  5950. };
  5951. },{"./is-symbol":76}],82:[function(require,module,exports){
  5952. 'use strict';
  5953. var d = require('d')
  5954. , callable = require('es5-ext/object/valid-callable')
  5955. , apply = Function.prototype.apply, call = Function.prototype.call
  5956. , create = Object.create, defineProperty = Object.defineProperty
  5957. , defineProperties = Object.defineProperties
  5958. , hasOwnProperty = Object.prototype.hasOwnProperty
  5959. , descriptor = { configurable: true, enumerable: false, writable: true }
  5960. , on, once, off, emit, methods, descriptors, base;
  5961. on = function (type, listener) {
  5962. var data;
  5963. callable(listener);
  5964. if (!hasOwnProperty.call(this, '__ee__')) {
  5965. data = descriptor.value = create(null);
  5966. defineProperty(this, '__ee__', descriptor);
  5967. descriptor.value = null;
  5968. } else {
  5969. data = this.__ee__;
  5970. }
  5971. if (!data[type]) data[type] = listener;
  5972. else if (typeof data[type] === 'object') data[type].push(listener);
  5973. else data[type] = [data[type], listener];
  5974. return this;
  5975. };
  5976. once = function (type, listener) {
  5977. var once, self;
  5978. callable(listener);
  5979. self = this;
  5980. on.call(this, type, once = function () {
  5981. off.call(self, type, once);
  5982. apply.call(listener, this, arguments);
  5983. });
  5984. once.__eeOnceListener__ = listener;
  5985. return this;
  5986. };
  5987. off = function (type, listener) {
  5988. var data, listeners, candidate, i;
  5989. callable(listener);
  5990. if (!hasOwnProperty.call(this, '__ee__')) return this;
  5991. data = this.__ee__;
  5992. if (!data[type]) return this;
  5993. listeners = data[type];
  5994. if (typeof listeners === 'object') {
  5995. for (i = 0; (candidate = listeners[i]); ++i) {
  5996. if ((candidate === listener) ||
  5997. (candidate.__eeOnceListener__ === listener)) {
  5998. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  5999. else listeners.splice(i, 1);
  6000. }
  6001. }
  6002. } else {
  6003. if ((listeners === listener) ||
  6004. (listeners.__eeOnceListener__ === listener)) {
  6005. delete data[type];
  6006. }
  6007. }
  6008. return this;
  6009. };
  6010. emit = function (type) {
  6011. var i, l, listener, listeners, args;
  6012. if (!hasOwnProperty.call(this, '__ee__')) return;
  6013. listeners = this.__ee__[type];
  6014. if (!listeners) return;
  6015. if (typeof listeners === 'object') {
  6016. l = arguments.length;
  6017. args = new Array(l - 1);
  6018. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  6019. listeners = listeners.slice();
  6020. for (i = 0; (listener = listeners[i]); ++i) {
  6021. apply.call(listener, this, args);
  6022. }
  6023. } else {
  6024. switch (arguments.length) {
  6025. case 1:
  6026. call.call(listeners, this);
  6027. break;
  6028. case 2:
  6029. call.call(listeners, this, arguments[1]);
  6030. break;
  6031. case 3:
  6032. call.call(listeners, this, arguments[1], arguments[2]);
  6033. break;
  6034. default:
  6035. l = arguments.length;
  6036. args = new Array(l - 1);
  6037. for (i = 1; i < l; ++i) {
  6038. args[i - 1] = arguments[i];
  6039. }
  6040. apply.call(listeners, this, args);
  6041. }
  6042. }
  6043. };
  6044. methods = {
  6045. on: on,
  6046. once: once,
  6047. off: off,
  6048. emit: emit
  6049. };
  6050. descriptors = {
  6051. on: d(on),
  6052. once: d(once),
  6053. off: d(off),
  6054. emit: d(emit)
  6055. };
  6056. base = defineProperties({}, descriptors);
  6057. module.exports = exports = function (o) {
  6058. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  6059. };
  6060. exports.methods = methods;
  6061. },{"d":15,"es5-ext/object/valid-callable":55}],83:[function(require,module,exports){
  6062. // Copyright Joyent, Inc. and other Node contributors.
  6063. //
  6064. // Permission is hereby granted, free of charge, to any person obtaining a
  6065. // copy of this software and associated documentation files (the
  6066. // "Software"), to deal in the Software without restriction, including
  6067. // without limitation the rights to use, copy, modify, merge, publish,
  6068. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6069. // persons to whom the Software is furnished to do so, subject to the
  6070. // following conditions:
  6071. //
  6072. // The above copyright notice and this permission notice shall be included
  6073. // in all copies or substantial portions of the Software.
  6074. //
  6075. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6076. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6077. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6078. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6079. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6080. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6081. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6082. var objectCreate = Object.create || objectCreatePolyfill
  6083. var objectKeys = Object.keys || objectKeysPolyfill
  6084. var bind = Function.prototype.bind || functionBindPolyfill
  6085. function EventEmitter() {
  6086. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  6087. this._events = objectCreate(null);
  6088. this._eventsCount = 0;
  6089. }
  6090. this._maxListeners = this._maxListeners || undefined;
  6091. }
  6092. module.exports = EventEmitter;
  6093. // Backwards-compat with node 0.10.x
  6094. EventEmitter.EventEmitter = EventEmitter;
  6095. EventEmitter.prototype._events = undefined;
  6096. EventEmitter.prototype._maxListeners = undefined;
  6097. // By default EventEmitters will print a warning if more than 10 listeners are
  6098. // added to it. This is a useful default which helps finding memory leaks.
  6099. var defaultMaxListeners = 10;
  6100. var hasDefineProperty;
  6101. try {
  6102. var o = {};
  6103. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  6104. hasDefineProperty = o.x === 0;
  6105. } catch (err) { hasDefineProperty = false }
  6106. if (hasDefineProperty) {
  6107. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  6108. enumerable: true,
  6109. get: function() {
  6110. return defaultMaxListeners;
  6111. },
  6112. set: function(arg) {
  6113. // check whether the input is a positive number (whose value is zero or
  6114. // greater and not a NaN).
  6115. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  6116. throw new TypeError('"defaultMaxListeners" must be a positive number');
  6117. defaultMaxListeners = arg;
  6118. }
  6119. });
  6120. } else {
  6121. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  6122. }
  6123. // Obviously not all Emitters should be limited to 10. This function allows
  6124. // that to be increased. Set to zero for unlimited.
  6125. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  6126. if (typeof n !== 'number' || n < 0 || isNaN(n))
  6127. throw new TypeError('"n" argument must be a positive number');
  6128. this._maxListeners = n;
  6129. return this;
  6130. };
  6131. function $getMaxListeners(that) {
  6132. if (that._maxListeners === undefined)
  6133. return EventEmitter.defaultMaxListeners;
  6134. return that._maxListeners;
  6135. }
  6136. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  6137. return $getMaxListeners(this);
  6138. };
  6139. // These standalone emit* functions are used to optimize calling of event
  6140. // handlers for fast cases because emit() itself often has a variable number of
  6141. // arguments and can be deoptimized because of that. These functions always have
  6142. // the same number of arguments and thus do not get deoptimized, so the code
  6143. // inside them can execute faster.
  6144. function emitNone(handler, isFn, self) {
  6145. if (isFn)
  6146. handler.call(self);
  6147. else {
  6148. var len = handler.length;
  6149. var listeners = arrayClone(handler, len);
  6150. for (var i = 0; i < len; ++i)
  6151. listeners[i].call(self);
  6152. }
  6153. }
  6154. function emitOne(handler, isFn, self, arg1) {
  6155. if (isFn)
  6156. handler.call(self, arg1);
  6157. else {
  6158. var len = handler.length;
  6159. var listeners = arrayClone(handler, len);
  6160. for (var i = 0; i < len; ++i)
  6161. listeners[i].call(self, arg1);
  6162. }
  6163. }
  6164. function emitTwo(handler, isFn, self, arg1, arg2) {
  6165. if (isFn)
  6166. handler.call(self, arg1, arg2);
  6167. else {
  6168. var len = handler.length;
  6169. var listeners = arrayClone(handler, len);
  6170. for (var i = 0; i < len; ++i)
  6171. listeners[i].call(self, arg1, arg2);
  6172. }
  6173. }
  6174. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  6175. if (isFn)
  6176. handler.call(self, arg1, arg2, arg3);
  6177. else {
  6178. var len = handler.length;
  6179. var listeners = arrayClone(handler, len);
  6180. for (var i = 0; i < len; ++i)
  6181. listeners[i].call(self, arg1, arg2, arg3);
  6182. }
  6183. }
  6184. function emitMany(handler, isFn, self, args) {
  6185. if (isFn)
  6186. handler.apply(self, args);
  6187. else {
  6188. var len = handler.length;
  6189. var listeners = arrayClone(handler, len);
  6190. for (var i = 0; i < len; ++i)
  6191. listeners[i].apply(self, args);
  6192. }
  6193. }
  6194. EventEmitter.prototype.emit = function emit(type) {
  6195. var er, handler, len, args, i, events;
  6196. var doError = (type === 'error');
  6197. events = this._events;
  6198. if (events)
  6199. doError = (doError && events.error == null);
  6200. else if (!doError)
  6201. return false;
  6202. // If there is no 'error' event listener then throw.
  6203. if (doError) {
  6204. if (arguments.length > 1)
  6205. er = arguments[1];
  6206. if (er instanceof Error) {
  6207. throw er; // Unhandled 'error' event
  6208. } else {
  6209. // At least give some kind of context to the user
  6210. var err = new Error('Unhandled "error" event. (' + er + ')');
  6211. err.context = er;
  6212. throw err;
  6213. }
  6214. return false;
  6215. }
  6216. handler = events[type];
  6217. if (!handler)
  6218. return false;
  6219. var isFn = typeof handler === 'function';
  6220. len = arguments.length;
  6221. switch (len) {
  6222. // fast cases
  6223. case 1:
  6224. emitNone(handler, isFn, this);
  6225. break;
  6226. case 2:
  6227. emitOne(handler, isFn, this, arguments[1]);
  6228. break;
  6229. case 3:
  6230. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  6231. break;
  6232. case 4:
  6233. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  6234. break;
  6235. // slower
  6236. default:
  6237. args = new Array(len - 1);
  6238. for (i = 1; i < len; i++)
  6239. args[i - 1] = arguments[i];
  6240. emitMany(handler, isFn, this, args);
  6241. }
  6242. return true;
  6243. };
  6244. function _addListener(target, type, listener, prepend) {
  6245. var m;
  6246. var events;
  6247. var existing;
  6248. if (typeof listener !== 'function')
  6249. throw new TypeError('"listener" argument must be a function');
  6250. events = target._events;
  6251. if (!events) {
  6252. events = target._events = objectCreate(null);
  6253. target._eventsCount = 0;
  6254. } else {
  6255. // To avoid recursion in the case that type === "newListener"! Before
  6256. // adding it to the listeners, first emit "newListener".
  6257. if (events.newListener) {
  6258. target.emit('newListener', type,
  6259. listener.listener ? listener.listener : listener);
  6260. // Re-assign `events` because a newListener handler could have caused the
  6261. // this._events to be assigned to a new object
  6262. events = target._events;
  6263. }
  6264. existing = events[type];
  6265. }
  6266. if (!existing) {
  6267. // Optimize the case of one listener. Don't need the extra array object.
  6268. existing = events[type] = listener;
  6269. ++target._eventsCount;
  6270. } else {
  6271. if (typeof existing === 'function') {
  6272. // Adding the second element, need to change to array.
  6273. existing = events[type] =
  6274. prepend ? [listener, existing] : [existing, listener];
  6275. } else {
  6276. // If we've already got an array, just append.
  6277. if (prepend) {
  6278. existing.unshift(listener);
  6279. } else {
  6280. existing.push(listener);
  6281. }
  6282. }
  6283. // Check for listener leak
  6284. if (!existing.warned) {
  6285. m = $getMaxListeners(target);
  6286. if (m && m > 0 && existing.length > m) {
  6287. existing.warned = true;
  6288. var w = new Error('Possible EventEmitter memory leak detected. ' +
  6289. existing.length + ' "' + String(type) + '" listeners ' +
  6290. 'added. Use emitter.setMaxListeners() to ' +
  6291. 'increase limit.');
  6292. w.name = 'MaxListenersExceededWarning';
  6293. w.emitter = target;
  6294. w.type = type;
  6295. w.count = existing.length;
  6296. if (typeof console === 'object' && console.warn) {
  6297. console.warn('%s: %s', w.name, w.message);
  6298. }
  6299. }
  6300. }
  6301. }
  6302. return target;
  6303. }
  6304. EventEmitter.prototype.addListener = function addListener(type, listener) {
  6305. return _addListener(this, type, listener, false);
  6306. };
  6307. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  6308. EventEmitter.prototype.prependListener =
  6309. function prependListener(type, listener) {
  6310. return _addListener(this, type, listener, true);
  6311. };
  6312. function onceWrapper() {
  6313. if (!this.fired) {
  6314. this.target.removeListener(this.type, this.wrapFn);
  6315. this.fired = true;
  6316. switch (arguments.length) {
  6317. case 0:
  6318. return this.listener.call(this.target);
  6319. case 1:
  6320. return this.listener.call(this.target, arguments[0]);
  6321. case 2:
  6322. return this.listener.call(this.target, arguments[0], arguments[1]);
  6323. case 3:
  6324. return this.listener.call(this.target, arguments[0], arguments[1],
  6325. arguments[2]);
  6326. default:
  6327. var args = new Array(arguments.length);
  6328. for (var i = 0; i < args.length; ++i)
  6329. args[i] = arguments[i];
  6330. this.listener.apply(this.target, args);
  6331. }
  6332. }
  6333. }
  6334. function _onceWrap(target, type, listener) {
  6335. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  6336. var wrapped = bind.call(onceWrapper, state);
  6337. wrapped.listener = listener;
  6338. state.wrapFn = wrapped;
  6339. return wrapped;
  6340. }
  6341. EventEmitter.prototype.once = function once(type, listener) {
  6342. if (typeof listener !== 'function')
  6343. throw new TypeError('"listener" argument must be a function');
  6344. this.on(type, _onceWrap(this, type, listener));
  6345. return this;
  6346. };
  6347. EventEmitter.prototype.prependOnceListener =
  6348. function prependOnceListener(type, listener) {
  6349. if (typeof listener !== 'function')
  6350. throw new TypeError('"listener" argument must be a function');
  6351. this.prependListener(type, _onceWrap(this, type, listener));
  6352. return this;
  6353. };
  6354. // Emits a 'removeListener' event if and only if the listener was removed.
  6355. EventEmitter.prototype.removeListener =
  6356. function removeListener(type, listener) {
  6357. var list, events, position, i, originalListener;
  6358. if (typeof listener !== 'function')
  6359. throw new TypeError('"listener" argument must be a function');
  6360. events = this._events;
  6361. if (!events)
  6362. return this;
  6363. list = events[type];
  6364. if (!list)
  6365. return this;
  6366. if (list === listener || list.listener === listener) {
  6367. if (--this._eventsCount === 0)
  6368. this._events = objectCreate(null);
  6369. else {
  6370. delete events[type];
  6371. if (events.removeListener)
  6372. this.emit('removeListener', type, list.listener || listener);
  6373. }
  6374. } else if (typeof list !== 'function') {
  6375. position = -1;
  6376. for (i = list.length - 1; i >= 0; i--) {
  6377. if (list[i] === listener || list[i].listener === listener) {
  6378. originalListener = list[i].listener;
  6379. position = i;
  6380. break;
  6381. }
  6382. }
  6383. if (position < 0)
  6384. return this;
  6385. if (position === 0)
  6386. list.shift();
  6387. else
  6388. spliceOne(list, position);
  6389. if (list.length === 1)
  6390. events[type] = list[0];
  6391. if (events.removeListener)
  6392. this.emit('removeListener', type, originalListener || listener);
  6393. }
  6394. return this;
  6395. };
  6396. EventEmitter.prototype.removeAllListeners =
  6397. function removeAllListeners(type) {
  6398. var listeners, events, i;
  6399. events = this._events;
  6400. if (!events)
  6401. return this;
  6402. // not listening for removeListener, no need to emit
  6403. if (!events.removeListener) {
  6404. if (arguments.length === 0) {
  6405. this._events = objectCreate(null);
  6406. this._eventsCount = 0;
  6407. } else if (events[type]) {
  6408. if (--this._eventsCount === 0)
  6409. this._events = objectCreate(null);
  6410. else
  6411. delete events[type];
  6412. }
  6413. return this;
  6414. }
  6415. // emit removeListener for all listeners on all events
  6416. if (arguments.length === 0) {
  6417. var keys = objectKeys(events);
  6418. var key;
  6419. for (i = 0; i < keys.length; ++i) {
  6420. key = keys[i];
  6421. if (key === 'removeListener') continue;
  6422. this.removeAllListeners(key);
  6423. }
  6424. this.removeAllListeners('removeListener');
  6425. this._events = objectCreate(null);
  6426. this._eventsCount = 0;
  6427. return this;
  6428. }
  6429. listeners = events[type];
  6430. if (typeof listeners === 'function') {
  6431. this.removeListener(type, listeners);
  6432. } else if (listeners) {
  6433. // LIFO order
  6434. for (i = listeners.length - 1; i >= 0; i--) {
  6435. this.removeListener(type, listeners[i]);
  6436. }
  6437. }
  6438. return this;
  6439. };
  6440. function _listeners(target, type, unwrap) {
  6441. var events = target._events;
  6442. if (!events)
  6443. return [];
  6444. var evlistener = events[type];
  6445. if (!evlistener)
  6446. return [];
  6447. if (typeof evlistener === 'function')
  6448. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  6449. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  6450. }
  6451. EventEmitter.prototype.listeners = function listeners(type) {
  6452. return _listeners(this, type, true);
  6453. };
  6454. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  6455. return _listeners(this, type, false);
  6456. };
  6457. EventEmitter.listenerCount = function(emitter, type) {
  6458. if (typeof emitter.listenerCount === 'function') {
  6459. return emitter.listenerCount(type);
  6460. } else {
  6461. return listenerCount.call(emitter, type);
  6462. }
  6463. };
  6464. EventEmitter.prototype.listenerCount = listenerCount;
  6465. function listenerCount(type) {
  6466. var events = this._events;
  6467. if (events) {
  6468. var evlistener = events[type];
  6469. if (typeof evlistener === 'function') {
  6470. return 1;
  6471. } else if (evlistener) {
  6472. return evlistener.length;
  6473. }
  6474. }
  6475. return 0;
  6476. }
  6477. EventEmitter.prototype.eventNames = function eventNames() {
  6478. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  6479. };
  6480. // About 1.5x faster than the two-arg version of Array#splice().
  6481. function spliceOne(list, index) {
  6482. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  6483. list[i] = list[k];
  6484. list.pop();
  6485. }
  6486. function arrayClone(arr, n) {
  6487. var copy = new Array(n);
  6488. for (var i = 0; i < n; ++i)
  6489. copy[i] = arr[i];
  6490. return copy;
  6491. }
  6492. function unwrapListeners(arr) {
  6493. var ret = new Array(arr.length);
  6494. for (var i = 0; i < ret.length; ++i) {
  6495. ret[i] = arr[i].listener || arr[i];
  6496. }
  6497. return ret;
  6498. }
  6499. function objectCreatePolyfill(proto) {
  6500. var F = function() {};
  6501. F.prototype = proto;
  6502. return new F;
  6503. }
  6504. function objectKeysPolyfill(obj) {
  6505. var keys = [];
  6506. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  6507. keys.push(k);
  6508. }
  6509. return k;
  6510. }
  6511. function functionBindPolyfill(context) {
  6512. var fn = this;
  6513. return function () {
  6514. return fn.apply(context, arguments);
  6515. };
  6516. }
  6517. },{}],84:[function(require,module,exports){
  6518. var naiveFallback = function () {
  6519. if (typeof self === "object" && self) return self;
  6520. if (typeof window === "object" && window) return window;
  6521. throw new Error("Unable to resolve global `this`");
  6522. };
  6523. module.exports = (function () {
  6524. if (this) return this;
  6525. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  6526. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  6527. // In all ES5+ engines global object inherits from Object.prototype
  6528. // (if you approached one that doesn't please report)
  6529. try {
  6530. Object.defineProperty(Object.prototype, "__global__", {
  6531. get: function () { return this; },
  6532. configurable: true
  6533. });
  6534. } catch (error) {
  6535. // Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze)
  6536. return naiveFallback();
  6537. }
  6538. try {
  6539. // Safari case (window.__global__ is resolved with global context, but __global__ does not)
  6540. if (!__global__) return naiveFallback();
  6541. return __global__;
  6542. } finally {
  6543. delete Object.prototype.__global__;
  6544. }
  6545. })();
  6546. },{}],85:[function(require,module,exports){
  6547. "use strict";
  6548. module.exports = require("./is-implemented")() ? globalThis : require("./implementation");
  6549. },{"./implementation":84,"./is-implemented":86}],86:[function(require,module,exports){
  6550. "use strict";
  6551. module.exports = function () {
  6552. if (typeof globalThis !== "object") return false;
  6553. if (!globalThis) return false;
  6554. return globalThis.Array === Array;
  6555. };
  6556. },{}],87:[function(require,module,exports){
  6557. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  6558. var e, m
  6559. var eLen = (nBytes * 8) - mLen - 1
  6560. var eMax = (1 << eLen) - 1
  6561. var eBias = eMax >> 1
  6562. var nBits = -7
  6563. var i = isLE ? (nBytes - 1) : 0
  6564. var d = isLE ? -1 : 1
  6565. var s = buffer[offset + i]
  6566. i += d
  6567. e = s & ((1 << (-nBits)) - 1)
  6568. s >>= (-nBits)
  6569. nBits += eLen
  6570. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  6571. m = e & ((1 << (-nBits)) - 1)
  6572. e >>= (-nBits)
  6573. nBits += mLen
  6574. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  6575. if (e === 0) {
  6576. e = 1 - eBias
  6577. } else if (e === eMax) {
  6578. return m ? NaN : ((s ? -1 : 1) * Infinity)
  6579. } else {
  6580. m = m + Math.pow(2, mLen)
  6581. e = e - eBias
  6582. }
  6583. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  6584. }
  6585. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  6586. var e, m, c
  6587. var eLen = (nBytes * 8) - mLen - 1
  6588. var eMax = (1 << eLen) - 1
  6589. var eBias = eMax >> 1
  6590. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  6591. var i = isLE ? 0 : (nBytes - 1)
  6592. var d = isLE ? 1 : -1
  6593. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  6594. value = Math.abs(value)
  6595. if (isNaN(value) || value === Infinity) {
  6596. m = isNaN(value) ? 1 : 0
  6597. e = eMax
  6598. } else {
  6599. e = Math.floor(Math.log(value) / Math.LN2)
  6600. if (value * (c = Math.pow(2, -e)) < 1) {
  6601. e--
  6602. c *= 2
  6603. }
  6604. if (e + eBias >= 1) {
  6605. value += rt / c
  6606. } else {
  6607. value += rt * Math.pow(2, 1 - eBias)
  6608. }
  6609. if (value * c >= 2) {
  6610. e++
  6611. c /= 2
  6612. }
  6613. if (e + eBias >= eMax) {
  6614. m = 0
  6615. e = eMax
  6616. } else if (e + eBias >= 1) {
  6617. m = ((value * c) - 1) * Math.pow(2, mLen)
  6618. e = e + eBias
  6619. } else {
  6620. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  6621. e = 0
  6622. }
  6623. }
  6624. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  6625. e = (e << mLen) | m
  6626. eLen += mLen
  6627. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  6628. buffer[offset + i - d] |= s * 128
  6629. }
  6630. },{}],88:[function(require,module,exports){
  6631. if (typeof Object.create === 'function') {
  6632. // implementation from standard node.js 'util' module
  6633. module.exports = function inherits(ctor, superCtor) {
  6634. ctor.super_ = superCtor
  6635. ctor.prototype = Object.create(superCtor.prototype, {
  6636. constructor: {
  6637. value: ctor,
  6638. enumerable: false,
  6639. writable: true,
  6640. configurable: true
  6641. }
  6642. });
  6643. };
  6644. } else {
  6645. // old school shim for old browsers
  6646. module.exports = function inherits(ctor, superCtor) {
  6647. ctor.super_ = superCtor
  6648. var TempCtor = function () {}
  6649. TempCtor.prototype = superCtor.prototype
  6650. ctor.prototype = new TempCtor()
  6651. ctor.prototype.constructor = ctor
  6652. }
  6653. }
  6654. },{}],89:[function(require,module,exports){
  6655. /*!
  6656. * Determine if an object is a Buffer
  6657. *
  6658. * @author Feross Aboukhadijeh <https://feross.org>
  6659. * @license MIT
  6660. */
  6661. // The _isBuffer check is for Safari 5-7 support, because it's missing
  6662. // Object.prototype.constructor. Remove this eventually
  6663. module.exports = function (obj) {
  6664. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  6665. }
  6666. function isBuffer (obj) {
  6667. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  6668. }
  6669. // For Node v0.10 support. Remove this eventually.
  6670. function isSlowBuffer (obj) {
  6671. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  6672. }
  6673. },{}],90:[function(require,module,exports){
  6674. 'use strict'
  6675. var Buffer = require('safe-buffer').Buffer
  6676. /* Protocol - protocol constants */
  6677. var protocol = module.exports
  6678. /* Command code => mnemonic */
  6679. protocol.types = {
  6680. 0: 'reserved',
  6681. 1: 'connect',
  6682. 2: 'connack',
  6683. 3: 'publish',
  6684. 4: 'puback',
  6685. 5: 'pubrec',
  6686. 6: 'pubrel',
  6687. 7: 'pubcomp',
  6688. 8: 'subscribe',
  6689. 9: 'suback',
  6690. 10: 'unsubscribe',
  6691. 11: 'unsuback',
  6692. 12: 'pingreq',
  6693. 13: 'pingresp',
  6694. 14: 'disconnect',
  6695. 15: 'auth'
  6696. }
  6697. /* Mnemonic => Command code */
  6698. protocol.codes = {}
  6699. for (var k in protocol.types) {
  6700. var v = protocol.types[k]
  6701. protocol.codes[v] = k
  6702. }
  6703. /* Header */
  6704. protocol.CMD_SHIFT = 4
  6705. protocol.CMD_MASK = 0xF0
  6706. protocol.DUP_MASK = 0x08
  6707. protocol.QOS_MASK = 0x03
  6708. protocol.QOS_SHIFT = 1
  6709. protocol.RETAIN_MASK = 0x01
  6710. /* Length */
  6711. protocol.LENGTH_MASK = 0x7F
  6712. protocol.LENGTH_FIN_MASK = 0x80
  6713. /* Connack */
  6714. protocol.SESSIONPRESENT_MASK = 0x01
  6715. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  6716. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  6717. /* Connect */
  6718. protocol.USERNAME_MASK = 0x80
  6719. protocol.PASSWORD_MASK = 0x40
  6720. protocol.WILL_RETAIN_MASK = 0x20
  6721. protocol.WILL_QOS_MASK = 0x18
  6722. protocol.WILL_QOS_SHIFT = 3
  6723. protocol.WILL_FLAG_MASK = 0x04
  6724. protocol.CLEAN_SESSION_MASK = 0x02
  6725. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  6726. /* Properties */
  6727. protocol.properties = {
  6728. sessionExpiryInterval: 17,
  6729. willDelayInterval: 24,
  6730. receiveMaximum: 33,
  6731. maximumPacketSize: 39,
  6732. topicAliasMaximum: 34,
  6733. requestResponseInformation: 25,
  6734. requestProblemInformation: 23,
  6735. userProperties: 38,
  6736. authenticationMethod: 21,
  6737. authenticationData: 22,
  6738. payloadFormatIndicator: 1,
  6739. messageExpiryInterval: 2,
  6740. contentType: 3,
  6741. responseTopic: 8,
  6742. correlationData: 9,
  6743. maximumQoS: 36,
  6744. retainAvailable: 37,
  6745. assignedClientIdentifier: 18,
  6746. reasonString: 31,
  6747. wildcardSubscriptionAvailable: 40,
  6748. subscriptionIdentifiersAvailable: 41,
  6749. sharedSubscriptionAvailable: 42,
  6750. serverKeepAlive: 19,
  6751. responseInformation: 26,
  6752. serverReference: 28,
  6753. topicAlias: 35,
  6754. subscriptionIdentifier: 11
  6755. }
  6756. protocol.propertiesCodes = {}
  6757. for (var prop in protocol.properties) {
  6758. var id = protocol.properties[prop]
  6759. protocol.propertiesCodes[id] = prop
  6760. }
  6761. protocol.propertiesTypes = {
  6762. sessionExpiryInterval: 'int32',
  6763. willDelayInterval: 'int32',
  6764. receiveMaximum: 'int16',
  6765. maximumPacketSize: 'int32',
  6766. topicAliasMaximum: 'int16',
  6767. requestResponseInformation: 'byte',
  6768. requestProblemInformation: 'byte',
  6769. userProperties: 'pair',
  6770. authenticationMethod: 'string',
  6771. authenticationData: 'binary',
  6772. payloadFormatIndicator: 'byte',
  6773. messageExpiryInterval: 'int32',
  6774. contentType: 'string',
  6775. responseTopic: 'string',
  6776. correlationData: 'binary',
  6777. maximumQoS: 'int8',
  6778. retainAvailable: 'byte',
  6779. assignedClientIdentifier: 'string',
  6780. reasonString: 'string',
  6781. wildcardSubscriptionAvailable: 'byte',
  6782. subscriptionIdentifiersAvailable: 'byte',
  6783. sharedSubscriptionAvailable: 'byte',
  6784. serverKeepAlive: 'int32',
  6785. responseInformation: 'string',
  6786. serverReference: 'string',
  6787. topicAlias: 'int16',
  6788. subscriptionIdentifier: 'var'
  6789. }
  6790. function genHeader (type) {
  6791. return [0, 1, 2].map(function (qos) {
  6792. return [0, 1].map(function (dup) {
  6793. return [0, 1].map(function (retain) {
  6794. var buf = new Buffer(1)
  6795. buf.writeUInt8(
  6796. protocol.codes[type] << protocol.CMD_SHIFT |
  6797. (dup ? protocol.DUP_MASK : 0) |
  6798. qos << protocol.QOS_SHIFT | retain, 0, true)
  6799. return buf
  6800. })
  6801. })
  6802. })
  6803. }
  6804. /* Publish */
  6805. protocol.PUBLISH_HEADER = genHeader('publish')
  6806. /* Subscribe */
  6807. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  6808. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  6809. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  6810. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  6811. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  6812. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  6813. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  6814. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  6815. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  6816. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  6817. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  6818. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  6819. /* Unsubscribe */
  6820. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  6821. /* Confirmations */
  6822. protocol.ACKS = {
  6823. unsuback: genHeader('unsuback'),
  6824. puback: genHeader('puback'),
  6825. pubcomp: genHeader('pubcomp'),
  6826. pubrel: genHeader('pubrel'),
  6827. pubrec: genHeader('pubrec')
  6828. }
  6829. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  6830. /* Protocol versions */
  6831. protocol.VERSION3 = Buffer.from([3])
  6832. protocol.VERSION4 = Buffer.from([4])
  6833. protocol.VERSION5 = Buffer.from([5])
  6834. /* QoS */
  6835. protocol.QOS = [0, 1, 2].map(function (qos) {
  6836. return Buffer.from([qos])
  6837. })
  6838. /* Empty packets */
  6839. protocol.EMPTY = {
  6840. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  6841. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  6842. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  6843. }
  6844. },{"safe-buffer":118}],91:[function(require,module,exports){
  6845. 'use strict'
  6846. var Buffer = require('safe-buffer').Buffer
  6847. var writeToStream = require('./writeToStream')
  6848. var EE = require('events').EventEmitter
  6849. var inherits = require('inherits')
  6850. function generate (packet, opts) {
  6851. var stream = new Accumulator()
  6852. writeToStream(packet, stream, opts)
  6853. return stream.concat()
  6854. }
  6855. function Accumulator () {
  6856. this._array = new Array(20)
  6857. this._i = 0
  6858. }
  6859. inherits(Accumulator, EE)
  6860. Accumulator.prototype.write = function (chunk) {
  6861. this._array[this._i++] = chunk
  6862. return true
  6863. }
  6864. Accumulator.prototype.concat = function () {
  6865. var length = 0
  6866. var lengths = new Array(this._array.length)
  6867. var list = this._array
  6868. var pos = 0
  6869. var i
  6870. var result
  6871. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6872. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  6873. else lengths[i] = Buffer.byteLength(list[i])
  6874. length += lengths[i]
  6875. }
  6876. result = Buffer.allocUnsafe(length)
  6877. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6878. if (typeof list[i] !== 'string') {
  6879. list[i].copy(result, pos)
  6880. pos += lengths[i]
  6881. } else {
  6882. result.write(list[i], pos)
  6883. pos += lengths[i]
  6884. }
  6885. }
  6886. return result
  6887. }
  6888. module.exports = generate
  6889. },{"./writeToStream":97,"events":83,"inherits":88,"safe-buffer":118}],92:[function(require,module,exports){
  6890. 'use strict'
  6891. exports.parser = require('./parser')
  6892. exports.generate = require('./generate')
  6893. exports.writeToStream = require('./writeToStream')
  6894. },{"./generate":91,"./parser":96,"./writeToStream":97}],93:[function(require,module,exports){
  6895. var DuplexStream = require('readable-stream/duplex')
  6896. , util = require('util')
  6897. , Buffer = require('safe-buffer').Buffer
  6898. function BufferList (callback) {
  6899. if (!(this instanceof BufferList))
  6900. return new BufferList(callback)
  6901. this._bufs = []
  6902. this.length = 0
  6903. if (typeof callback == 'function') {
  6904. this._callback = callback
  6905. var piper = function piper (err) {
  6906. if (this._callback) {
  6907. this._callback(err)
  6908. this._callback = null
  6909. }
  6910. }.bind(this)
  6911. this.on('pipe', function onPipe (src) {
  6912. src.on('error', piper)
  6913. })
  6914. this.on('unpipe', function onUnpipe (src) {
  6915. src.removeListener('error', piper)
  6916. })
  6917. } else {
  6918. this.append(callback)
  6919. }
  6920. DuplexStream.call(this)
  6921. }
  6922. util.inherits(BufferList, DuplexStream)
  6923. BufferList.prototype._offset = function _offset (offset) {
  6924. var tot = 0, i = 0, _t
  6925. if (offset === 0) return [ 0, 0 ]
  6926. for (; i < this._bufs.length; i++) {
  6927. _t = tot + this._bufs[i].length
  6928. if (offset < _t || i == this._bufs.length - 1)
  6929. return [ i, offset - tot ]
  6930. tot = _t
  6931. }
  6932. }
  6933. BufferList.prototype.append = function append (buf) {
  6934. var i = 0
  6935. if (Buffer.isBuffer(buf)) {
  6936. this._appendBuffer(buf);
  6937. } else if (Array.isArray(buf)) {
  6938. for (; i < buf.length; i++)
  6939. this.append(buf[i])
  6940. } else if (buf instanceof BufferList) {
  6941. // unwrap argument into individual BufferLists
  6942. for (; i < buf._bufs.length; i++)
  6943. this.append(buf._bufs[i])
  6944. } else if (buf != null) {
  6945. // coerce number arguments to strings, since Buffer(number) does
  6946. // uninitialized memory allocation
  6947. if (typeof buf == 'number')
  6948. buf = buf.toString()
  6949. this._appendBuffer(Buffer.from(buf));
  6950. }
  6951. return this
  6952. }
  6953. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  6954. this._bufs.push(buf)
  6955. this.length += buf.length
  6956. }
  6957. BufferList.prototype._write = function _write (buf, encoding, callback) {
  6958. this._appendBuffer(buf)
  6959. if (typeof callback == 'function')
  6960. callback()
  6961. }
  6962. BufferList.prototype._read = function _read (size) {
  6963. if (!this.length)
  6964. return this.push(null)
  6965. size = Math.min(size, this.length)
  6966. this.push(this.slice(0, size))
  6967. this.consume(size)
  6968. }
  6969. BufferList.prototype.end = function end (chunk) {
  6970. DuplexStream.prototype.end.call(this, chunk)
  6971. if (this._callback) {
  6972. this._callback(null, this.slice())
  6973. this._callback = null
  6974. }
  6975. }
  6976. BufferList.prototype.get = function get (index) {
  6977. return this.slice(index, index + 1)[0]
  6978. }
  6979. BufferList.prototype.slice = function slice (start, end) {
  6980. if (typeof start == 'number' && start < 0)
  6981. start += this.length
  6982. if (typeof end == 'number' && end < 0)
  6983. end += this.length
  6984. return this.copy(null, 0, start, end)
  6985. }
  6986. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  6987. if (typeof srcStart != 'number' || srcStart < 0)
  6988. srcStart = 0
  6989. if (typeof srcEnd != 'number' || srcEnd > this.length)
  6990. srcEnd = this.length
  6991. if (srcStart >= this.length)
  6992. return dst || Buffer.alloc(0)
  6993. if (srcEnd <= 0)
  6994. return dst || Buffer.alloc(0)
  6995. var copy = !!dst
  6996. , off = this._offset(srcStart)
  6997. , len = srcEnd - srcStart
  6998. , bytes = len
  6999. , bufoff = (copy && dstStart) || 0
  7000. , start = off[1]
  7001. , l
  7002. , i
  7003. // copy/slice everything
  7004. if (srcStart === 0 && srcEnd == this.length) {
  7005. if (!copy) { // slice, but full concat if multiple buffers
  7006. return this._bufs.length === 1
  7007. ? this._bufs[0]
  7008. : Buffer.concat(this._bufs, this.length)
  7009. }
  7010. // copy, need to copy individual buffers
  7011. for (i = 0; i < this._bufs.length; i++) {
  7012. this._bufs[i].copy(dst, bufoff)
  7013. bufoff += this._bufs[i].length
  7014. }
  7015. return dst
  7016. }
  7017. // easy, cheap case where it's a subset of one of the buffers
  7018. if (bytes <= this._bufs[off[0]].length - start) {
  7019. return copy
  7020. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  7021. : this._bufs[off[0]].slice(start, start + bytes)
  7022. }
  7023. if (!copy) // a slice, we need something to copy in to
  7024. dst = Buffer.allocUnsafe(len)
  7025. for (i = off[0]; i < this._bufs.length; i++) {
  7026. l = this._bufs[i].length - start
  7027. if (bytes > l) {
  7028. this._bufs[i].copy(dst, bufoff, start)
  7029. } else {
  7030. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  7031. break
  7032. }
  7033. bufoff += l
  7034. bytes -= l
  7035. if (start)
  7036. start = 0
  7037. }
  7038. return dst
  7039. }
  7040. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  7041. start = start || 0
  7042. end = end || this.length
  7043. if (start < 0)
  7044. start += this.length
  7045. if (end < 0)
  7046. end += this.length
  7047. var startOffset = this._offset(start)
  7048. , endOffset = this._offset(end)
  7049. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  7050. if (endOffset[1] == 0)
  7051. buffers.pop()
  7052. else
  7053. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  7054. if (startOffset[1] != 0)
  7055. buffers[0] = buffers[0].slice(startOffset[1])
  7056. return new BufferList(buffers)
  7057. }
  7058. BufferList.prototype.toString = function toString (encoding, start, end) {
  7059. return this.slice(start, end).toString(encoding)
  7060. }
  7061. BufferList.prototype.consume = function consume (bytes) {
  7062. while (this._bufs.length) {
  7063. if (bytes >= this._bufs[0].length) {
  7064. bytes -= this._bufs[0].length
  7065. this.length -= this._bufs[0].length
  7066. this._bufs.shift()
  7067. } else {
  7068. this._bufs[0] = this._bufs[0].slice(bytes)
  7069. this.length -= bytes
  7070. break
  7071. }
  7072. }
  7073. return this
  7074. }
  7075. BufferList.prototype.duplicate = function duplicate () {
  7076. var i = 0
  7077. , copy = new BufferList()
  7078. for (; i < this._bufs.length; i++)
  7079. copy.append(this._bufs[i])
  7080. return copy
  7081. }
  7082. BufferList.prototype.destroy = function destroy () {
  7083. this._bufs.length = 0
  7084. this.length = 0
  7085. this.push(null)
  7086. }
  7087. ;(function () {
  7088. var methods = {
  7089. 'readDoubleBE' : 8
  7090. , 'readDoubleLE' : 8
  7091. , 'readFloatBE' : 4
  7092. , 'readFloatLE' : 4
  7093. , 'readInt32BE' : 4
  7094. , 'readInt32LE' : 4
  7095. , 'readUInt32BE' : 4
  7096. , 'readUInt32LE' : 4
  7097. , 'readInt16BE' : 2
  7098. , 'readInt16LE' : 2
  7099. , 'readUInt16BE' : 2
  7100. , 'readUInt16LE' : 2
  7101. , 'readInt8' : 1
  7102. , 'readUInt8' : 1
  7103. }
  7104. for (var m in methods) {
  7105. (function (m) {
  7106. BufferList.prototype[m] = function (offset) {
  7107. return this.slice(offset, offset + methods[m])[m](0)
  7108. }
  7109. }(m))
  7110. }
  7111. }())
  7112. module.exports = BufferList
  7113. },{"readable-stream/duplex":105,"safe-buffer":118,"util":136}],94:[function(require,module,exports){
  7114. 'use strict'
  7115. var Buffer = require('safe-buffer').Buffer
  7116. var max = 65536
  7117. var cache = {}
  7118. function generateBuffer (i) {
  7119. var buffer = Buffer.allocUnsafe(2)
  7120. buffer.writeUInt8(i >> 8, 0)
  7121. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  7122. return buffer
  7123. }
  7124. function generateCache () {
  7125. for (var i = 0; i < max; i++) {
  7126. cache[i] = generateBuffer(i)
  7127. }
  7128. }
  7129. /**
  7130. * calcVariableByteIntLength - calculate the variable byte integer
  7131. * length field
  7132. *
  7133. * @api private
  7134. */
  7135. function calcVariableByteIntLength (length) {
  7136. if (length >= 0 && length < 128) return 1
  7137. else if (length >= 128 && length < 16384) return 2
  7138. else if (length >= 16384 && length < 2097152) return 3
  7139. else if (length >= 2097152 && length < 268435456) return 4
  7140. else return 0
  7141. }
  7142. function genBufVariableByteInt (num) {
  7143. var digit = 0
  7144. var pos = 0
  7145. var length = calcVariableByteIntLength(num)
  7146. var buffer = Buffer.allocUnsafe(length)
  7147. do {
  7148. digit = num % 128 | 0
  7149. num = num / 128 | 0
  7150. if (num > 0) digit = digit | 0x80
  7151. buffer.writeUInt8(digit, pos++)
  7152. } while (num > 0)
  7153. return {
  7154. data: buffer,
  7155. length: length
  7156. }
  7157. }
  7158. function generate4ByteBuffer (num) {
  7159. var buffer = Buffer.allocUnsafe(4)
  7160. buffer.writeUInt32BE(num, 0)
  7161. return buffer
  7162. }
  7163. module.exports = {
  7164. cache: cache,
  7165. generateCache: generateCache,
  7166. generateNumber: generateBuffer,
  7167. genBufVariableByteInt: genBufVariableByteInt,
  7168. generate4ByteBuffer: generate4ByteBuffer
  7169. }
  7170. },{"safe-buffer":118}],95:[function(require,module,exports){
  7171. function Packet () {
  7172. this.cmd = null
  7173. this.retain = false
  7174. this.qos = 0
  7175. this.dup = false
  7176. this.length = -1
  7177. this.topic = null
  7178. this.payload = null
  7179. }
  7180. module.exports = Packet
  7181. },{}],96:[function(require,module,exports){
  7182. 'use strict'
  7183. var bl = require('bl')
  7184. var inherits = require('inherits')
  7185. var EE = require('events').EventEmitter
  7186. var Packet = require('./packet')
  7187. var constants = require('./constants')
  7188. function Parser (opt) {
  7189. if (!(this instanceof Parser)) return new Parser(opt)
  7190. this.settings = opt || {}
  7191. this._states = [
  7192. '_parseHeader',
  7193. '_parseLength',
  7194. '_parsePayload',
  7195. '_newPacket'
  7196. ]
  7197. this._resetState()
  7198. }
  7199. inherits(Parser, EE)
  7200. Parser.prototype._resetState = function () {
  7201. this.packet = new Packet()
  7202. this.error = null
  7203. this._list = bl()
  7204. this._stateCounter = 0
  7205. }
  7206. Parser.prototype.parse = function (buf) {
  7207. if (this.error) this._resetState()
  7208. this._list.append(buf)
  7209. while ((this.packet.length !== -1 || this._list.length > 0) &&
  7210. this[this._states[this._stateCounter]]() &&
  7211. !this.error) {
  7212. this._stateCounter++
  7213. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  7214. }
  7215. return this._list.length
  7216. }
  7217. Parser.prototype._parseHeader = function () {
  7218. // There is at least one byte in the buffer
  7219. var zero = this._list.readUInt8(0)
  7220. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  7221. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  7222. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  7223. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  7224. this._list.consume(1)
  7225. return true
  7226. }
  7227. Parser.prototype._parseLength = function () {
  7228. // There is at least one byte in the list
  7229. var result = this._parseVarByteNum(true)
  7230. if (result) {
  7231. this.packet.length = result.value
  7232. this._list.consume(result.bytes)
  7233. }
  7234. return !!result
  7235. }
  7236. Parser.prototype._parsePayload = function () {
  7237. var result = false
  7238. // Do we have a payload? Do we have enough data to complete the payload?
  7239. // PINGs have no payload
  7240. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  7241. this._pos = 0
  7242. switch (this.packet.cmd) {
  7243. case 'connect':
  7244. this._parseConnect()
  7245. break
  7246. case 'connack':
  7247. this._parseConnack()
  7248. break
  7249. case 'publish':
  7250. this._parsePublish()
  7251. break
  7252. case 'puback':
  7253. case 'pubrec':
  7254. case 'pubrel':
  7255. case 'pubcomp':
  7256. this._parseConfirmation()
  7257. break
  7258. case 'subscribe':
  7259. this._parseSubscribe()
  7260. break
  7261. case 'suback':
  7262. this._parseSuback()
  7263. break
  7264. case 'unsubscribe':
  7265. this._parseUnsubscribe()
  7266. break
  7267. case 'unsuback':
  7268. this._parseUnsuback()
  7269. break
  7270. case 'pingreq':
  7271. case 'pingresp':
  7272. // These are empty, nothing to do
  7273. break
  7274. case 'disconnect':
  7275. this._parseDisconnect()
  7276. break
  7277. case 'auth':
  7278. this._parseAuth()
  7279. break
  7280. default:
  7281. this._emitError(new Error('Not supported'))
  7282. }
  7283. result = true
  7284. }
  7285. return result
  7286. }
  7287. Parser.prototype._parseConnect = function () {
  7288. var protocolId // Protocol ID
  7289. var clientId // Client ID
  7290. var topic // Will topic
  7291. var payload // Will payload
  7292. var password // Password
  7293. var username // Username
  7294. var flags = {}
  7295. var packet = this.packet
  7296. // Parse protocolId
  7297. protocolId = this._parseString()
  7298. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  7299. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  7300. return this._emitError(new Error('Invalid protocolId'))
  7301. }
  7302. packet.protocolId = protocolId
  7303. // Parse constants version number
  7304. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  7305. packet.protocolVersion = this._list.readUInt8(this._pos)
  7306. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  7307. return this._emitError(new Error('Invalid protocol version'))
  7308. }
  7309. this._pos++
  7310. if (this._pos >= this._list.length) {
  7311. return this._emitError(new Error('Packet too short'))
  7312. }
  7313. // Parse connect flags
  7314. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  7315. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  7316. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  7317. if (flags.will) {
  7318. packet.will = {}
  7319. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  7320. packet.will.qos = (this._list.readUInt8(this._pos) &
  7321. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  7322. }
  7323. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  7324. this._pos++
  7325. // Parse keepalive
  7326. packet.keepalive = this._parseNum()
  7327. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  7328. // parse properties
  7329. if (packet.protocolVersion === 5) {
  7330. var properties = this._parseProperties()
  7331. if (Object.getOwnPropertyNames(properties).length) {
  7332. packet.properties = properties
  7333. }
  7334. }
  7335. // Parse clientId
  7336. clientId = this._parseString()
  7337. if (clientId === null) return this._emitError(new Error('Packet too short'))
  7338. packet.clientId = clientId
  7339. if (flags.will) {
  7340. if (packet.protocolVersion === 5) {
  7341. var willProperties = this._parseProperties()
  7342. if (Object.getOwnPropertyNames(willProperties).length) {
  7343. packet.will.properties = willProperties
  7344. }
  7345. }
  7346. // Parse will topic
  7347. topic = this._parseString()
  7348. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  7349. packet.will.topic = topic
  7350. // Parse will payload
  7351. payload = this._parseBuffer()
  7352. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  7353. packet.will.payload = payload
  7354. }
  7355. // Parse username
  7356. if (flags.username) {
  7357. username = this._parseString()
  7358. if (username === null) return this._emitError(new Error('Cannot parse username'))
  7359. packet.username = username
  7360. }
  7361. // Parse password
  7362. if (flags.password) {
  7363. password = this._parseBuffer()
  7364. if (password === null) return this._emitError(new Error('Cannot parse password'))
  7365. packet.password = password
  7366. }
  7367. // need for right parse auth packet and self set up
  7368. this.settings = packet
  7369. return packet
  7370. }
  7371. Parser.prototype._parseConnack = function () {
  7372. var packet = this.packet
  7373. if (this._list.length < 2) return null
  7374. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  7375. if (this.settings.protocolVersion === 5) {
  7376. packet.reasonCode = this._list.readUInt8(this._pos++)
  7377. } else {
  7378. packet.returnCode = this._list.readUInt8(this._pos++)
  7379. }
  7380. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  7381. // mqtt 5 properties
  7382. if (this.settings.protocolVersion === 5) {
  7383. var properties = this._parseProperties()
  7384. if (Object.getOwnPropertyNames(properties).length) {
  7385. packet.properties = properties
  7386. }
  7387. }
  7388. }
  7389. Parser.prototype._parsePublish = function () {
  7390. var packet = this.packet
  7391. packet.topic = this._parseString()
  7392. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  7393. // Parse messageId
  7394. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  7395. // Properties mqtt 5
  7396. if (this.settings.protocolVersion === 5) {
  7397. var properties = this._parseProperties()
  7398. if (Object.getOwnPropertyNames(properties).length) {
  7399. packet.properties = properties
  7400. }
  7401. }
  7402. packet.payload = this._list.slice(this._pos, packet.length)
  7403. }
  7404. Parser.prototype._parseSubscribe = function () {
  7405. var packet = this.packet
  7406. var topic
  7407. var options
  7408. var qos
  7409. var rh
  7410. var rap
  7411. var nl
  7412. var subscription
  7413. if (packet.qos !== 1) {
  7414. return this._emitError(new Error('Wrong subscribe header'))
  7415. }
  7416. packet.subscriptions = []
  7417. if (!this._parseMessageId()) { return }
  7418. // Properties mqtt 5
  7419. if (this.settings.protocolVersion === 5) {
  7420. var properties = this._parseProperties()
  7421. if (Object.getOwnPropertyNames(properties).length) {
  7422. packet.properties = properties
  7423. }
  7424. }
  7425. while (this._pos < packet.length) {
  7426. // Parse topic
  7427. topic = this._parseString()
  7428. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  7429. options = this._parseByte()
  7430. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  7431. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  7432. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  7433. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  7434. subscription = { topic: topic, qos: qos }
  7435. // mqtt 5 options
  7436. if (this.settings.protocolVersion === 5) {
  7437. subscription.nl = nl
  7438. subscription.rap = rap
  7439. subscription.rh = rh
  7440. }
  7441. // Push pair to subscriptions
  7442. packet.subscriptions.push(subscription)
  7443. }
  7444. }
  7445. Parser.prototype._parseSuback = function () {
  7446. var packet = this.packet
  7447. this.packet.granted = []
  7448. if (!this._parseMessageId()) { return }
  7449. // Properties mqtt 5
  7450. if (this.settings.protocolVersion === 5) {
  7451. var properties = this._parseProperties()
  7452. if (Object.getOwnPropertyNames(properties).length) {
  7453. packet.properties = properties
  7454. }
  7455. }
  7456. // Parse granted QoSes
  7457. while (this._pos < this.packet.length) {
  7458. this.packet.granted.push(this._list.readUInt8(this._pos++))
  7459. }
  7460. }
  7461. Parser.prototype._parseUnsubscribe = function () {
  7462. var packet = this.packet
  7463. packet.unsubscriptions = []
  7464. // Parse messageId
  7465. if (!this._parseMessageId()) { return }
  7466. // Properties mqtt 5
  7467. if (this.settings.protocolVersion === 5) {
  7468. var properties = this._parseProperties()
  7469. if (Object.getOwnPropertyNames(properties).length) {
  7470. packet.properties = properties
  7471. }
  7472. }
  7473. while (this._pos < packet.length) {
  7474. var topic
  7475. // Parse topic
  7476. topic = this._parseString()
  7477. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  7478. // Push topic to unsubscriptions
  7479. packet.unsubscriptions.push(topic)
  7480. }
  7481. }
  7482. Parser.prototype._parseUnsuback = function () {
  7483. var packet = this.packet
  7484. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  7485. // Properties mqtt 5
  7486. if (this.settings.protocolVersion === 5) {
  7487. var properties = this._parseProperties()
  7488. if (Object.getOwnPropertyNames(properties).length) {
  7489. packet.properties = properties
  7490. }
  7491. // Parse granted QoSes
  7492. packet.granted = []
  7493. while (this._pos < this.packet.length) {
  7494. this.packet.granted.push(this._list.readUInt8(this._pos++))
  7495. }
  7496. }
  7497. }
  7498. // parse packets like puback, pubrec, pubrel, pubcomp
  7499. Parser.prototype._parseConfirmation = function () {
  7500. var packet = this.packet
  7501. this._parseMessageId()
  7502. if (this.settings.protocolVersion === 5) {
  7503. if (packet.length > 2) {
  7504. // response code
  7505. packet.reasonCode = this._parseByte()
  7506. // properies mqtt 5
  7507. var properties = this._parseProperties()
  7508. if (Object.getOwnPropertyNames(properties).length) {
  7509. packet.properties = properties
  7510. }
  7511. }
  7512. }
  7513. return true
  7514. }
  7515. // parse disconnect packet
  7516. Parser.prototype._parseDisconnect = function () {
  7517. var packet = this.packet
  7518. if (this.settings.protocolVersion === 5) {
  7519. // response code
  7520. packet.reasonCode = this._parseByte()
  7521. // properies mqtt 5
  7522. var properties = this._parseProperties()
  7523. if (Object.getOwnPropertyNames(properties).length) {
  7524. packet.properties = properties
  7525. }
  7526. }
  7527. return true
  7528. }
  7529. // parse auth packet
  7530. Parser.prototype._parseAuth = function () {
  7531. var packet = this.packet
  7532. if (this.settings.protocolVersion !== 5) {
  7533. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  7534. }
  7535. // response code
  7536. packet.reasonCode = this._parseByte()
  7537. // properies mqtt 5
  7538. var properties = this._parseProperties()
  7539. if (Object.getOwnPropertyNames(properties).length) {
  7540. packet.properties = properties
  7541. }
  7542. return true
  7543. }
  7544. Parser.prototype._parseMessageId = function () {
  7545. var packet = this.packet
  7546. packet.messageId = this._parseNum()
  7547. if (packet.messageId === null) {
  7548. this._emitError(new Error('Cannot parse messageId'))
  7549. return false
  7550. }
  7551. return true
  7552. }
  7553. Parser.prototype._parseString = function (maybeBuffer) {
  7554. var length = this._parseNum()
  7555. var result
  7556. var end = length + this._pos
  7557. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  7558. result = this._list.toString('utf8', this._pos, end)
  7559. this._pos += length
  7560. return result
  7561. }
  7562. Parser.prototype._parseStringPair = function () {
  7563. return {
  7564. name: this._parseString(),
  7565. value: this._parseString()
  7566. }
  7567. }
  7568. Parser.prototype._parseBuffer = function () {
  7569. var length = this._parseNum()
  7570. var result
  7571. var end = length + this._pos
  7572. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  7573. result = this._list.slice(this._pos, end)
  7574. this._pos += length
  7575. return result
  7576. }
  7577. Parser.prototype._parseNum = function () {
  7578. if (this._list.length - this._pos < 2) return -1
  7579. var result = this._list.readUInt16BE(this._pos)
  7580. this._pos += 2
  7581. return result
  7582. }
  7583. Parser.prototype._parse4ByteNum = function () {
  7584. if (this._list.length - this._pos < 4) return -1
  7585. var result = this._list.readUInt32BE(this._pos)
  7586. this._pos += 4
  7587. return result
  7588. }
  7589. Parser.prototype._parseVarByteNum = function (fullInfoFlag) {
  7590. var bytes = 0
  7591. var mul = 1
  7592. var length = 0
  7593. var result = true
  7594. var current
  7595. var padding = this._pos ? this._pos : 0
  7596. while (bytes < 5) {
  7597. current = this._list.readUInt8(padding + bytes++)
  7598. length += mul * (current & constants.LENGTH_MASK)
  7599. mul *= 0x80
  7600. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  7601. if (this._list.length <= bytes) {
  7602. result = false
  7603. break
  7604. }
  7605. }
  7606. if (padding) {
  7607. this._pos += bytes
  7608. }
  7609. result = result
  7610. ? fullInfoFlag ? {
  7611. bytes: bytes,
  7612. value: length
  7613. } : length
  7614. : false
  7615. return result
  7616. }
  7617. Parser.prototype._parseByte = function () {
  7618. var result = this._list.readUInt8(this._pos)
  7619. this._pos++
  7620. return result
  7621. }
  7622. Parser.prototype._parseByType = function (type) {
  7623. switch (type) {
  7624. case 'byte': {
  7625. return this._parseByte() !== 0
  7626. }
  7627. case 'int8': {
  7628. return this._parseByte()
  7629. }
  7630. case 'int16': {
  7631. return this._parseNum()
  7632. }
  7633. case 'int32': {
  7634. return this._parse4ByteNum()
  7635. }
  7636. case 'var': {
  7637. return this._parseVarByteNum()
  7638. }
  7639. case 'string': {
  7640. return this._parseString()
  7641. }
  7642. case 'pair': {
  7643. return this._parseStringPair()
  7644. }
  7645. case 'binary': {
  7646. return this._parseBuffer()
  7647. }
  7648. }
  7649. }
  7650. Parser.prototype._parseProperties = function () {
  7651. var length = this._parseVarByteNum()
  7652. var start = this._pos
  7653. var end = start + length
  7654. var result = {}
  7655. while (this._pos < end) {
  7656. var type = this._parseByte()
  7657. var name = constants.propertiesCodes[type]
  7658. if (!name) {
  7659. this._emitError(new Error('Unknown property'))
  7660. return false
  7661. }
  7662. // user properties process
  7663. if (name === 'userProperties') {
  7664. if (!result[name]) {
  7665. result[name] = {}
  7666. }
  7667. var currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  7668. result[name][currentUserProperty.name] = currentUserProperty.value
  7669. continue
  7670. }
  7671. result[name] = this._parseByType(constants.propertiesTypes[name])
  7672. }
  7673. return result
  7674. }
  7675. Parser.prototype._newPacket = function () {
  7676. if (this.packet) {
  7677. this._list.consume(this.packet.length)
  7678. this.emit('packet', this.packet)
  7679. }
  7680. this.packet = new Packet()
  7681. this._pos = 0
  7682. return true
  7683. }
  7684. Parser.prototype._emitError = function (err) {
  7685. this.error = err
  7686. this.emit('error', err)
  7687. }
  7688. module.exports = Parser
  7689. },{"./constants":90,"./packet":95,"bl":93,"events":83,"inherits":88}],97:[function(require,module,exports){
  7690. 'use strict'
  7691. var protocol = require('./constants')
  7692. var Buffer = require('safe-buffer').Buffer
  7693. var empty = Buffer.allocUnsafe(0)
  7694. var zeroBuf = Buffer.from([0])
  7695. var numbers = require('./numbers')
  7696. var nextTick = require('process-nextick-args').nextTick
  7697. var numCache = numbers.cache
  7698. var generateNumber = numbers.generateNumber
  7699. var generateCache = numbers.generateCache
  7700. var genBufVariableByteInt = numbers.genBufVariableByteInt
  7701. var generate4ByteBuffer = numbers.generate4ByteBuffer
  7702. var writeNumber = writeNumberCached
  7703. var toGenerate = true
  7704. function generate (packet, stream, opts) {
  7705. if (stream.cork) {
  7706. stream.cork()
  7707. nextTick(uncork, stream)
  7708. }
  7709. if (toGenerate) {
  7710. toGenerate = false
  7711. generateCache()
  7712. }
  7713. switch (packet.cmd) {
  7714. case 'connect':
  7715. return connect(packet, stream, opts)
  7716. case 'connack':
  7717. return connack(packet, stream, opts)
  7718. case 'publish':
  7719. return publish(packet, stream, opts)
  7720. case 'puback':
  7721. case 'pubrec':
  7722. case 'pubrel':
  7723. case 'pubcomp':
  7724. return confirmation(packet, stream, opts)
  7725. case 'subscribe':
  7726. return subscribe(packet, stream, opts)
  7727. case 'suback':
  7728. return suback(packet, stream, opts)
  7729. case 'unsubscribe':
  7730. return unsubscribe(packet, stream, opts)
  7731. case 'unsuback':
  7732. return unsuback(packet, stream, opts)
  7733. case 'pingreq':
  7734. case 'pingresp':
  7735. return emptyPacket(packet, stream, opts)
  7736. case 'disconnect':
  7737. return disconnect(packet, stream, opts)
  7738. case 'auth':
  7739. return auth(packet, stream, opts)
  7740. default:
  7741. stream.emit('error', new Error('Unknown command'))
  7742. return false
  7743. }
  7744. }
  7745. /**
  7746. * Controls numbers cache.
  7747. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  7748. */
  7749. Object.defineProperty(generate, 'cacheNumbers', {
  7750. get: function () {
  7751. return writeNumber === writeNumberCached
  7752. },
  7753. set: function (value) {
  7754. if (value) {
  7755. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  7756. writeNumber = writeNumberCached
  7757. } else {
  7758. toGenerate = false
  7759. writeNumber = writeNumberGenerated
  7760. }
  7761. }
  7762. })
  7763. function uncork (stream) {
  7764. stream.uncork()
  7765. }
  7766. function connect (packet, stream, opts) {
  7767. var settings = packet || {}
  7768. var protocolId = settings.protocolId || 'MQTT'
  7769. var protocolVersion = settings.protocolVersion || 4
  7770. var will = settings.will
  7771. var clean = settings.clean
  7772. var keepalive = settings.keepalive || 0
  7773. var clientId = settings.clientId || ''
  7774. var username = settings.username
  7775. var password = settings.password
  7776. /* mqtt5 new oprions */
  7777. var properties = settings.properties
  7778. if (clean === undefined) clean = true
  7779. var length = 0
  7780. // Must be a string and non-falsy
  7781. if (!protocolId ||
  7782. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  7783. stream.emit('error', new Error('Invalid protocolId'))
  7784. return false
  7785. } else length += protocolId.length + 2
  7786. // Must be 3 or 4 or 5
  7787. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  7788. stream.emit('error', new Error('Invalid protocol version'))
  7789. return false
  7790. } else length += 1
  7791. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  7792. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  7793. (clientId || protocolVersion === 4) && (clientId || clean)) {
  7794. length += clientId.length + 2
  7795. } else {
  7796. if (protocolVersion < 4) {
  7797. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  7798. return false
  7799. }
  7800. if ((clean * 1) === 0) {
  7801. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  7802. return false
  7803. }
  7804. }
  7805. // Must be a two byte number
  7806. if (typeof keepalive !== 'number' ||
  7807. keepalive < 0 ||
  7808. keepalive > 65535 ||
  7809. keepalive % 1 !== 0) {
  7810. stream.emit('error', new Error('Invalid keepalive'))
  7811. return false
  7812. } else length += 2
  7813. // Connect flags
  7814. length += 1
  7815. // Properties
  7816. if (protocolVersion === 5) {
  7817. var propertiesData = getProperties(stream, properties)
  7818. length += propertiesData.length
  7819. }
  7820. // If will exists...
  7821. if (will) {
  7822. // It must be an object
  7823. if (typeof will !== 'object') {
  7824. stream.emit('error', new Error('Invalid will'))
  7825. return false
  7826. }
  7827. // It must have topic typeof string
  7828. if (!will.topic || typeof will.topic !== 'string') {
  7829. stream.emit('error', new Error('Invalid will topic'))
  7830. return false
  7831. } else {
  7832. length += Buffer.byteLength(will.topic) + 2
  7833. }
  7834. // Payload
  7835. if (will.payload) {
  7836. if (will.payload.length >= 0) {
  7837. if (typeof will.payload === 'string') {
  7838. length += Buffer.byteLength(will.payload) + 2
  7839. } else {
  7840. length += will.payload.length + 2
  7841. }
  7842. } else {
  7843. stream.emit('error', new Error('Invalid will payload'))
  7844. return false
  7845. }
  7846. // will properties
  7847. var willProperties = {}
  7848. if (protocolVersion === 5) {
  7849. willProperties = getProperties(stream, will.properties)
  7850. length += willProperties.length
  7851. }
  7852. }
  7853. }
  7854. // Username
  7855. var providedUsername = false
  7856. if (username != null) {
  7857. if (isStringOrBuffer(username)) {
  7858. providedUsername = true
  7859. length += Buffer.byteLength(username) + 2
  7860. } else {
  7861. stream.emit('error', new Error('Invalid username'))
  7862. return false
  7863. }
  7864. }
  7865. // Password
  7866. if (password != null) {
  7867. if (!providedUsername) {
  7868. stream.emit('error', new Error('Username is required to use password'))
  7869. return false
  7870. }
  7871. if (isStringOrBuffer(password)) {
  7872. length += byteLength(password) + 2
  7873. } else {
  7874. stream.emit('error', new Error('Invalid password'))
  7875. return false
  7876. }
  7877. }
  7878. // Generate header
  7879. stream.write(protocol.CONNECT_HEADER)
  7880. // Generate length
  7881. writeVarByteInt(stream, length)
  7882. // Generate protocol ID
  7883. writeStringOrBuffer(stream, protocolId)
  7884. stream.write(
  7885. protocolVersion === 4
  7886. ? protocol.VERSION4
  7887. : protocolVersion === 5
  7888. ? protocol.VERSION5
  7889. : protocol.VERSION3
  7890. )
  7891. // Connect flags
  7892. var flags = 0
  7893. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  7894. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  7895. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  7896. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  7897. flags |= will ? protocol.WILL_FLAG_MASK : 0
  7898. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  7899. stream.write(Buffer.from([flags]))
  7900. // Keepalive
  7901. writeNumber(stream, keepalive)
  7902. // Properties
  7903. if (protocolVersion === 5) {
  7904. propertiesData.write()
  7905. }
  7906. // Client ID
  7907. writeStringOrBuffer(stream, clientId)
  7908. // Will
  7909. if (will) {
  7910. if (protocolVersion === 5) {
  7911. willProperties.write()
  7912. }
  7913. writeString(stream, will.topic)
  7914. writeStringOrBuffer(stream, will.payload)
  7915. }
  7916. // Username and password
  7917. if (username != null) {
  7918. writeStringOrBuffer(stream, username)
  7919. }
  7920. if (password != null) {
  7921. writeStringOrBuffer(stream, password)
  7922. }
  7923. // This is a small packet that happens only once on a stream
  7924. // We assume the stream is always free to receive more data after this
  7925. return true
  7926. }
  7927. function connack (packet, stream, opts) {
  7928. var version = opts ? opts.protocolVersion : 4
  7929. var settings = packet || {}
  7930. var rc = version === 5 ? settings.reasonCode : settings.returnCode
  7931. var properties = settings.properties
  7932. var length = 2 // length of rc and sessionHeader
  7933. // Check return code
  7934. if (typeof rc !== 'number') {
  7935. stream.emit('error', new Error('Invalid return code'))
  7936. return false
  7937. }
  7938. // mqtt5 properties
  7939. var propertiesData = null
  7940. if (version === 5) {
  7941. propertiesData = getProperties(stream, properties)
  7942. length += propertiesData.length
  7943. }
  7944. stream.write(protocol.CONNACK_HEADER)
  7945. // length
  7946. writeVarByteInt(stream, length)
  7947. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  7948. stream.write(Buffer.from([rc]))
  7949. if (propertiesData != null) {
  7950. propertiesData.write()
  7951. }
  7952. return true
  7953. }
  7954. function publish (packet, stream, opts) {
  7955. var version = opts ? opts.protocolVersion : 4
  7956. var settings = packet || {}
  7957. var qos = settings.qos || 0
  7958. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  7959. var topic = settings.topic
  7960. var payload = settings.payload || empty
  7961. var id = settings.messageId
  7962. var properties = settings.properties
  7963. var length = 0
  7964. // Topic must be a non-empty string or Buffer
  7965. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  7966. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  7967. else {
  7968. stream.emit('error', new Error('Invalid topic'))
  7969. return false
  7970. }
  7971. // Get the payload length
  7972. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  7973. else length += payload.length
  7974. // Message ID must a number if qos > 0
  7975. if (qos && typeof id !== 'number') {
  7976. stream.emit('error', new Error('Invalid messageId'))
  7977. return false
  7978. } else if (qos) length += 2
  7979. // mqtt5 properties
  7980. var propertiesData = null
  7981. if (version === 5) {
  7982. propertiesData = getProperties(stream, properties)
  7983. length += propertiesData.length
  7984. }
  7985. // Header
  7986. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  7987. // Remaining length
  7988. writeVarByteInt(stream, length)
  7989. // Topic
  7990. writeNumber(stream, byteLength(topic))
  7991. stream.write(topic)
  7992. // Message ID
  7993. if (qos > 0) writeNumber(stream, id)
  7994. // Properties
  7995. if (propertiesData != null) {
  7996. propertiesData.write()
  7997. }
  7998. // Payload
  7999. return stream.write(payload)
  8000. }
  8001. /* Puback, pubrec, pubrel and pubcomp */
  8002. function confirmation (packet, stream, opts) {
  8003. var version = opts ? opts.protocolVersion : 4
  8004. var settings = packet || {}
  8005. var type = settings.cmd || 'puback'
  8006. var id = settings.messageId
  8007. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  8008. var qos = 0
  8009. var reasonCode = settings.reasonCode
  8010. var properties = settings.properties
  8011. var length = version === 5 ? 3 : 2
  8012. if (type === 'pubrel') qos = 1
  8013. // Check message ID
  8014. if (typeof id !== 'number') {
  8015. stream.emit('error', new Error('Invalid messageId'))
  8016. return false
  8017. }
  8018. // properies mqtt 5
  8019. var propertiesData = null
  8020. if (version === 5) {
  8021. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  8022. if (!propertiesData) { return false }
  8023. length += propertiesData.length
  8024. }
  8025. // Header
  8026. stream.write(protocol.ACKS[type][qos][dup][0])
  8027. // Length
  8028. writeVarByteInt(stream, length)
  8029. // Message ID
  8030. writeNumber(stream, id)
  8031. // reason code in header
  8032. if (version === 5) {
  8033. stream.write(Buffer.from([reasonCode]))
  8034. }
  8035. // properies mqtt 5
  8036. if (propertiesData !== null) {
  8037. propertiesData.write()
  8038. }
  8039. return true
  8040. }
  8041. function subscribe (packet, stream, opts) {
  8042. var version = opts ? opts.protocolVersion : 4
  8043. var settings = packet || {}
  8044. var dup = settings.dup ? protocol.DUP_MASK : 0
  8045. var id = settings.messageId
  8046. var subs = settings.subscriptions
  8047. var properties = settings.properties
  8048. var length = 0
  8049. // Check message ID
  8050. if (typeof id !== 'number') {
  8051. stream.emit('error', new Error('Invalid messageId'))
  8052. return false
  8053. } else length += 2
  8054. // properies mqtt 5
  8055. var propertiesData = null
  8056. if (version === 5) {
  8057. propertiesData = getProperties(stream, properties)
  8058. length += propertiesData.length
  8059. }
  8060. // Check subscriptions
  8061. if (typeof subs === 'object' && subs.length) {
  8062. for (var i = 0; i < subs.length; i += 1) {
  8063. var itopic = subs[i].topic
  8064. var iqos = subs[i].qos
  8065. if (typeof itopic !== 'string') {
  8066. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  8067. return false
  8068. }
  8069. if (typeof iqos !== 'number') {
  8070. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  8071. return false
  8072. }
  8073. if (version === 5) {
  8074. var nl = subs[i].nl || false
  8075. if (typeof nl !== 'boolean') {
  8076. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  8077. return false
  8078. }
  8079. var rap = subs[i].rap || false
  8080. if (typeof rap !== 'boolean') {
  8081. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  8082. return false
  8083. }
  8084. var rh = subs[i].rh || 0
  8085. if (typeof rh !== 'number' || rh > 2) {
  8086. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  8087. return false
  8088. }
  8089. }
  8090. length += Buffer.byteLength(itopic) + 2 + 1
  8091. }
  8092. } else {
  8093. stream.emit('error', new Error('Invalid subscriptions'))
  8094. return false
  8095. }
  8096. // Generate header
  8097. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  8098. // Generate length
  8099. writeVarByteInt(stream, length)
  8100. // Generate message ID
  8101. writeNumber(stream, id)
  8102. // properies mqtt 5
  8103. if (propertiesData !== null) {
  8104. propertiesData.write()
  8105. }
  8106. var result = true
  8107. // Generate subs
  8108. for (var j = 0; j < subs.length; j++) {
  8109. var sub = subs[j]
  8110. var jtopic = sub.topic
  8111. var jqos = sub.qos
  8112. var jnl = +sub.nl
  8113. var jrap = +sub.rap
  8114. var jrh = sub.rh
  8115. var joptions
  8116. // Write topic string
  8117. writeString(stream, jtopic)
  8118. // options process
  8119. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  8120. if (version === 5) {
  8121. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  8122. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  8123. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  8124. }
  8125. // Write options
  8126. result = stream.write(Buffer.from([joptions]))
  8127. }
  8128. return result
  8129. }
  8130. function suback (packet, stream, opts) {
  8131. var version = opts ? opts.protocolVersion : 4
  8132. var settings = packet || {}
  8133. var id = settings.messageId
  8134. var granted = settings.granted
  8135. var properties = settings.properties
  8136. var length = 0
  8137. // Check message ID
  8138. if (typeof id !== 'number') {
  8139. stream.emit('error', new Error('Invalid messageId'))
  8140. return false
  8141. } else length += 2
  8142. // Check granted qos vector
  8143. if (typeof granted === 'object' && granted.length) {
  8144. for (var i = 0; i < granted.length; i += 1) {
  8145. if (typeof granted[i] !== 'number') {
  8146. stream.emit('error', new Error('Invalid qos vector'))
  8147. return false
  8148. }
  8149. length += 1
  8150. }
  8151. } else {
  8152. stream.emit('error', new Error('Invalid qos vector'))
  8153. return false
  8154. }
  8155. // properies mqtt 5
  8156. var propertiesData = null
  8157. if (version === 5) {
  8158. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  8159. if (!propertiesData) { return false }
  8160. length += propertiesData.length
  8161. }
  8162. // header
  8163. stream.write(protocol.SUBACK_HEADER)
  8164. // Length
  8165. writeVarByteInt(stream, length)
  8166. // Message ID
  8167. writeNumber(stream, id)
  8168. // properies mqtt 5
  8169. if (propertiesData !== null) {
  8170. propertiesData.write()
  8171. }
  8172. return stream.write(Buffer.from(granted))
  8173. }
  8174. function unsubscribe (packet, stream, opts) {
  8175. var version = opts ? opts.protocolVersion : 4
  8176. var settings = packet || {}
  8177. var id = settings.messageId
  8178. var dup = settings.dup ? protocol.DUP_MASK : 0
  8179. var unsubs = settings.unsubscriptions
  8180. var properties = settings.properties
  8181. var length = 0
  8182. // Check message ID
  8183. if (typeof id !== 'number') {
  8184. stream.emit('error', new Error('Invalid messageId'))
  8185. return false
  8186. } else {
  8187. length += 2
  8188. }
  8189. // Check unsubs
  8190. if (typeof unsubs === 'object' && unsubs.length) {
  8191. for (var i = 0; i < unsubs.length; i += 1) {
  8192. if (typeof unsubs[i] !== 'string') {
  8193. stream.emit('error', new Error('Invalid unsubscriptions'))
  8194. return false
  8195. }
  8196. length += Buffer.byteLength(unsubs[i]) + 2
  8197. }
  8198. } else {
  8199. stream.emit('error', new Error('Invalid unsubscriptions'))
  8200. return false
  8201. }
  8202. // properies mqtt 5
  8203. var propertiesData = null
  8204. if (version === 5) {
  8205. propertiesData = getProperties(stream, properties)
  8206. length += propertiesData.length
  8207. }
  8208. // Header
  8209. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  8210. // Length
  8211. writeVarByteInt(stream, length)
  8212. // Message ID
  8213. writeNumber(stream, id)
  8214. // properies mqtt 5
  8215. if (propertiesData !== null) {
  8216. propertiesData.write()
  8217. }
  8218. // Unsubs
  8219. var result = true
  8220. for (var j = 0; j < unsubs.length; j++) {
  8221. result = writeString(stream, unsubs[j])
  8222. }
  8223. return result
  8224. }
  8225. function unsuback (packet, stream, opts) {
  8226. var version = opts ? opts.protocolVersion : 4
  8227. var settings = packet || {}
  8228. var id = settings.messageId
  8229. var dup = settings.dup ? protocol.DUP_MASK : 0
  8230. var granted = settings.granted
  8231. var properties = settings.properties
  8232. var type = settings.cmd
  8233. var qos = 0
  8234. var length = 2
  8235. // Check message ID
  8236. if (typeof id !== 'number') {
  8237. stream.emit('error', new Error('Invalid messageId'))
  8238. return false
  8239. }
  8240. // Check granted
  8241. if (version === 5) {
  8242. if (typeof granted === 'object' && granted.length) {
  8243. for (var i = 0; i < granted.length; i += 1) {
  8244. if (typeof granted[i] !== 'number') {
  8245. stream.emit('error', new Error('Invalid qos vector'))
  8246. return false
  8247. }
  8248. length += 1
  8249. }
  8250. } else {
  8251. stream.emit('error', new Error('Invalid qos vector'))
  8252. return false
  8253. }
  8254. }
  8255. // properies mqtt 5
  8256. var propertiesData = null
  8257. if (version === 5) {
  8258. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  8259. if (!propertiesData) { return false }
  8260. length += propertiesData.length
  8261. }
  8262. // Header
  8263. stream.write(protocol.ACKS[type][qos][dup][0])
  8264. // Length
  8265. writeVarByteInt(stream, length)
  8266. // Message ID
  8267. writeNumber(stream, id)
  8268. // properies mqtt 5
  8269. if (propertiesData !== null) {
  8270. propertiesData.write()
  8271. }
  8272. // payload
  8273. if (version === 5) {
  8274. stream.write(Buffer.from(granted))
  8275. }
  8276. return true
  8277. }
  8278. function emptyPacket (packet, stream, opts) {
  8279. return stream.write(protocol.EMPTY[packet.cmd])
  8280. }
  8281. function disconnect (packet, stream, opts) {
  8282. var version = opts ? opts.protocolVersion : 4
  8283. var settings = packet || {}
  8284. var reasonCode = settings.reasonCode
  8285. var properties = settings.properties
  8286. var length = version === 5 ? 1 : 0
  8287. // properies mqtt 5
  8288. var propertiesData = null
  8289. if (version === 5) {
  8290. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  8291. if (!propertiesData) { return false }
  8292. length += propertiesData.length
  8293. }
  8294. // Header
  8295. stream.write(Buffer.from([protocol.codes['disconnect'] << 4]))
  8296. // Length
  8297. writeVarByteInt(stream, length)
  8298. // reason code in header
  8299. if (version === 5) {
  8300. stream.write(Buffer.from([reasonCode]))
  8301. }
  8302. // properies mqtt 5
  8303. if (propertiesData !== null) {
  8304. propertiesData.write()
  8305. }
  8306. return true
  8307. }
  8308. function auth (packet, stream, opts) {
  8309. var version = opts ? opts.protocolVersion : 4
  8310. var settings = packet || {}
  8311. var reasonCode = settings.reasonCode
  8312. var properties = settings.properties
  8313. var length = version === 5 ? 1 : 0
  8314. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  8315. // properies mqtt 5
  8316. var propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  8317. if (!propertiesData) { return false }
  8318. length += propertiesData.length
  8319. // Header
  8320. stream.write(Buffer.from([protocol.codes['auth'] << 4]))
  8321. // Length
  8322. writeVarByteInt(stream, length)
  8323. // reason code in header
  8324. stream.write(Buffer.from([reasonCode]))
  8325. // properies mqtt 5
  8326. if (propertiesData !== null) {
  8327. propertiesData.write()
  8328. }
  8329. return true
  8330. }
  8331. /**
  8332. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  8333. *
  8334. * @param <Buffer> buffer - destination
  8335. * @param <Number> pos - offset
  8336. * @param <Number> length - length (>0)
  8337. * @returns <Number> number of bytes written
  8338. *
  8339. * @api private
  8340. */
  8341. var varByteIntCache = {}
  8342. function writeVarByteInt (stream, num) {
  8343. var buffer = varByteIntCache[num]
  8344. if (!buffer) {
  8345. buffer = genBufVariableByteInt(num).data
  8346. if (num < 16384) varByteIntCache[num] = buffer
  8347. }
  8348. stream.write(buffer)
  8349. }
  8350. /**
  8351. * writeString - write a utf8 string to the buffer
  8352. *
  8353. * @param <Buffer> buffer - destination
  8354. * @param <Number> pos - offset
  8355. * @param <String> string - string to write
  8356. * @return <Number> number of bytes written
  8357. *
  8358. * @api private
  8359. */
  8360. function writeString (stream, string) {
  8361. var strlen = Buffer.byteLength(string)
  8362. writeNumber(stream, strlen)
  8363. stream.write(string, 'utf8')
  8364. }
  8365. /**
  8366. * writeStringPair - write a utf8 string pairs to the buffer
  8367. *
  8368. * @param <Buffer> buffer - destination
  8369. * @param <String> name - string name to write
  8370. * @param <String> value - string value to write
  8371. * @return <Number> number of bytes written
  8372. *
  8373. * @api private
  8374. */
  8375. function writeStringPair (stream, name, value) {
  8376. writeString(stream, name)
  8377. writeString(stream, value)
  8378. }
  8379. /**
  8380. * writeNumber - write a two byte number to the buffer
  8381. *
  8382. * @param <Buffer> buffer - destination
  8383. * @param <Number> pos - offset
  8384. * @param <String> number - number to write
  8385. * @return <Number> number of bytes written
  8386. *
  8387. * @api private
  8388. */
  8389. function writeNumberCached (stream, number) {
  8390. return stream.write(numCache[number])
  8391. }
  8392. function writeNumberGenerated (stream, number) {
  8393. return stream.write(generateNumber(number))
  8394. }
  8395. function write4ByteNumber (stream, number) {
  8396. return stream.write(generate4ByteBuffer(number))
  8397. }
  8398. /**
  8399. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  8400. *
  8401. * @param <Buffer> buffer - destination
  8402. * @param <Number> pos - offset
  8403. * @param <String> toWrite - String or Buffer
  8404. * @return <Number> number of bytes written
  8405. */
  8406. function writeStringOrBuffer (stream, toWrite) {
  8407. if (typeof toWrite === 'string') {
  8408. writeString(stream, toWrite)
  8409. } else if (toWrite) {
  8410. writeNumber(stream, toWrite.length)
  8411. stream.write(toWrite)
  8412. } else writeNumber(stream, 0)
  8413. }
  8414. function getProperties (stream, properties) {
  8415. /* connect properties */
  8416. if (typeof properties !== 'object' || properties.length != null) {
  8417. return {
  8418. length: 1,
  8419. write: function () {
  8420. writeProperties(stream, {}, 0)
  8421. }
  8422. }
  8423. }
  8424. var propertiesLength = 0
  8425. function getLengthProperty (name) {
  8426. var type = protocol.propertiesTypes[name]
  8427. var value = properties[name]
  8428. var length = 0
  8429. switch (type) {
  8430. case 'byte': {
  8431. if (typeof value !== 'boolean') {
  8432. stream.emit('error', new Error('Invalid ' + name))
  8433. return false
  8434. }
  8435. length += 1 + 1
  8436. break
  8437. }
  8438. case 'int8': {
  8439. if (typeof value !== 'number') {
  8440. stream.emit('error', new Error('Invalid ' + name))
  8441. return false
  8442. }
  8443. length += 1 + 1
  8444. break
  8445. }
  8446. case 'binary': {
  8447. if (value && value === null) {
  8448. stream.emit('error', new Error('Invalid ' + name))
  8449. return false
  8450. }
  8451. length += 1 + Buffer.byteLength(value) + 2
  8452. break
  8453. }
  8454. case 'int16': {
  8455. if (typeof value !== 'number') {
  8456. stream.emit('error', new Error('Invalid ' + name))
  8457. return false
  8458. }
  8459. length += 1 + 2
  8460. break
  8461. }
  8462. case 'int32': {
  8463. if (typeof value !== 'number') {
  8464. stream.emit('error', new Error('Invalid ' + name))
  8465. return false
  8466. }
  8467. length += 1 + 4
  8468. break
  8469. }
  8470. case 'var': {
  8471. if (typeof value !== 'number') {
  8472. stream.emit('error', new Error('Invalid ' + name))
  8473. return false
  8474. }
  8475. length += 1 + genBufVariableByteInt(value).length
  8476. break
  8477. }
  8478. case 'string': {
  8479. if (typeof value !== 'string') {
  8480. stream.emit('error', new Error('Invalid ' + name))
  8481. return false
  8482. }
  8483. length += 1 + 2 + Buffer.byteLength(value.toString())
  8484. break
  8485. }
  8486. case 'pair': {
  8487. if (typeof value !== 'object') {
  8488. stream.emit('error', new Error('Invalid ' + name))
  8489. return false
  8490. }
  8491. length += Object.getOwnPropertyNames(value).reduce(function (result, name) {
  8492. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  8493. return result
  8494. }, 0)
  8495. break
  8496. }
  8497. default: {
  8498. stream.emit('error', new Error('Invalid property ' + name))
  8499. return false
  8500. }
  8501. }
  8502. return length
  8503. }
  8504. if (properties) {
  8505. for (var propName in properties) {
  8506. var propLength = getLengthProperty(propName)
  8507. if (!propLength) return false
  8508. propertiesLength += propLength
  8509. }
  8510. }
  8511. var propertiesLengthLength = genBufVariableByteInt(propertiesLength).length
  8512. return {
  8513. length: propertiesLengthLength + propertiesLength,
  8514. write: function () {
  8515. writeProperties(stream, properties, propertiesLength)
  8516. }
  8517. }
  8518. }
  8519. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  8520. var mayEmptyProps = ['reasonString', 'userProperties']
  8521. var maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  8522. var propertiesData = getProperties(stream, properties)
  8523. if (maximumPacketSize) {
  8524. while (length + propertiesData.length > maximumPacketSize) {
  8525. var currentMayEmptyProp = mayEmptyProps.shift()
  8526. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  8527. delete properties[currentMayEmptyProp]
  8528. propertiesData = getProperties(stream, properties)
  8529. } else {
  8530. return false
  8531. }
  8532. }
  8533. }
  8534. return propertiesData
  8535. }
  8536. function writeProperties (stream, properties, propertiesLength) {
  8537. /* write properties to stream */
  8538. writeVarByteInt(stream, propertiesLength)
  8539. for (var propName in properties) {
  8540. if (properties.hasOwnProperty(propName) && properties[propName] !== null) {
  8541. var value = properties[propName]
  8542. var type = protocol.propertiesTypes[propName]
  8543. switch (type) {
  8544. case 'byte': {
  8545. stream.write(Buffer.from([protocol.properties[propName]]))
  8546. stream.write(Buffer.from([+value]))
  8547. break
  8548. }
  8549. case 'int8': {
  8550. stream.write(Buffer.from([protocol.properties[propName]]))
  8551. stream.write(Buffer.from([value]))
  8552. break
  8553. }
  8554. case 'binary': {
  8555. stream.write(Buffer.from([protocol.properties[propName]]))
  8556. writeStringOrBuffer(stream, value)
  8557. break
  8558. }
  8559. case 'int16': {
  8560. stream.write(Buffer.from([protocol.properties[propName]]))
  8561. writeNumber(stream, value)
  8562. break
  8563. }
  8564. case 'int32': {
  8565. stream.write(Buffer.from([protocol.properties[propName]]))
  8566. write4ByteNumber(stream, value)
  8567. break
  8568. }
  8569. case 'var': {
  8570. stream.write(Buffer.from([protocol.properties[propName]]))
  8571. writeVarByteInt(stream, value)
  8572. break
  8573. }
  8574. case 'string': {
  8575. stream.write(Buffer.from([protocol.properties[propName]]))
  8576. writeString(stream, value)
  8577. break
  8578. }
  8579. case 'pair': {
  8580. Object.getOwnPropertyNames(value).forEach(function (name) {
  8581. stream.write(Buffer.from([protocol.properties[propName]]))
  8582. writeStringPair(stream, name.toString(), value[name].toString())
  8583. })
  8584. break
  8585. }
  8586. default: {
  8587. stream.emit('error', new Error('Invalid property ' + propName))
  8588. return false
  8589. }
  8590. }
  8591. }
  8592. }
  8593. }
  8594. function byteLength (bufOrString) {
  8595. if (!bufOrString) return 0
  8596. else if (bufOrString instanceof Buffer) return bufOrString.length
  8597. else return Buffer.byteLength(bufOrString)
  8598. }
  8599. function isStringOrBuffer (field) {
  8600. return typeof field === 'string' || field instanceof Buffer
  8601. }
  8602. module.exports = generate
  8603. },{"./constants":90,"./numbers":94,"process-nextick-args":99,"safe-buffer":118}],98:[function(require,module,exports){
  8604. var wrappy = require('wrappy')
  8605. module.exports = wrappy(once)
  8606. module.exports.strict = wrappy(onceStrict)
  8607. once.proto = once(function () {
  8608. Object.defineProperty(Function.prototype, 'once', {
  8609. value: function () {
  8610. return once(this)
  8611. },
  8612. configurable: true
  8613. })
  8614. Object.defineProperty(Function.prototype, 'onceStrict', {
  8615. value: function () {
  8616. return onceStrict(this)
  8617. },
  8618. configurable: true
  8619. })
  8620. })
  8621. function once (fn) {
  8622. var f = function () {
  8623. if (f.called) return f.value
  8624. f.called = true
  8625. return f.value = fn.apply(this, arguments)
  8626. }
  8627. f.called = false
  8628. return f
  8629. }
  8630. function onceStrict (fn) {
  8631. var f = function () {
  8632. if (f.called)
  8633. throw new Error(f.onceError)
  8634. f.called = true
  8635. return f.value = fn.apply(this, arguments)
  8636. }
  8637. var name = fn.name || 'Function wrapped with `once`'
  8638. f.onceError = name + " shouldn't be called more than once"
  8639. f.called = false
  8640. return f
  8641. }
  8642. },{"wrappy":139}],99:[function(require,module,exports){
  8643. (function (process){
  8644. 'use strict';
  8645. if (typeof process === 'undefined' ||
  8646. !process.version ||
  8647. process.version.indexOf('v0.') === 0 ||
  8648. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  8649. module.exports = { nextTick: nextTick };
  8650. } else {
  8651. module.exports = process
  8652. }
  8653. function nextTick(fn, arg1, arg2, arg3) {
  8654. if (typeof fn !== 'function') {
  8655. throw new TypeError('"callback" argument must be a function');
  8656. }
  8657. var len = arguments.length;
  8658. var args, i;
  8659. switch (len) {
  8660. case 0:
  8661. case 1:
  8662. return process.nextTick(fn);
  8663. case 2:
  8664. return process.nextTick(function afterTickOne() {
  8665. fn.call(null, arg1);
  8666. });
  8667. case 3:
  8668. return process.nextTick(function afterTickTwo() {
  8669. fn.call(null, arg1, arg2);
  8670. });
  8671. case 4:
  8672. return process.nextTick(function afterTickThree() {
  8673. fn.call(null, arg1, arg2, arg3);
  8674. });
  8675. default:
  8676. args = new Array(len - 1);
  8677. i = 0;
  8678. while (i < args.length) {
  8679. args[i++] = arguments[i];
  8680. }
  8681. return process.nextTick(function afterTick() {
  8682. fn.apply(null, args);
  8683. });
  8684. }
  8685. }
  8686. }).call(this,require('_process'))
  8687. },{"_process":100}],100:[function(require,module,exports){
  8688. // shim for using process in browser
  8689. var process = module.exports = {};
  8690. // cached from whatever global is present so that test runners that stub it
  8691. // don't break things. But we need to wrap it in a try catch in case it is
  8692. // wrapped in strict mode code which doesn't define any globals. It's inside a
  8693. // function because try/catches deoptimize in certain engines.
  8694. var cachedSetTimeout;
  8695. var cachedClearTimeout;
  8696. function defaultSetTimout() {
  8697. throw new Error('setTimeout has not been defined');
  8698. }
  8699. function defaultClearTimeout () {
  8700. throw new Error('clearTimeout has not been defined');
  8701. }
  8702. (function () {
  8703. try {
  8704. if (typeof setTimeout === 'function') {
  8705. cachedSetTimeout = setTimeout;
  8706. } else {
  8707. cachedSetTimeout = defaultSetTimout;
  8708. }
  8709. } catch (e) {
  8710. cachedSetTimeout = defaultSetTimout;
  8711. }
  8712. try {
  8713. if (typeof clearTimeout === 'function') {
  8714. cachedClearTimeout = clearTimeout;
  8715. } else {
  8716. cachedClearTimeout = defaultClearTimeout;
  8717. }
  8718. } catch (e) {
  8719. cachedClearTimeout = defaultClearTimeout;
  8720. }
  8721. } ())
  8722. function runTimeout(fun) {
  8723. if (cachedSetTimeout === setTimeout) {
  8724. //normal enviroments in sane situations
  8725. return setTimeout(fun, 0);
  8726. }
  8727. // if setTimeout wasn't available but was latter defined
  8728. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  8729. cachedSetTimeout = setTimeout;
  8730. return setTimeout(fun, 0);
  8731. }
  8732. try {
  8733. // when when somebody has screwed with setTimeout but no I.E. maddness
  8734. return cachedSetTimeout(fun, 0);
  8735. } catch(e){
  8736. try {
  8737. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8738. return cachedSetTimeout.call(null, fun, 0);
  8739. } catch(e){
  8740. // 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
  8741. return cachedSetTimeout.call(this, fun, 0);
  8742. }
  8743. }
  8744. }
  8745. function runClearTimeout(marker) {
  8746. if (cachedClearTimeout === clearTimeout) {
  8747. //normal enviroments in sane situations
  8748. return clearTimeout(marker);
  8749. }
  8750. // if clearTimeout wasn't available but was latter defined
  8751. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  8752. cachedClearTimeout = clearTimeout;
  8753. return clearTimeout(marker);
  8754. }
  8755. try {
  8756. // when when somebody has screwed with setTimeout but no I.E. maddness
  8757. return cachedClearTimeout(marker);
  8758. } catch (e){
  8759. try {
  8760. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8761. return cachedClearTimeout.call(null, marker);
  8762. } catch (e){
  8763. // 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.
  8764. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  8765. return cachedClearTimeout.call(this, marker);
  8766. }
  8767. }
  8768. }
  8769. var queue = [];
  8770. var draining = false;
  8771. var currentQueue;
  8772. var queueIndex = -1;
  8773. function cleanUpNextTick() {
  8774. if (!draining || !currentQueue) {
  8775. return;
  8776. }
  8777. draining = false;
  8778. if (currentQueue.length) {
  8779. queue = currentQueue.concat(queue);
  8780. } else {
  8781. queueIndex = -1;
  8782. }
  8783. if (queue.length) {
  8784. drainQueue();
  8785. }
  8786. }
  8787. function drainQueue() {
  8788. if (draining) {
  8789. return;
  8790. }
  8791. var timeout = runTimeout(cleanUpNextTick);
  8792. draining = true;
  8793. var len = queue.length;
  8794. while(len) {
  8795. currentQueue = queue;
  8796. queue = [];
  8797. while (++queueIndex < len) {
  8798. if (currentQueue) {
  8799. currentQueue[queueIndex].run();
  8800. }
  8801. }
  8802. queueIndex = -1;
  8803. len = queue.length;
  8804. }
  8805. currentQueue = null;
  8806. draining = false;
  8807. runClearTimeout(timeout);
  8808. }
  8809. process.nextTick = function (fun) {
  8810. var args = new Array(arguments.length - 1);
  8811. if (arguments.length > 1) {
  8812. for (var i = 1; i < arguments.length; i++) {
  8813. args[i - 1] = arguments[i];
  8814. }
  8815. }
  8816. queue.push(new Item(fun, args));
  8817. if (queue.length === 1 && !draining) {
  8818. runTimeout(drainQueue);
  8819. }
  8820. };
  8821. // v8 likes predictible objects
  8822. function Item(fun, array) {
  8823. this.fun = fun;
  8824. this.array = array;
  8825. }
  8826. Item.prototype.run = function () {
  8827. this.fun.apply(null, this.array);
  8828. };
  8829. process.title = 'browser';
  8830. process.browser = true;
  8831. process.env = {};
  8832. process.argv = [];
  8833. process.version = ''; // empty string to avoid regexp issues
  8834. process.versions = {};
  8835. function noop() {}
  8836. process.on = noop;
  8837. process.addListener = noop;
  8838. process.once = noop;
  8839. process.off = noop;
  8840. process.removeListener = noop;
  8841. process.removeAllListeners = noop;
  8842. process.emit = noop;
  8843. process.prependListener = noop;
  8844. process.prependOnceListener = noop;
  8845. process.listeners = function (name) { return [] }
  8846. process.binding = function (name) {
  8847. throw new Error('process.binding is not supported');
  8848. };
  8849. process.cwd = function () { return '/' };
  8850. process.chdir = function (dir) {
  8851. throw new Error('process.chdir is not supported');
  8852. };
  8853. process.umask = function() { return 0; };
  8854. },{}],101:[function(require,module,exports){
  8855. (function (global){
  8856. /*! https://mths.be/punycode v1.4.1 by @mathias */
  8857. ;(function(root) {
  8858. /** Detect free variables */
  8859. var freeExports = typeof exports == 'object' && exports &&
  8860. !exports.nodeType && exports;
  8861. var freeModule = typeof module == 'object' && module &&
  8862. !module.nodeType && module;
  8863. var freeGlobal = typeof global == 'object' && global;
  8864. if (
  8865. freeGlobal.global === freeGlobal ||
  8866. freeGlobal.window === freeGlobal ||
  8867. freeGlobal.self === freeGlobal
  8868. ) {
  8869. root = freeGlobal;
  8870. }
  8871. /**
  8872. * The `punycode` object.
  8873. * @name punycode
  8874. * @type Object
  8875. */
  8876. var punycode,
  8877. /** Highest positive signed 32-bit float value */
  8878. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  8879. /** Bootstring parameters */
  8880. base = 36,
  8881. tMin = 1,
  8882. tMax = 26,
  8883. skew = 38,
  8884. damp = 700,
  8885. initialBias = 72,
  8886. initialN = 128, // 0x80
  8887. delimiter = '-', // '\x2D'
  8888. /** Regular expressions */
  8889. regexPunycode = /^xn--/,
  8890. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  8891. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  8892. /** Error messages */
  8893. errors = {
  8894. 'overflow': 'Overflow: input needs wider integers to process',
  8895. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  8896. 'invalid-input': 'Invalid input'
  8897. },
  8898. /** Convenience shortcuts */
  8899. baseMinusTMin = base - tMin,
  8900. floor = Math.floor,
  8901. stringFromCharCode = String.fromCharCode,
  8902. /** Temporary variable */
  8903. key;
  8904. /*--------------------------------------------------------------------------*/
  8905. /**
  8906. * A generic error utility function.
  8907. * @private
  8908. * @param {String} type The error type.
  8909. * @returns {Error} Throws a `RangeError` with the applicable error message.
  8910. */
  8911. function error(type) {
  8912. throw new RangeError(errors[type]);
  8913. }
  8914. /**
  8915. * A generic `Array#map` utility function.
  8916. * @private
  8917. * @param {Array} array The array to iterate over.
  8918. * @param {Function} callback The function that gets called for every array
  8919. * item.
  8920. * @returns {Array} A new array of values returned by the callback function.
  8921. */
  8922. function map(array, fn) {
  8923. var length = array.length;
  8924. var result = [];
  8925. while (length--) {
  8926. result[length] = fn(array[length]);
  8927. }
  8928. return result;
  8929. }
  8930. /**
  8931. * A simple `Array#map`-like wrapper to work with domain name strings or email
  8932. * addresses.
  8933. * @private
  8934. * @param {String} domain The domain name or email address.
  8935. * @param {Function} callback The function that gets called for every
  8936. * character.
  8937. * @returns {Array} A new string of characters returned by the callback
  8938. * function.
  8939. */
  8940. function mapDomain(string, fn) {
  8941. var parts = string.split('@');
  8942. var result = '';
  8943. if (parts.length > 1) {
  8944. // In email addresses, only the domain name should be punycoded. Leave
  8945. // the local part (i.e. everything up to `@`) intact.
  8946. result = parts[0] + '@';
  8947. string = parts[1];
  8948. }
  8949. // Avoid `split(regex)` for IE8 compatibility. See #17.
  8950. string = string.replace(regexSeparators, '\x2E');
  8951. var labels = string.split('.');
  8952. var encoded = map(labels, fn).join('.');
  8953. return result + encoded;
  8954. }
  8955. /**
  8956. * Creates an array containing the numeric code points of each Unicode
  8957. * character in the string. While JavaScript uses UCS-2 internally,
  8958. * this function will convert a pair of surrogate halves (each of which
  8959. * UCS-2 exposes as separate characters) into a single code point,
  8960. * matching UTF-16.
  8961. * @see `punycode.ucs2.encode`
  8962. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8963. * @memberOf punycode.ucs2
  8964. * @name decode
  8965. * @param {String} string The Unicode input string (UCS-2).
  8966. * @returns {Array} The new array of code points.
  8967. */
  8968. function ucs2decode(string) {
  8969. var output = [],
  8970. counter = 0,
  8971. length = string.length,
  8972. value,
  8973. extra;
  8974. while (counter < length) {
  8975. value = string.charCodeAt(counter++);
  8976. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  8977. // high surrogate, and there is a next character
  8978. extra = string.charCodeAt(counter++);
  8979. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  8980. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  8981. } else {
  8982. // unmatched surrogate; only append this code unit, in case the next
  8983. // code unit is the high surrogate of a surrogate pair
  8984. output.push(value);
  8985. counter--;
  8986. }
  8987. } else {
  8988. output.push(value);
  8989. }
  8990. }
  8991. return output;
  8992. }
  8993. /**
  8994. * Creates a string based on an array of numeric code points.
  8995. * @see `punycode.ucs2.decode`
  8996. * @memberOf punycode.ucs2
  8997. * @name encode
  8998. * @param {Array} codePoints The array of numeric code points.
  8999. * @returns {String} The new Unicode string (UCS-2).
  9000. */
  9001. function ucs2encode(array) {
  9002. return map(array, function(value) {
  9003. var output = '';
  9004. if (value > 0xFFFF) {
  9005. value -= 0x10000;
  9006. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  9007. value = 0xDC00 | value & 0x3FF;
  9008. }
  9009. output += stringFromCharCode(value);
  9010. return output;
  9011. }).join('');
  9012. }
  9013. /**
  9014. * Converts a basic code point into a digit/integer.
  9015. * @see `digitToBasic()`
  9016. * @private
  9017. * @param {Number} codePoint The basic numeric code point value.
  9018. * @returns {Number} The numeric value of a basic code point (for use in
  9019. * representing integers) in the range `0` to `base - 1`, or `base` if
  9020. * the code point does not represent a value.
  9021. */
  9022. function basicToDigit(codePoint) {
  9023. if (codePoint - 48 < 10) {
  9024. return codePoint - 22;
  9025. }
  9026. if (codePoint - 65 < 26) {
  9027. return codePoint - 65;
  9028. }
  9029. if (codePoint - 97 < 26) {
  9030. return codePoint - 97;
  9031. }
  9032. return base;
  9033. }
  9034. /**
  9035. * Converts a digit/integer into a basic code point.
  9036. * @see `basicToDigit()`
  9037. * @private
  9038. * @param {Number} digit The numeric value of a basic code point.
  9039. * @returns {Number} The basic code point whose value (when used for
  9040. * representing integers) is `digit`, which needs to be in the range
  9041. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  9042. * used; else, the lowercase form is used. The behavior is undefined
  9043. * if `flag` is non-zero and `digit` has no uppercase form.
  9044. */
  9045. function digitToBasic(digit, flag) {
  9046. // 0..25 map to ASCII a..z or A..Z
  9047. // 26..35 map to ASCII 0..9
  9048. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  9049. }
  9050. /**
  9051. * Bias adaptation function as per section 3.4 of RFC 3492.
  9052. * https://tools.ietf.org/html/rfc3492#section-3.4
  9053. * @private
  9054. */
  9055. function adapt(delta, numPoints, firstTime) {
  9056. var k = 0;
  9057. delta = firstTime ? floor(delta / damp) : delta >> 1;
  9058. delta += floor(delta / numPoints);
  9059. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  9060. delta = floor(delta / baseMinusTMin);
  9061. }
  9062. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  9063. }
  9064. /**
  9065. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  9066. * symbols.
  9067. * @memberOf punycode
  9068. * @param {String} input The Punycode string of ASCII-only symbols.
  9069. * @returns {String} The resulting string of Unicode symbols.
  9070. */
  9071. function decode(input) {
  9072. // Don't use UCS-2
  9073. var output = [],
  9074. inputLength = input.length,
  9075. out,
  9076. i = 0,
  9077. n = initialN,
  9078. bias = initialBias,
  9079. basic,
  9080. j,
  9081. index,
  9082. oldi,
  9083. w,
  9084. k,
  9085. digit,
  9086. t,
  9087. /** Cached calculation results */
  9088. baseMinusT;
  9089. // Handle the basic code points: let `basic` be the number of input code
  9090. // points before the last delimiter, or `0` if there is none, then copy
  9091. // the first basic code points to the output.
  9092. basic = input.lastIndexOf(delimiter);
  9093. if (basic < 0) {
  9094. basic = 0;
  9095. }
  9096. for (j = 0; j < basic; ++j) {
  9097. // if it's not a basic code point
  9098. if (input.charCodeAt(j) >= 0x80) {
  9099. error('not-basic');
  9100. }
  9101. output.push(input.charCodeAt(j));
  9102. }
  9103. // Main decoding loop: start just after the last delimiter if any basic code
  9104. // points were copied; start at the beginning otherwise.
  9105. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  9106. // `index` is the index of the next character to be consumed.
  9107. // Decode a generalized variable-length integer into `delta`,
  9108. // which gets added to `i`. The overflow checking is easier
  9109. // if we increase `i` as we go, then subtract off its starting
  9110. // value at the end to obtain `delta`.
  9111. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  9112. if (index >= inputLength) {
  9113. error('invalid-input');
  9114. }
  9115. digit = basicToDigit(input.charCodeAt(index++));
  9116. if (digit >= base || digit > floor((maxInt - i) / w)) {
  9117. error('overflow');
  9118. }
  9119. i += digit * w;
  9120. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9121. if (digit < t) {
  9122. break;
  9123. }
  9124. baseMinusT = base - t;
  9125. if (w > floor(maxInt / baseMinusT)) {
  9126. error('overflow');
  9127. }
  9128. w *= baseMinusT;
  9129. }
  9130. out = output.length + 1;
  9131. bias = adapt(i - oldi, out, oldi == 0);
  9132. // `i` was supposed to wrap around from `out` to `0`,
  9133. // incrementing `n` each time, so we'll fix that now:
  9134. if (floor(i / out) > maxInt - n) {
  9135. error('overflow');
  9136. }
  9137. n += floor(i / out);
  9138. i %= out;
  9139. // Insert `n` at position `i` of the output
  9140. output.splice(i++, 0, n);
  9141. }
  9142. return ucs2encode(output);
  9143. }
  9144. /**
  9145. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  9146. * Punycode string of ASCII-only symbols.
  9147. * @memberOf punycode
  9148. * @param {String} input The string of Unicode symbols.
  9149. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  9150. */
  9151. function encode(input) {
  9152. var n,
  9153. delta,
  9154. handledCPCount,
  9155. basicLength,
  9156. bias,
  9157. j,
  9158. m,
  9159. q,
  9160. k,
  9161. t,
  9162. currentValue,
  9163. output = [],
  9164. /** `inputLength` will hold the number of code points in `input`. */
  9165. inputLength,
  9166. /** Cached calculation results */
  9167. handledCPCountPlusOne,
  9168. baseMinusT,
  9169. qMinusT;
  9170. // Convert the input in UCS-2 to Unicode
  9171. input = ucs2decode(input);
  9172. // Cache the length
  9173. inputLength = input.length;
  9174. // Initialize the state
  9175. n = initialN;
  9176. delta = 0;
  9177. bias = initialBias;
  9178. // Handle the basic code points
  9179. for (j = 0; j < inputLength; ++j) {
  9180. currentValue = input[j];
  9181. if (currentValue < 0x80) {
  9182. output.push(stringFromCharCode(currentValue));
  9183. }
  9184. }
  9185. handledCPCount = basicLength = output.length;
  9186. // `handledCPCount` is the number of code points that have been handled;
  9187. // `basicLength` is the number of basic code points.
  9188. // Finish the basic string - if it is not empty - with a delimiter
  9189. if (basicLength) {
  9190. output.push(delimiter);
  9191. }
  9192. // Main encoding loop:
  9193. while (handledCPCount < inputLength) {
  9194. // All non-basic code points < n have been handled already. Find the next
  9195. // larger one:
  9196. for (m = maxInt, j = 0; j < inputLength; ++j) {
  9197. currentValue = input[j];
  9198. if (currentValue >= n && currentValue < m) {
  9199. m = currentValue;
  9200. }
  9201. }
  9202. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  9203. // but guard against overflow
  9204. handledCPCountPlusOne = handledCPCount + 1;
  9205. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  9206. error('overflow');
  9207. }
  9208. delta += (m - n) * handledCPCountPlusOne;
  9209. n = m;
  9210. for (j = 0; j < inputLength; ++j) {
  9211. currentValue = input[j];
  9212. if (currentValue < n && ++delta > maxInt) {
  9213. error('overflow');
  9214. }
  9215. if (currentValue == n) {
  9216. // Represent delta as a generalized variable-length integer
  9217. for (q = delta, k = base; /* no condition */; k += base) {
  9218. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9219. if (q < t) {
  9220. break;
  9221. }
  9222. qMinusT = q - t;
  9223. baseMinusT = base - t;
  9224. output.push(
  9225. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  9226. );
  9227. q = floor(qMinusT / baseMinusT);
  9228. }
  9229. output.push(stringFromCharCode(digitToBasic(q, 0)));
  9230. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  9231. delta = 0;
  9232. ++handledCPCount;
  9233. }
  9234. }
  9235. ++delta;
  9236. ++n;
  9237. }
  9238. return output.join('');
  9239. }
  9240. /**
  9241. * Converts a Punycode string representing a domain name or an email address
  9242. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  9243. * it doesn't matter if you call it on a string that has already been
  9244. * converted to Unicode.
  9245. * @memberOf punycode
  9246. * @param {String} input The Punycoded domain name or email address to
  9247. * convert to Unicode.
  9248. * @returns {String} The Unicode representation of the given Punycode
  9249. * string.
  9250. */
  9251. function toUnicode(input) {
  9252. return mapDomain(input, function(string) {
  9253. return regexPunycode.test(string)
  9254. ? decode(string.slice(4).toLowerCase())
  9255. : string;
  9256. });
  9257. }
  9258. /**
  9259. * Converts a Unicode string representing a domain name or an email address to
  9260. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  9261. * i.e. it doesn't matter if you call it with a domain that's already in
  9262. * ASCII.
  9263. * @memberOf punycode
  9264. * @param {String} input The domain name or email address to convert, as a
  9265. * Unicode string.
  9266. * @returns {String} The Punycode representation of the given domain name or
  9267. * email address.
  9268. */
  9269. function toASCII(input) {
  9270. return mapDomain(input, function(string) {
  9271. return regexNonASCII.test(string)
  9272. ? 'xn--' + encode(string)
  9273. : string;
  9274. });
  9275. }
  9276. /*--------------------------------------------------------------------------*/
  9277. /** Define the public API */
  9278. punycode = {
  9279. /**
  9280. * A string representing the current Punycode.js version number.
  9281. * @memberOf punycode
  9282. * @type String
  9283. */
  9284. 'version': '1.4.1',
  9285. /**
  9286. * An object of methods to convert from JavaScript's internal character
  9287. * representation (UCS-2) to Unicode code points, and back.
  9288. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  9289. * @memberOf punycode
  9290. * @type Object
  9291. */
  9292. 'ucs2': {
  9293. 'decode': ucs2decode,
  9294. 'encode': ucs2encode
  9295. },
  9296. 'decode': decode,
  9297. 'encode': encode,
  9298. 'toASCII': toASCII,
  9299. 'toUnicode': toUnicode
  9300. };
  9301. /** Expose `punycode` */
  9302. // Some AMD build optimizers, like r.js, check for specific condition patterns
  9303. // like the following:
  9304. if (
  9305. typeof define == 'function' &&
  9306. typeof define.amd == 'object' &&
  9307. define.amd
  9308. ) {
  9309. define('punycode', function() {
  9310. return punycode;
  9311. });
  9312. } else if (freeExports && freeModule) {
  9313. if (module.exports == freeExports) {
  9314. // in Node.js, io.js, or RingoJS v0.8.0+
  9315. freeModule.exports = punycode;
  9316. } else {
  9317. // in Narwhal or RingoJS v0.7.0-
  9318. for (key in punycode) {
  9319. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  9320. }
  9321. }
  9322. } else {
  9323. // in Rhino or a web browser
  9324. root.punycode = punycode;
  9325. }
  9326. }(this));
  9327. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9328. },{}],102:[function(require,module,exports){
  9329. // Copyright Joyent, Inc. and other Node contributors.
  9330. //
  9331. // Permission is hereby granted, free of charge, to any person obtaining a
  9332. // copy of this software and associated documentation files (the
  9333. // "Software"), to deal in the Software without restriction, including
  9334. // without limitation the rights to use, copy, modify, merge, publish,
  9335. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9336. // persons to whom the Software is furnished to do so, subject to the
  9337. // following conditions:
  9338. //
  9339. // The above copyright notice and this permission notice shall be included
  9340. // in all copies or substantial portions of the Software.
  9341. //
  9342. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9343. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9344. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9345. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9346. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9347. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9348. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9349. 'use strict';
  9350. // If obj.hasOwnProperty has been overridden, then calling
  9351. // obj.hasOwnProperty(prop) will break.
  9352. // See: https://github.com/joyent/node/issues/1707
  9353. function hasOwnProperty(obj, prop) {
  9354. return Object.prototype.hasOwnProperty.call(obj, prop);
  9355. }
  9356. module.exports = function(qs, sep, eq, options) {
  9357. sep = sep || '&';
  9358. eq = eq || '=';
  9359. var obj = {};
  9360. if (typeof qs !== 'string' || qs.length === 0) {
  9361. return obj;
  9362. }
  9363. var regexp = /\+/g;
  9364. qs = qs.split(sep);
  9365. var maxKeys = 1000;
  9366. if (options && typeof options.maxKeys === 'number') {
  9367. maxKeys = options.maxKeys;
  9368. }
  9369. var len = qs.length;
  9370. // maxKeys <= 0 means that we should not limit keys count
  9371. if (maxKeys > 0 && len > maxKeys) {
  9372. len = maxKeys;
  9373. }
  9374. for (var i = 0; i < len; ++i) {
  9375. var x = qs[i].replace(regexp, '%20'),
  9376. idx = x.indexOf(eq),
  9377. kstr, vstr, k, v;
  9378. if (idx >= 0) {
  9379. kstr = x.substr(0, idx);
  9380. vstr = x.substr(idx + 1);
  9381. } else {
  9382. kstr = x;
  9383. vstr = '';
  9384. }
  9385. k = decodeURIComponent(kstr);
  9386. v = decodeURIComponent(vstr);
  9387. if (!hasOwnProperty(obj, k)) {
  9388. obj[k] = v;
  9389. } else if (isArray(obj[k])) {
  9390. obj[k].push(v);
  9391. } else {
  9392. obj[k] = [obj[k], v];
  9393. }
  9394. }
  9395. return obj;
  9396. };
  9397. var isArray = Array.isArray || function (xs) {
  9398. return Object.prototype.toString.call(xs) === '[object Array]';
  9399. };
  9400. },{}],103:[function(require,module,exports){
  9401. // Copyright Joyent, Inc. and other Node contributors.
  9402. //
  9403. // Permission is hereby granted, free of charge, to any person obtaining a
  9404. // copy of this software and associated documentation files (the
  9405. // "Software"), to deal in the Software without restriction, including
  9406. // without limitation the rights to use, copy, modify, merge, publish,
  9407. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9408. // persons to whom the Software is furnished to do so, subject to the
  9409. // following conditions:
  9410. //
  9411. // The above copyright notice and this permission notice shall be included
  9412. // in all copies or substantial portions of the Software.
  9413. //
  9414. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9415. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9416. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9417. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9418. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9419. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9420. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9421. 'use strict';
  9422. var stringifyPrimitive = function(v) {
  9423. switch (typeof v) {
  9424. case 'string':
  9425. return v;
  9426. case 'boolean':
  9427. return v ? 'true' : 'false';
  9428. case 'number':
  9429. return isFinite(v) ? v : '';
  9430. default:
  9431. return '';
  9432. }
  9433. };
  9434. module.exports = function(obj, sep, eq, name) {
  9435. sep = sep || '&';
  9436. eq = eq || '=';
  9437. if (obj === null) {
  9438. obj = undefined;
  9439. }
  9440. if (typeof obj === 'object') {
  9441. return map(objectKeys(obj), function(k) {
  9442. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  9443. if (isArray(obj[k])) {
  9444. return map(obj[k], function(v) {
  9445. return ks + encodeURIComponent(stringifyPrimitive(v));
  9446. }).join(sep);
  9447. } else {
  9448. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  9449. }
  9450. }).join(sep);
  9451. }
  9452. if (!name) return '';
  9453. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  9454. encodeURIComponent(stringifyPrimitive(obj));
  9455. };
  9456. var isArray = Array.isArray || function (xs) {
  9457. return Object.prototype.toString.call(xs) === '[object Array]';
  9458. };
  9459. function map (xs, f) {
  9460. if (xs.map) return xs.map(f);
  9461. var res = [];
  9462. for (var i = 0; i < xs.length; i++) {
  9463. res.push(f(xs[i], i));
  9464. }
  9465. return res;
  9466. }
  9467. var objectKeys = Object.keys || function (obj) {
  9468. var res = [];
  9469. for (var key in obj) {
  9470. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  9471. }
  9472. return res;
  9473. };
  9474. },{}],104:[function(require,module,exports){
  9475. 'use strict';
  9476. exports.decode = exports.parse = require('./decode');
  9477. exports.encode = exports.stringify = require('./encode');
  9478. },{"./decode":102,"./encode":103}],105:[function(require,module,exports){
  9479. module.exports = require('./lib/_stream_duplex.js');
  9480. },{"./lib/_stream_duplex.js":106}],106:[function(require,module,exports){
  9481. // Copyright Joyent, Inc. and other Node contributors.
  9482. //
  9483. // Permission is hereby granted, free of charge, to any person obtaining a
  9484. // copy of this software and associated documentation files (the
  9485. // "Software"), to deal in the Software without restriction, including
  9486. // without limitation the rights to use, copy, modify, merge, publish,
  9487. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9488. // persons to whom the Software is furnished to do so, subject to the
  9489. // following conditions:
  9490. //
  9491. // The above copyright notice and this permission notice shall be included
  9492. // in all copies or substantial portions of the Software.
  9493. //
  9494. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9495. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9496. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9497. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9498. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9499. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9500. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9501. // a duplex stream is just a stream that is both readable and writable.
  9502. // Since JS doesn't have multiple prototypal inheritance, this class
  9503. // prototypally inherits from Readable, and then parasitically from
  9504. // Writable.
  9505. 'use strict';
  9506. /*<replacement>*/
  9507. var pna = require('process-nextick-args');
  9508. /*</replacement>*/
  9509. /*<replacement>*/
  9510. var objectKeys = Object.keys || function (obj) {
  9511. var keys = [];
  9512. for (var key in obj) {
  9513. keys.push(key);
  9514. }return keys;
  9515. };
  9516. /*</replacement>*/
  9517. module.exports = Duplex;
  9518. /*<replacement>*/
  9519. var util = require('core-util-is');
  9520. util.inherits = require('inherits');
  9521. /*</replacement>*/
  9522. var Readable = require('./_stream_readable');
  9523. var Writable = require('./_stream_writable');
  9524. util.inherits(Duplex, Readable);
  9525. {
  9526. // avoid scope creep, the keys array can then be collected
  9527. var keys = objectKeys(Writable.prototype);
  9528. for (var v = 0; v < keys.length; v++) {
  9529. var method = keys[v];
  9530. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  9531. }
  9532. }
  9533. function Duplex(options) {
  9534. if (!(this instanceof Duplex)) return new Duplex(options);
  9535. Readable.call(this, options);
  9536. Writable.call(this, options);
  9537. if (options && options.readable === false) this.readable = false;
  9538. if (options && options.writable === false) this.writable = false;
  9539. this.allowHalfOpen = true;
  9540. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  9541. this.once('end', onend);
  9542. }
  9543. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  9544. // making it explicit this property is not enumerable
  9545. // because otherwise some prototype manipulation in
  9546. // userland will fail
  9547. enumerable: false,
  9548. get: function () {
  9549. return this._writableState.highWaterMark;
  9550. }
  9551. });
  9552. // the no-half-open enforcer
  9553. function onend() {
  9554. // if we allow half-open state, or if the writable side ended,
  9555. // then we're ok.
  9556. if (this.allowHalfOpen || this._writableState.ended) return;
  9557. // no more data can be written.
  9558. // But allow more writes to happen in this tick.
  9559. pna.nextTick(onEndNT, this);
  9560. }
  9561. function onEndNT(self) {
  9562. self.end();
  9563. }
  9564. Object.defineProperty(Duplex.prototype, 'destroyed', {
  9565. get: function () {
  9566. if (this._readableState === undefined || this._writableState === undefined) {
  9567. return false;
  9568. }
  9569. return this._readableState.destroyed && this._writableState.destroyed;
  9570. },
  9571. set: function (value) {
  9572. // we ignore the value if the stream
  9573. // has not been initialized yet
  9574. if (this._readableState === undefined || this._writableState === undefined) {
  9575. return;
  9576. }
  9577. // backward compatibility, the user is explicitly
  9578. // managing destroyed
  9579. this._readableState.destroyed = value;
  9580. this._writableState.destroyed = value;
  9581. }
  9582. });
  9583. Duplex.prototype._destroy = function (err, cb) {
  9584. this.push(null);
  9585. this.end();
  9586. pna.nextTick(cb, err);
  9587. };
  9588. },{"./_stream_readable":108,"./_stream_writable":110,"core-util-is":13,"inherits":88,"process-nextick-args":99}],107:[function(require,module,exports){
  9589. // Copyright Joyent, Inc. and other Node contributors.
  9590. //
  9591. // Permission is hereby granted, free of charge, to any person obtaining a
  9592. // copy of this software and associated documentation files (the
  9593. // "Software"), to deal in the Software without restriction, including
  9594. // without limitation the rights to use, copy, modify, merge, publish,
  9595. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9596. // persons to whom the Software is furnished to do so, subject to the
  9597. // following conditions:
  9598. //
  9599. // The above copyright notice and this permission notice shall be included
  9600. // in all copies or substantial portions of the Software.
  9601. //
  9602. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9603. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9604. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9605. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9606. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9607. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9608. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9609. // a passthrough stream.
  9610. // basically just the most minimal sort of Transform stream.
  9611. // Every written chunk gets output as-is.
  9612. 'use strict';
  9613. module.exports = PassThrough;
  9614. var Transform = require('./_stream_transform');
  9615. /*<replacement>*/
  9616. var util = require('core-util-is');
  9617. util.inherits = require('inherits');
  9618. /*</replacement>*/
  9619. util.inherits(PassThrough, Transform);
  9620. function PassThrough(options) {
  9621. if (!(this instanceof PassThrough)) return new PassThrough(options);
  9622. Transform.call(this, options);
  9623. }
  9624. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  9625. cb(null, chunk);
  9626. };
  9627. },{"./_stream_transform":109,"core-util-is":13,"inherits":88}],108:[function(require,module,exports){
  9628. (function (process,global){
  9629. // Copyright Joyent, Inc. and other Node contributors.
  9630. //
  9631. // Permission is hereby granted, free of charge, to any person obtaining a
  9632. // copy of this software and associated documentation files (the
  9633. // "Software"), to deal in the Software without restriction, including
  9634. // without limitation the rights to use, copy, modify, merge, publish,
  9635. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9636. // persons to whom the Software is furnished to do so, subject to the
  9637. // following conditions:
  9638. //
  9639. // The above copyright notice and this permission notice shall be included
  9640. // in all copies or substantial portions of the Software.
  9641. //
  9642. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9643. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9644. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9645. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9646. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9647. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9648. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9649. 'use strict';
  9650. /*<replacement>*/
  9651. var pna = require('process-nextick-args');
  9652. /*</replacement>*/
  9653. module.exports = Readable;
  9654. /*<replacement>*/
  9655. var isArray = require('isarray');
  9656. /*</replacement>*/
  9657. /*<replacement>*/
  9658. var Duplex;
  9659. /*</replacement>*/
  9660. Readable.ReadableState = ReadableState;
  9661. /*<replacement>*/
  9662. var EE = require('events').EventEmitter;
  9663. var EElistenerCount = function (emitter, type) {
  9664. return emitter.listeners(type).length;
  9665. };
  9666. /*</replacement>*/
  9667. /*<replacement>*/
  9668. var Stream = require('./internal/streams/stream');
  9669. /*</replacement>*/
  9670. /*<replacement>*/
  9671. var Buffer = require('safe-buffer').Buffer;
  9672. var OurUint8Array = global.Uint8Array || function () {};
  9673. function _uint8ArrayToBuffer(chunk) {
  9674. return Buffer.from(chunk);
  9675. }
  9676. function _isUint8Array(obj) {
  9677. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  9678. }
  9679. /*</replacement>*/
  9680. /*<replacement>*/
  9681. var util = require('core-util-is');
  9682. util.inherits = require('inherits');
  9683. /*</replacement>*/
  9684. /*<replacement>*/
  9685. var debugUtil = require('util');
  9686. var debug = void 0;
  9687. if (debugUtil && debugUtil.debuglog) {
  9688. debug = debugUtil.debuglog('stream');
  9689. } else {
  9690. debug = function () {};
  9691. }
  9692. /*</replacement>*/
  9693. var BufferList = require('./internal/streams/BufferList');
  9694. var destroyImpl = require('./internal/streams/destroy');
  9695. var StringDecoder;
  9696. util.inherits(Readable, Stream);
  9697. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  9698. function prependListener(emitter, event, fn) {
  9699. // Sadly this is not cacheable as some libraries bundle their own
  9700. // event emitter implementation with them.
  9701. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  9702. // This is a hack to make sure that our error handler is attached before any
  9703. // userland ones. NEVER DO THIS. This is here only because this code needs
  9704. // to continue to work with older versions of Node.js that do not include
  9705. // the prependListener() method. The goal is to eventually remove this hack.
  9706. 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]];
  9707. }
  9708. function ReadableState(options, stream) {
  9709. Duplex = Duplex || require('./_stream_duplex');
  9710. options = options || {};
  9711. // Duplex streams are both readable and writable, but share
  9712. // the same options object.
  9713. // However, some cases require setting options to different
  9714. // values for the readable and the writable sides of the duplex stream.
  9715. // These options can be provided separately as readableXXX and writableXXX.
  9716. var isDuplex = stream instanceof Duplex;
  9717. // object stream flag. Used to make read(n) ignore n and to
  9718. // make all the buffer merging and length checks go away
  9719. this.objectMode = !!options.objectMode;
  9720. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  9721. // the point at which it stops calling _read() to fill the buffer
  9722. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  9723. var hwm = options.highWaterMark;
  9724. var readableHwm = options.readableHighWaterMark;
  9725. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  9726. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  9727. // cast to ints.
  9728. this.highWaterMark = Math.floor(this.highWaterMark);
  9729. // A linked list is used to store data chunks instead of an array because the
  9730. // linked list can remove elements from the beginning faster than
  9731. // array.shift()
  9732. this.buffer = new BufferList();
  9733. this.length = 0;
  9734. this.pipes = null;
  9735. this.pipesCount = 0;
  9736. this.flowing = null;
  9737. this.ended = false;
  9738. this.endEmitted = false;
  9739. this.reading = false;
  9740. // a flag to be able to tell if the event 'readable'/'data' is emitted
  9741. // immediately, or on a later tick. We set this to true at first, because
  9742. // any actions that shouldn't happen until "later" should generally also
  9743. // not happen before the first read call.
  9744. this.sync = true;
  9745. // whenever we return null, then we set a flag to say
  9746. // that we're awaiting a 'readable' event emission.
  9747. this.needReadable = false;
  9748. this.emittedReadable = false;
  9749. this.readableListening = false;
  9750. this.resumeScheduled = false;
  9751. // has it been destroyed
  9752. this.destroyed = false;
  9753. // Crypto is kind of old and crusty. Historically, its default string
  9754. // encoding is 'binary' so we have to make this configurable.
  9755. // Everything else in the universe uses 'utf8', though.
  9756. this.defaultEncoding = options.defaultEncoding || 'utf8';
  9757. // the number of writers that are awaiting a drain event in .pipe()s
  9758. this.awaitDrain = 0;
  9759. // if true, a maybeReadMore has been scheduled
  9760. this.readingMore = false;
  9761. this.decoder = null;
  9762. this.encoding = null;
  9763. if (options.encoding) {
  9764. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9765. this.decoder = new StringDecoder(options.encoding);
  9766. this.encoding = options.encoding;
  9767. }
  9768. }
  9769. function Readable(options) {
  9770. Duplex = Duplex || require('./_stream_duplex');
  9771. if (!(this instanceof Readable)) return new Readable(options);
  9772. this._readableState = new ReadableState(options, this);
  9773. // legacy
  9774. this.readable = true;
  9775. if (options) {
  9776. if (typeof options.read === 'function') this._read = options.read;
  9777. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  9778. }
  9779. Stream.call(this);
  9780. }
  9781. Object.defineProperty(Readable.prototype, 'destroyed', {
  9782. get: function () {
  9783. if (this._readableState === undefined) {
  9784. return false;
  9785. }
  9786. return this._readableState.destroyed;
  9787. },
  9788. set: function (value) {
  9789. // we ignore the value if the stream
  9790. // has not been initialized yet
  9791. if (!this._readableState) {
  9792. return;
  9793. }
  9794. // backward compatibility, the user is explicitly
  9795. // managing destroyed
  9796. this._readableState.destroyed = value;
  9797. }
  9798. });
  9799. Readable.prototype.destroy = destroyImpl.destroy;
  9800. Readable.prototype._undestroy = destroyImpl.undestroy;
  9801. Readable.prototype._destroy = function (err, cb) {
  9802. this.push(null);
  9803. cb(err);
  9804. };
  9805. // Manually shove something into the read() buffer.
  9806. // This returns true if the highWaterMark has not been hit yet,
  9807. // similar to how Writable.write() returns true if you should
  9808. // write() some more.
  9809. Readable.prototype.push = function (chunk, encoding) {
  9810. var state = this._readableState;
  9811. var skipChunkCheck;
  9812. if (!state.objectMode) {
  9813. if (typeof chunk === 'string') {
  9814. encoding = encoding || state.defaultEncoding;
  9815. if (encoding !== state.encoding) {
  9816. chunk = Buffer.from(chunk, encoding);
  9817. encoding = '';
  9818. }
  9819. skipChunkCheck = true;
  9820. }
  9821. } else {
  9822. skipChunkCheck = true;
  9823. }
  9824. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  9825. };
  9826. // Unshift should *always* be something directly out of read()
  9827. Readable.prototype.unshift = function (chunk) {
  9828. return readableAddChunk(this, chunk, null, true, false);
  9829. };
  9830. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  9831. var state = stream._readableState;
  9832. if (chunk === null) {
  9833. state.reading = false;
  9834. onEofChunk(stream, state);
  9835. } else {
  9836. var er;
  9837. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  9838. if (er) {
  9839. stream.emit('error', er);
  9840. } else if (state.objectMode || chunk && chunk.length > 0) {
  9841. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  9842. chunk = _uint8ArrayToBuffer(chunk);
  9843. }
  9844. if (addToFront) {
  9845. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  9846. } else if (state.ended) {
  9847. stream.emit('error', new Error('stream.push() after EOF'));
  9848. } else {
  9849. state.reading = false;
  9850. if (state.decoder && !encoding) {
  9851. chunk = state.decoder.write(chunk);
  9852. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  9853. } else {
  9854. addChunk(stream, state, chunk, false);
  9855. }
  9856. }
  9857. } else if (!addToFront) {
  9858. state.reading = false;
  9859. }
  9860. }
  9861. return needMoreData(state);
  9862. }
  9863. function addChunk(stream, state, chunk, addToFront) {
  9864. if (state.flowing && state.length === 0 && !state.sync) {
  9865. stream.emit('data', chunk);
  9866. stream.read(0);
  9867. } else {
  9868. // update the buffer info.
  9869. state.length += state.objectMode ? 1 : chunk.length;
  9870. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  9871. if (state.needReadable) emitReadable(stream);
  9872. }
  9873. maybeReadMore(stream, state);
  9874. }
  9875. function chunkInvalid(state, chunk) {
  9876. var er;
  9877. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  9878. er = new TypeError('Invalid non-string/buffer chunk');
  9879. }
  9880. return er;
  9881. }
  9882. // if it's past the high water mark, we can push in some more.
  9883. // Also, if we have no data yet, we can stand some
  9884. // more bytes. This is to work around cases where hwm=0,
  9885. // such as the repl. Also, if the push() triggered a
  9886. // readable event, and the user called read(largeNumber) such that
  9887. // needReadable was set, then we ought to push more, so that another
  9888. // 'readable' event will be triggered.
  9889. function needMoreData(state) {
  9890. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  9891. }
  9892. Readable.prototype.isPaused = function () {
  9893. return this._readableState.flowing === false;
  9894. };
  9895. // backwards compatibility.
  9896. Readable.prototype.setEncoding = function (enc) {
  9897. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9898. this._readableState.decoder = new StringDecoder(enc);
  9899. this._readableState.encoding = enc;
  9900. return this;
  9901. };
  9902. // Don't raise the hwm > 8MB
  9903. var MAX_HWM = 0x800000;
  9904. function computeNewHighWaterMark(n) {
  9905. if (n >= MAX_HWM) {
  9906. n = MAX_HWM;
  9907. } else {
  9908. // Get the next highest power of 2 to prevent increasing hwm excessively in
  9909. // tiny amounts
  9910. n--;
  9911. n |= n >>> 1;
  9912. n |= n >>> 2;
  9913. n |= n >>> 4;
  9914. n |= n >>> 8;
  9915. n |= n >>> 16;
  9916. n++;
  9917. }
  9918. return n;
  9919. }
  9920. // This function is designed to be inlinable, so please take care when making
  9921. // changes to the function body.
  9922. function howMuchToRead(n, state) {
  9923. if (n <= 0 || state.length === 0 && state.ended) return 0;
  9924. if (state.objectMode) return 1;
  9925. if (n !== n) {
  9926. // Only flow one buffer at a time
  9927. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  9928. }
  9929. // If we're asking for more than the current hwm, then raise the hwm.
  9930. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  9931. if (n <= state.length) return n;
  9932. // Don't have enough
  9933. if (!state.ended) {
  9934. state.needReadable = true;
  9935. return 0;
  9936. }
  9937. return state.length;
  9938. }
  9939. // you can override either this method, or the async _read(n) below.
  9940. Readable.prototype.read = function (n) {
  9941. debug('read', n);
  9942. n = parseInt(n, 10);
  9943. var state = this._readableState;
  9944. var nOrig = n;
  9945. if (n !== 0) state.emittedReadable = false;
  9946. // if we're doing read(0) to trigger a readable event, but we
  9947. // already have a bunch of data in the buffer, then just trigger
  9948. // the 'readable' event and move on.
  9949. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  9950. debug('read: emitReadable', state.length, state.ended);
  9951. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  9952. return null;
  9953. }
  9954. n = howMuchToRead(n, state);
  9955. // if we've ended, and we're now clear, then finish it up.
  9956. if (n === 0 && state.ended) {
  9957. if (state.length === 0) endReadable(this);
  9958. return null;
  9959. }
  9960. // All the actual chunk generation logic needs to be
  9961. // *below* the call to _read. The reason is that in certain
  9962. // synthetic stream cases, such as passthrough streams, _read
  9963. // may be a completely synchronous operation which may change
  9964. // the state of the read buffer, providing enough data when
  9965. // before there was *not* enough.
  9966. //
  9967. // So, the steps are:
  9968. // 1. Figure out what the state of things will be after we do
  9969. // a read from the buffer.
  9970. //
  9971. // 2. If that resulting state will trigger a _read, then call _read.
  9972. // Note that this may be asynchronous, or synchronous. Yes, it is
  9973. // deeply ugly to write APIs this way, but that still doesn't mean
  9974. // that the Readable class should behave improperly, as streams are
  9975. // designed to be sync/async agnostic.
  9976. // Take note if the _read call is sync or async (ie, if the read call
  9977. // has returned yet), so that we know whether or not it's safe to emit
  9978. // 'readable' etc.
  9979. //
  9980. // 3. Actually pull the requested chunks out of the buffer and return.
  9981. // if we need a readable event, then we need to do some reading.
  9982. var doRead = state.needReadable;
  9983. debug('need readable', doRead);
  9984. // if we currently have less than the highWaterMark, then also read some
  9985. if (state.length === 0 || state.length - n < state.highWaterMark) {
  9986. doRead = true;
  9987. debug('length less than watermark', doRead);
  9988. }
  9989. // however, if we've ended, then there's no point, and if we're already
  9990. // reading, then it's unnecessary.
  9991. if (state.ended || state.reading) {
  9992. doRead = false;
  9993. debug('reading or ended', doRead);
  9994. } else if (doRead) {
  9995. debug('do read');
  9996. state.reading = true;
  9997. state.sync = true;
  9998. // if the length is currently zero, then we *need* a readable event.
  9999. if (state.length === 0) state.needReadable = true;
  10000. // call internal read method
  10001. this._read(state.highWaterMark);
  10002. state.sync = false;
  10003. // If _read pushed data synchronously, then `reading` will be false,
  10004. // and we need to re-evaluate how much data we can return to the user.
  10005. if (!state.reading) n = howMuchToRead(nOrig, state);
  10006. }
  10007. var ret;
  10008. if (n > 0) ret = fromList(n, state);else ret = null;
  10009. if (ret === null) {
  10010. state.needReadable = true;
  10011. n = 0;
  10012. } else {
  10013. state.length -= n;
  10014. }
  10015. if (state.length === 0) {
  10016. // If we have nothing in the buffer, then we want to know
  10017. // as soon as we *do* get something into the buffer.
  10018. if (!state.ended) state.needReadable = true;
  10019. // If we tried to read() past the EOF, then emit end on the next tick.
  10020. if (nOrig !== n && state.ended) endReadable(this);
  10021. }
  10022. if (ret !== null) this.emit('data', ret);
  10023. return ret;
  10024. };
  10025. function onEofChunk(stream, state) {
  10026. if (state.ended) return;
  10027. if (state.decoder) {
  10028. var chunk = state.decoder.end();
  10029. if (chunk && chunk.length) {
  10030. state.buffer.push(chunk);
  10031. state.length += state.objectMode ? 1 : chunk.length;
  10032. }
  10033. }
  10034. state.ended = true;
  10035. // emit 'readable' now to make sure it gets picked up.
  10036. emitReadable(stream);
  10037. }
  10038. // Don't emit readable right away in sync mode, because this can trigger
  10039. // another read() call => stack overflow. This way, it might trigger
  10040. // a nextTick recursion warning, but that's not so bad.
  10041. function emitReadable(stream) {
  10042. var state = stream._readableState;
  10043. state.needReadable = false;
  10044. if (!state.emittedReadable) {
  10045. debug('emitReadable', state.flowing);
  10046. state.emittedReadable = true;
  10047. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  10048. }
  10049. }
  10050. function emitReadable_(stream) {
  10051. debug('emit readable');
  10052. stream.emit('readable');
  10053. flow(stream);
  10054. }
  10055. // at this point, the user has presumably seen the 'readable' event,
  10056. // and called read() to consume some data. that may have triggered
  10057. // in turn another _read(n) call, in which case reading = true if
  10058. // it's in progress.
  10059. // However, if we're not ended, or reading, and the length < hwm,
  10060. // then go ahead and try to read some more preemptively.
  10061. function maybeReadMore(stream, state) {
  10062. if (!state.readingMore) {
  10063. state.readingMore = true;
  10064. pna.nextTick(maybeReadMore_, stream, state);
  10065. }
  10066. }
  10067. function maybeReadMore_(stream, state) {
  10068. var len = state.length;
  10069. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  10070. debug('maybeReadMore read 0');
  10071. stream.read(0);
  10072. if (len === state.length)
  10073. // didn't get any data, stop spinning.
  10074. break;else len = state.length;
  10075. }
  10076. state.readingMore = false;
  10077. }
  10078. // abstract method. to be overridden in specific implementation classes.
  10079. // call cb(er, data) where data is <= n in length.
  10080. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  10081. // arbitrary, and perhaps not very meaningful.
  10082. Readable.prototype._read = function (n) {
  10083. this.emit('error', new Error('_read() is not implemented'));
  10084. };
  10085. Readable.prototype.pipe = function (dest, pipeOpts) {
  10086. var src = this;
  10087. var state = this._readableState;
  10088. switch (state.pipesCount) {
  10089. case 0:
  10090. state.pipes = dest;
  10091. break;
  10092. case 1:
  10093. state.pipes = [state.pipes, dest];
  10094. break;
  10095. default:
  10096. state.pipes.push(dest);
  10097. break;
  10098. }
  10099. state.pipesCount += 1;
  10100. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  10101. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  10102. var endFn = doEnd ? onend : unpipe;
  10103. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  10104. dest.on('unpipe', onunpipe);
  10105. function onunpipe(readable, unpipeInfo) {
  10106. debug('onunpipe');
  10107. if (readable === src) {
  10108. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  10109. unpipeInfo.hasUnpiped = true;
  10110. cleanup();
  10111. }
  10112. }
  10113. }
  10114. function onend() {
  10115. debug('onend');
  10116. dest.end();
  10117. }
  10118. // when the dest drains, it reduces the awaitDrain counter
  10119. // on the source. This would be more elegant with a .once()
  10120. // handler in flow(), but adding and removing repeatedly is
  10121. // too slow.
  10122. var ondrain = pipeOnDrain(src);
  10123. dest.on('drain', ondrain);
  10124. var cleanedUp = false;
  10125. function cleanup() {
  10126. debug('cleanup');
  10127. // cleanup event handlers once the pipe is broken
  10128. dest.removeListener('close', onclose);
  10129. dest.removeListener('finish', onfinish);
  10130. dest.removeListener('drain', ondrain);
  10131. dest.removeListener('error', onerror);
  10132. dest.removeListener('unpipe', onunpipe);
  10133. src.removeListener('end', onend);
  10134. src.removeListener('end', unpipe);
  10135. src.removeListener('data', ondata);
  10136. cleanedUp = true;
  10137. // if the reader is waiting for a drain event from this
  10138. // specific writer, then it would cause it to never start
  10139. // flowing again.
  10140. // So, if this is awaiting a drain, then we just call it now.
  10141. // If we don't know, then assume that we are waiting for one.
  10142. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  10143. }
  10144. // If the user pushes more data while we're writing to dest then we'll end up
  10145. // in ondata again. However, we only want to increase awaitDrain once because
  10146. // dest will only emit one 'drain' event for the multiple writes.
  10147. // => Introduce a guard on increasing awaitDrain.
  10148. var increasedAwaitDrain = false;
  10149. src.on('data', ondata);
  10150. function ondata(chunk) {
  10151. debug('ondata');
  10152. increasedAwaitDrain = false;
  10153. var ret = dest.write(chunk);
  10154. if (false === ret && !increasedAwaitDrain) {
  10155. // If the user unpiped during `dest.write()`, it is possible
  10156. // to get stuck in a permanently paused state if that write
  10157. // also returned false.
  10158. // => Check whether `dest` is still a piping destination.
  10159. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  10160. debug('false write response, pause', src._readableState.awaitDrain);
  10161. src._readableState.awaitDrain++;
  10162. increasedAwaitDrain = true;
  10163. }
  10164. src.pause();
  10165. }
  10166. }
  10167. // if the dest has an error, then stop piping into it.
  10168. // however, don't suppress the throwing behavior for this.
  10169. function onerror(er) {
  10170. debug('onerror', er);
  10171. unpipe();
  10172. dest.removeListener('error', onerror);
  10173. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  10174. }
  10175. // Make sure our error handler is attached before userland ones.
  10176. prependListener(dest, 'error', onerror);
  10177. // Both close and finish should trigger unpipe, but only once.
  10178. function onclose() {
  10179. dest.removeListener('finish', onfinish);
  10180. unpipe();
  10181. }
  10182. dest.once('close', onclose);
  10183. function onfinish() {
  10184. debug('onfinish');
  10185. dest.removeListener('close', onclose);
  10186. unpipe();
  10187. }
  10188. dest.once('finish', onfinish);
  10189. function unpipe() {
  10190. debug('unpipe');
  10191. src.unpipe(dest);
  10192. }
  10193. // tell the dest that it's being piped to
  10194. dest.emit('pipe', src);
  10195. // start the flow if it hasn't been started already.
  10196. if (!state.flowing) {
  10197. debug('pipe resume');
  10198. src.resume();
  10199. }
  10200. return dest;
  10201. };
  10202. function pipeOnDrain(src) {
  10203. return function () {
  10204. var state = src._readableState;
  10205. debug('pipeOnDrain', state.awaitDrain);
  10206. if (state.awaitDrain) state.awaitDrain--;
  10207. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  10208. state.flowing = true;
  10209. flow(src);
  10210. }
  10211. };
  10212. }
  10213. Readable.prototype.unpipe = function (dest) {
  10214. var state = this._readableState;
  10215. var unpipeInfo = { hasUnpiped: false };
  10216. // if we're not piping anywhere, then do nothing.
  10217. if (state.pipesCount === 0) return this;
  10218. // just one destination. most common case.
  10219. if (state.pipesCount === 1) {
  10220. // passed in one, but it's not the right one.
  10221. if (dest && dest !== state.pipes) return this;
  10222. if (!dest) dest = state.pipes;
  10223. // got a match.
  10224. state.pipes = null;
  10225. state.pipesCount = 0;
  10226. state.flowing = false;
  10227. if (dest) dest.emit('unpipe', this, unpipeInfo);
  10228. return this;
  10229. }
  10230. // slow case. multiple pipe destinations.
  10231. if (!dest) {
  10232. // remove all.
  10233. var dests = state.pipes;
  10234. var len = state.pipesCount;
  10235. state.pipes = null;
  10236. state.pipesCount = 0;
  10237. state.flowing = false;
  10238. for (var i = 0; i < len; i++) {
  10239. dests[i].emit('unpipe', this, unpipeInfo);
  10240. }return this;
  10241. }
  10242. // try to find the right one.
  10243. var index = indexOf(state.pipes, dest);
  10244. if (index === -1) return this;
  10245. state.pipes.splice(index, 1);
  10246. state.pipesCount -= 1;
  10247. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  10248. dest.emit('unpipe', this, unpipeInfo);
  10249. return this;
  10250. };
  10251. // set up data events if they are asked for
  10252. // Ensure readable listeners eventually get something
  10253. Readable.prototype.on = function (ev, fn) {
  10254. var res = Stream.prototype.on.call(this, ev, fn);
  10255. if (ev === 'data') {
  10256. // Start flowing on next tick if stream isn't explicitly paused
  10257. if (this._readableState.flowing !== false) this.resume();
  10258. } else if (ev === 'readable') {
  10259. var state = this._readableState;
  10260. if (!state.endEmitted && !state.readableListening) {
  10261. state.readableListening = state.needReadable = true;
  10262. state.emittedReadable = false;
  10263. if (!state.reading) {
  10264. pna.nextTick(nReadingNextTick, this);
  10265. } else if (state.length) {
  10266. emitReadable(this);
  10267. }
  10268. }
  10269. }
  10270. return res;
  10271. };
  10272. Readable.prototype.addListener = Readable.prototype.on;
  10273. function nReadingNextTick(self) {
  10274. debug('readable nexttick read 0');
  10275. self.read(0);
  10276. }
  10277. // pause() and resume() are remnants of the legacy readable stream API
  10278. // If the user uses them, then switch into old mode.
  10279. Readable.prototype.resume = function () {
  10280. var state = this._readableState;
  10281. if (!state.flowing) {
  10282. debug('resume');
  10283. state.flowing = true;
  10284. resume(this, state);
  10285. }
  10286. return this;
  10287. };
  10288. function resume(stream, state) {
  10289. if (!state.resumeScheduled) {
  10290. state.resumeScheduled = true;
  10291. pna.nextTick(resume_, stream, state);
  10292. }
  10293. }
  10294. function resume_(stream, state) {
  10295. if (!state.reading) {
  10296. debug('resume read 0');
  10297. stream.read(0);
  10298. }
  10299. state.resumeScheduled = false;
  10300. state.awaitDrain = 0;
  10301. stream.emit('resume');
  10302. flow(stream);
  10303. if (state.flowing && !state.reading) stream.read(0);
  10304. }
  10305. Readable.prototype.pause = function () {
  10306. debug('call pause flowing=%j', this._readableState.flowing);
  10307. if (false !== this._readableState.flowing) {
  10308. debug('pause');
  10309. this._readableState.flowing = false;
  10310. this.emit('pause');
  10311. }
  10312. return this;
  10313. };
  10314. function flow(stream) {
  10315. var state = stream._readableState;
  10316. debug('flow', state.flowing);
  10317. while (state.flowing && stream.read() !== null) {}
  10318. }
  10319. // wrap an old-style stream as the async data source.
  10320. // This is *not* part of the readable stream interface.
  10321. // It is an ugly unfortunate mess of history.
  10322. Readable.prototype.wrap = function (stream) {
  10323. var _this = this;
  10324. var state = this._readableState;
  10325. var paused = false;
  10326. stream.on('end', function () {
  10327. debug('wrapped end');
  10328. if (state.decoder && !state.ended) {
  10329. var chunk = state.decoder.end();
  10330. if (chunk && chunk.length) _this.push(chunk);
  10331. }
  10332. _this.push(null);
  10333. });
  10334. stream.on('data', function (chunk) {
  10335. debug('wrapped data');
  10336. if (state.decoder) chunk = state.decoder.write(chunk);
  10337. // don't skip over falsy values in objectMode
  10338. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  10339. var ret = _this.push(chunk);
  10340. if (!ret) {
  10341. paused = true;
  10342. stream.pause();
  10343. }
  10344. });
  10345. // proxy all the other methods.
  10346. // important when wrapping filters and duplexes.
  10347. for (var i in stream) {
  10348. if (this[i] === undefined && typeof stream[i] === 'function') {
  10349. this[i] = function (method) {
  10350. return function () {
  10351. return stream[method].apply(stream, arguments);
  10352. };
  10353. }(i);
  10354. }
  10355. }
  10356. // proxy certain important events.
  10357. for (var n = 0; n < kProxyEvents.length; n++) {
  10358. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  10359. }
  10360. // when we try to consume some more bytes, simply unpause the
  10361. // underlying stream.
  10362. this._read = function (n) {
  10363. debug('wrapped _read', n);
  10364. if (paused) {
  10365. paused = false;
  10366. stream.resume();
  10367. }
  10368. };
  10369. return this;
  10370. };
  10371. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  10372. // making it explicit this property is not enumerable
  10373. // because otherwise some prototype manipulation in
  10374. // userland will fail
  10375. enumerable: false,
  10376. get: function () {
  10377. return this._readableState.highWaterMark;
  10378. }
  10379. });
  10380. // exposed for testing purposes only.
  10381. Readable._fromList = fromList;
  10382. // Pluck off n bytes from an array of buffers.
  10383. // Length is the combined lengths of all the buffers in the list.
  10384. // This function is designed to be inlinable, so please take care when making
  10385. // changes to the function body.
  10386. function fromList(n, state) {
  10387. // nothing buffered
  10388. if (state.length === 0) return null;
  10389. var ret;
  10390. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  10391. // read it all, truncate the list
  10392. 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);
  10393. state.buffer.clear();
  10394. } else {
  10395. // read part of list
  10396. ret = fromListPartial(n, state.buffer, state.decoder);
  10397. }
  10398. return ret;
  10399. }
  10400. // Extracts only enough buffered data to satisfy the amount requested.
  10401. // This function is designed to be inlinable, so please take care when making
  10402. // changes to the function body.
  10403. function fromListPartial(n, list, hasStrings) {
  10404. var ret;
  10405. if (n < list.head.data.length) {
  10406. // slice is the same for buffers and strings
  10407. ret = list.head.data.slice(0, n);
  10408. list.head.data = list.head.data.slice(n);
  10409. } else if (n === list.head.data.length) {
  10410. // first chunk is a perfect match
  10411. ret = list.shift();
  10412. } else {
  10413. // result spans more than one buffer
  10414. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  10415. }
  10416. return ret;
  10417. }
  10418. // Copies a specified amount of characters from the list of buffered data
  10419. // chunks.
  10420. // This function is designed to be inlinable, so please take care when making
  10421. // changes to the function body.
  10422. function copyFromBufferString(n, list) {
  10423. var p = list.head;
  10424. var c = 1;
  10425. var ret = p.data;
  10426. n -= ret.length;
  10427. while (p = p.next) {
  10428. var str = p.data;
  10429. var nb = n > str.length ? str.length : n;
  10430. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  10431. n -= nb;
  10432. if (n === 0) {
  10433. if (nb === str.length) {
  10434. ++c;
  10435. if (p.next) list.head = p.next;else list.head = list.tail = null;
  10436. } else {
  10437. list.head = p;
  10438. p.data = str.slice(nb);
  10439. }
  10440. break;
  10441. }
  10442. ++c;
  10443. }
  10444. list.length -= c;
  10445. return ret;
  10446. }
  10447. // Copies a specified amount of bytes from the list of buffered data chunks.
  10448. // This function is designed to be inlinable, so please take care when making
  10449. // changes to the function body.
  10450. function copyFromBuffer(n, list) {
  10451. var ret = Buffer.allocUnsafe(n);
  10452. var p = list.head;
  10453. var c = 1;
  10454. p.data.copy(ret);
  10455. n -= p.data.length;
  10456. while (p = p.next) {
  10457. var buf = p.data;
  10458. var nb = n > buf.length ? buf.length : n;
  10459. buf.copy(ret, ret.length - n, 0, nb);
  10460. n -= nb;
  10461. if (n === 0) {
  10462. if (nb === buf.length) {
  10463. ++c;
  10464. if (p.next) list.head = p.next;else list.head = list.tail = null;
  10465. } else {
  10466. list.head = p;
  10467. p.data = buf.slice(nb);
  10468. }
  10469. break;
  10470. }
  10471. ++c;
  10472. }
  10473. list.length -= c;
  10474. return ret;
  10475. }
  10476. function endReadable(stream) {
  10477. var state = stream._readableState;
  10478. // If we get here before consuming all the bytes, then that is a
  10479. // bug in node. Should never happen.
  10480. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  10481. if (!state.endEmitted) {
  10482. state.ended = true;
  10483. pna.nextTick(endReadableNT, state, stream);
  10484. }
  10485. }
  10486. function endReadableNT(state, stream) {
  10487. // Check that we didn't get one last unshift.
  10488. if (!state.endEmitted && state.length === 0) {
  10489. state.endEmitted = true;
  10490. stream.readable = false;
  10491. stream.emit('end');
  10492. }
  10493. }
  10494. function indexOf(xs, x) {
  10495. for (var i = 0, l = xs.length; i < l; i++) {
  10496. if (xs[i] === x) return i;
  10497. }
  10498. return -1;
  10499. }
  10500. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10501. },{"./_stream_duplex":106,"./internal/streams/BufferList":111,"./internal/streams/destroy":112,"./internal/streams/stream":113,"_process":100,"core-util-is":13,"events":83,"inherits":88,"isarray":114,"process-nextick-args":99,"safe-buffer":118,"string_decoder/":115,"util":11}],109:[function(require,module,exports){
  10502. // Copyright Joyent, Inc. and other Node contributors.
  10503. //
  10504. // Permission is hereby granted, free of charge, to any person obtaining a
  10505. // copy of this software and associated documentation files (the
  10506. // "Software"), to deal in the Software without restriction, including
  10507. // without limitation the rights to use, copy, modify, merge, publish,
  10508. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10509. // persons to whom the Software is furnished to do so, subject to the
  10510. // following conditions:
  10511. //
  10512. // The above copyright notice and this permission notice shall be included
  10513. // in all copies or substantial portions of the Software.
  10514. //
  10515. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10516. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10517. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10518. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10519. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10520. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10521. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10522. // a transform stream is a readable/writable stream where you do
  10523. // something with the data. Sometimes it's called a "filter",
  10524. // but that's not a great name for it, since that implies a thing where
  10525. // some bits pass through, and others are simply ignored. (That would
  10526. // be a valid example of a transform, of course.)
  10527. //
  10528. // While the output is causally related to the input, it's not a
  10529. // necessarily symmetric or synchronous transformation. For example,
  10530. // a zlib stream might take multiple plain-text writes(), and then
  10531. // emit a single compressed chunk some time in the future.
  10532. //
  10533. // Here's how this works:
  10534. //
  10535. // The Transform stream has all the aspects of the readable and writable
  10536. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  10537. // internally, and returns false if there's a lot of pending writes
  10538. // buffered up. When you call read(), that calls _read(n) until
  10539. // there's enough pending readable data buffered up.
  10540. //
  10541. // In a transform stream, the written data is placed in a buffer. When
  10542. // _read(n) is called, it transforms the queued up data, calling the
  10543. // buffered _write cb's as it consumes chunks. If consuming a single
  10544. // written chunk would result in multiple output chunks, then the first
  10545. // outputted bit calls the readcb, and subsequent chunks just go into
  10546. // the read buffer, and will cause it to emit 'readable' if necessary.
  10547. //
  10548. // This way, back-pressure is actually determined by the reading side,
  10549. // since _read has to be called to start processing a new chunk. However,
  10550. // a pathological inflate type of transform can cause excessive buffering
  10551. // here. For example, imagine a stream where every byte of input is
  10552. // interpreted as an integer from 0-255, and then results in that many
  10553. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  10554. // 1kb of data being output. In this case, you could write a very small
  10555. // amount of input, and end up with a very large amount of output. In
  10556. // such a pathological inflating mechanism, there'd be no way to tell
  10557. // the system to stop doing the transform. A single 4MB write could
  10558. // cause the system to run out of memory.
  10559. //
  10560. // However, even in such a pathological case, only a single written chunk
  10561. // would be consumed, and then the rest would wait (un-transformed) until
  10562. // the results of the previous transformed chunk were consumed.
  10563. 'use strict';
  10564. module.exports = Transform;
  10565. var Duplex = require('./_stream_duplex');
  10566. /*<replacement>*/
  10567. var util = require('core-util-is');
  10568. util.inherits = require('inherits');
  10569. /*</replacement>*/
  10570. util.inherits(Transform, Duplex);
  10571. function afterTransform(er, data) {
  10572. var ts = this._transformState;
  10573. ts.transforming = false;
  10574. var cb = ts.writecb;
  10575. if (!cb) {
  10576. return this.emit('error', new Error('write callback called multiple times'));
  10577. }
  10578. ts.writechunk = null;
  10579. ts.writecb = null;
  10580. if (data != null) // single equals check for both `null` and `undefined`
  10581. this.push(data);
  10582. cb(er);
  10583. var rs = this._readableState;
  10584. rs.reading = false;
  10585. if (rs.needReadable || rs.length < rs.highWaterMark) {
  10586. this._read(rs.highWaterMark);
  10587. }
  10588. }
  10589. function Transform(options) {
  10590. if (!(this instanceof Transform)) return new Transform(options);
  10591. Duplex.call(this, options);
  10592. this._transformState = {
  10593. afterTransform: afterTransform.bind(this),
  10594. needTransform: false,
  10595. transforming: false,
  10596. writecb: null,
  10597. writechunk: null,
  10598. writeencoding: null
  10599. };
  10600. // start out asking for a readable event once data is transformed.
  10601. this._readableState.needReadable = true;
  10602. // we have implemented the _read method, and done the other things
  10603. // that Readable wants before the first _read call, so unset the
  10604. // sync guard flag.
  10605. this._readableState.sync = false;
  10606. if (options) {
  10607. if (typeof options.transform === 'function') this._transform = options.transform;
  10608. if (typeof options.flush === 'function') this._flush = options.flush;
  10609. }
  10610. // When the writable side finishes, then flush out anything remaining.
  10611. this.on('prefinish', prefinish);
  10612. }
  10613. function prefinish() {
  10614. var _this = this;
  10615. if (typeof this._flush === 'function') {
  10616. this._flush(function (er, data) {
  10617. done(_this, er, data);
  10618. });
  10619. } else {
  10620. done(this, null, null);
  10621. }
  10622. }
  10623. Transform.prototype.push = function (chunk, encoding) {
  10624. this._transformState.needTransform = false;
  10625. return Duplex.prototype.push.call(this, chunk, encoding);
  10626. };
  10627. // This is the part where you do stuff!
  10628. // override this function in implementation classes.
  10629. // 'chunk' is an input chunk.
  10630. //
  10631. // Call `push(newChunk)` to pass along transformed output
  10632. // to the readable side. You may call 'push' zero or more times.
  10633. //
  10634. // Call `cb(err)` when you are done with this chunk. If you pass
  10635. // an error, then that'll put the hurt on the whole operation. If you
  10636. // never call cb(), then you'll never get another chunk.
  10637. Transform.prototype._transform = function (chunk, encoding, cb) {
  10638. throw new Error('_transform() is not implemented');
  10639. };
  10640. Transform.prototype._write = function (chunk, encoding, cb) {
  10641. var ts = this._transformState;
  10642. ts.writecb = cb;
  10643. ts.writechunk = chunk;
  10644. ts.writeencoding = encoding;
  10645. if (!ts.transforming) {
  10646. var rs = this._readableState;
  10647. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  10648. }
  10649. };
  10650. // Doesn't matter what the args are here.
  10651. // _transform does all the work.
  10652. // That we got here means that the readable side wants more data.
  10653. Transform.prototype._read = function (n) {
  10654. var ts = this._transformState;
  10655. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  10656. ts.transforming = true;
  10657. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  10658. } else {
  10659. // mark that we need a transform, so that any data that comes in
  10660. // will get processed, now that we've asked for it.
  10661. ts.needTransform = true;
  10662. }
  10663. };
  10664. Transform.prototype._destroy = function (err, cb) {
  10665. var _this2 = this;
  10666. Duplex.prototype._destroy.call(this, err, function (err2) {
  10667. cb(err2);
  10668. _this2.emit('close');
  10669. });
  10670. };
  10671. function done(stream, er, data) {
  10672. if (er) return stream.emit('error', er);
  10673. if (data != null) // single equals check for both `null` and `undefined`
  10674. stream.push(data);
  10675. // if there's nothing in the write buffer, then that means
  10676. // that nothing more will ever be provided
  10677. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  10678. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  10679. return stream.push(null);
  10680. }
  10681. },{"./_stream_duplex":106,"core-util-is":13,"inherits":88}],110:[function(require,module,exports){
  10682. (function (process,global,setImmediate){
  10683. // Copyright Joyent, Inc. and other Node contributors.
  10684. //
  10685. // Permission is hereby granted, free of charge, to any person obtaining a
  10686. // copy of this software and associated documentation files (the
  10687. // "Software"), to deal in the Software without restriction, including
  10688. // without limitation the rights to use, copy, modify, merge, publish,
  10689. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10690. // persons to whom the Software is furnished to do so, subject to the
  10691. // following conditions:
  10692. //
  10693. // The above copyright notice and this permission notice shall be included
  10694. // in all copies or substantial portions of the Software.
  10695. //
  10696. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10697. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10698. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10699. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10700. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10701. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10702. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10703. // A bit simpler than readable streams.
  10704. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  10705. // the drain event emission and buffering.
  10706. 'use strict';
  10707. /*<replacement>*/
  10708. var pna = require('process-nextick-args');
  10709. /*</replacement>*/
  10710. module.exports = Writable;
  10711. /* <replacement> */
  10712. function WriteReq(chunk, encoding, cb) {
  10713. this.chunk = chunk;
  10714. this.encoding = encoding;
  10715. this.callback = cb;
  10716. this.next = null;
  10717. }
  10718. // It seems a linked list but it is not
  10719. // there will be only 2 of these for each stream
  10720. function CorkedRequest(state) {
  10721. var _this = this;
  10722. this.next = null;
  10723. this.entry = null;
  10724. this.finish = function () {
  10725. onCorkedFinish(_this, state);
  10726. };
  10727. }
  10728. /* </replacement> */
  10729. /*<replacement>*/
  10730. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  10731. /*</replacement>*/
  10732. /*<replacement>*/
  10733. var Duplex;
  10734. /*</replacement>*/
  10735. Writable.WritableState = WritableState;
  10736. /*<replacement>*/
  10737. var util = require('core-util-is');
  10738. util.inherits = require('inherits');
  10739. /*</replacement>*/
  10740. /*<replacement>*/
  10741. var internalUtil = {
  10742. deprecate: require('util-deprecate')
  10743. };
  10744. /*</replacement>*/
  10745. /*<replacement>*/
  10746. var Stream = require('./internal/streams/stream');
  10747. /*</replacement>*/
  10748. /*<replacement>*/
  10749. var Buffer = require('safe-buffer').Buffer;
  10750. var OurUint8Array = global.Uint8Array || function () {};
  10751. function _uint8ArrayToBuffer(chunk) {
  10752. return Buffer.from(chunk);
  10753. }
  10754. function _isUint8Array(obj) {
  10755. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  10756. }
  10757. /*</replacement>*/
  10758. var destroyImpl = require('./internal/streams/destroy');
  10759. util.inherits(Writable, Stream);
  10760. function nop() {}
  10761. function WritableState(options, stream) {
  10762. Duplex = Duplex || require('./_stream_duplex');
  10763. options = options || {};
  10764. // Duplex streams are both readable and writable, but share
  10765. // the same options object.
  10766. // However, some cases require setting options to different
  10767. // values for the readable and the writable sides of the duplex stream.
  10768. // These options can be provided separately as readableXXX and writableXXX.
  10769. var isDuplex = stream instanceof Duplex;
  10770. // object stream flag to indicate whether or not this stream
  10771. // contains buffers or objects.
  10772. this.objectMode = !!options.objectMode;
  10773. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  10774. // the point at which write() starts returning false
  10775. // Note: 0 is a valid value, means that we always return false if
  10776. // the entire buffer is not flushed immediately on write()
  10777. var hwm = options.highWaterMark;
  10778. var writableHwm = options.writableHighWaterMark;
  10779. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  10780. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  10781. // cast to ints.
  10782. this.highWaterMark = Math.floor(this.highWaterMark);
  10783. // if _final has been called
  10784. this.finalCalled = false;
  10785. // drain event flag.
  10786. this.needDrain = false;
  10787. // at the start of calling end()
  10788. this.ending = false;
  10789. // when end() has been called, and returned
  10790. this.ended = false;
  10791. // when 'finish' is emitted
  10792. this.finished = false;
  10793. // has it been destroyed
  10794. this.destroyed = false;
  10795. // should we decode strings into buffers before passing to _write?
  10796. // this is here so that some node-core streams can optimize string
  10797. // handling at a lower level.
  10798. var noDecode = options.decodeStrings === false;
  10799. this.decodeStrings = !noDecode;
  10800. // Crypto is kind of old and crusty. Historically, its default string
  10801. // encoding is 'binary' so we have to make this configurable.
  10802. // Everything else in the universe uses 'utf8', though.
  10803. this.defaultEncoding = options.defaultEncoding || 'utf8';
  10804. // not an actual buffer we keep track of, but a measurement
  10805. // of how much we're waiting to get pushed to some underlying
  10806. // socket or file.
  10807. this.length = 0;
  10808. // a flag to see when we're in the middle of a write.
  10809. this.writing = false;
  10810. // when true all writes will be buffered until .uncork() call
  10811. this.corked = 0;
  10812. // a flag to be able to tell if the onwrite cb is called immediately,
  10813. // or on a later tick. We set this to true at first, because any
  10814. // actions that shouldn't happen until "later" should generally also
  10815. // not happen before the first write call.
  10816. this.sync = true;
  10817. // a flag to know if we're processing previously buffered items, which
  10818. // may call the _write() callback in the same tick, so that we don't
  10819. // end up in an overlapped onwrite situation.
  10820. this.bufferProcessing = false;
  10821. // the callback that's passed to _write(chunk,cb)
  10822. this.onwrite = function (er) {
  10823. onwrite(stream, er);
  10824. };
  10825. // the callback that the user supplies to write(chunk,encoding,cb)
  10826. this.writecb = null;
  10827. // the amount that is being written when _write is called.
  10828. this.writelen = 0;
  10829. this.bufferedRequest = null;
  10830. this.lastBufferedRequest = null;
  10831. // number of pending user-supplied write callbacks
  10832. // this must be 0 before 'finish' can be emitted
  10833. this.pendingcb = 0;
  10834. // emit prefinish if the only thing we're waiting for is _write cbs
  10835. // This is relevant for synchronous Transform streams
  10836. this.prefinished = false;
  10837. // True if the error was already emitted and should not be thrown again
  10838. this.errorEmitted = false;
  10839. // count buffered requests
  10840. this.bufferedRequestCount = 0;
  10841. // allocate the first CorkedRequest, there is always
  10842. // one allocated and free to use, and we maintain at most two
  10843. this.corkedRequestsFree = new CorkedRequest(this);
  10844. }
  10845. WritableState.prototype.getBuffer = function getBuffer() {
  10846. var current = this.bufferedRequest;
  10847. var out = [];
  10848. while (current) {
  10849. out.push(current);
  10850. current = current.next;
  10851. }
  10852. return out;
  10853. };
  10854. (function () {
  10855. try {
  10856. Object.defineProperty(WritableState.prototype, 'buffer', {
  10857. get: internalUtil.deprecate(function () {
  10858. return this.getBuffer();
  10859. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  10860. });
  10861. } catch (_) {}
  10862. })();
  10863. // Test _writableState for inheritance to account for Duplex streams,
  10864. // whose prototype chain only points to Readable.
  10865. var realHasInstance;
  10866. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  10867. realHasInstance = Function.prototype[Symbol.hasInstance];
  10868. Object.defineProperty(Writable, Symbol.hasInstance, {
  10869. value: function (object) {
  10870. if (realHasInstance.call(this, object)) return true;
  10871. if (this !== Writable) return false;
  10872. return object && object._writableState instanceof WritableState;
  10873. }
  10874. });
  10875. } else {
  10876. realHasInstance = function (object) {
  10877. return object instanceof this;
  10878. };
  10879. }
  10880. function Writable(options) {
  10881. Duplex = Duplex || require('./_stream_duplex');
  10882. // Writable ctor is applied to Duplexes, too.
  10883. // `realHasInstance` is necessary because using plain `instanceof`
  10884. // would return false, as no `_writableState` property is attached.
  10885. // Trying to use the custom `instanceof` for Writable here will also break the
  10886. // Node.js LazyTransform implementation, which has a non-trivial getter for
  10887. // `_writableState` that would lead to infinite recursion.
  10888. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  10889. return new Writable(options);
  10890. }
  10891. this._writableState = new WritableState(options, this);
  10892. // legacy.
  10893. this.writable = true;
  10894. if (options) {
  10895. if (typeof options.write === 'function') this._write = options.write;
  10896. if (typeof options.writev === 'function') this._writev = options.writev;
  10897. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  10898. if (typeof options.final === 'function') this._final = options.final;
  10899. }
  10900. Stream.call(this);
  10901. }
  10902. // Otherwise people can pipe Writable streams, which is just wrong.
  10903. Writable.prototype.pipe = function () {
  10904. this.emit('error', new Error('Cannot pipe, not readable'));
  10905. };
  10906. function writeAfterEnd(stream, cb) {
  10907. var er = new Error('write after end');
  10908. // TODO: defer error events consistently everywhere, not just the cb
  10909. stream.emit('error', er);
  10910. pna.nextTick(cb, er);
  10911. }
  10912. // Checks that a user-supplied chunk is valid, especially for the particular
  10913. // mode the stream is in. Currently this means that `null` is never accepted
  10914. // and undefined/non-string values are only allowed in object mode.
  10915. function validChunk(stream, state, chunk, cb) {
  10916. var valid = true;
  10917. var er = false;
  10918. if (chunk === null) {
  10919. er = new TypeError('May not write null values to stream');
  10920. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  10921. er = new TypeError('Invalid non-string/buffer chunk');
  10922. }
  10923. if (er) {
  10924. stream.emit('error', er);
  10925. pna.nextTick(cb, er);
  10926. valid = false;
  10927. }
  10928. return valid;
  10929. }
  10930. Writable.prototype.write = function (chunk, encoding, cb) {
  10931. var state = this._writableState;
  10932. var ret = false;
  10933. var isBuf = !state.objectMode && _isUint8Array(chunk);
  10934. if (isBuf && !Buffer.isBuffer(chunk)) {
  10935. chunk = _uint8ArrayToBuffer(chunk);
  10936. }
  10937. if (typeof encoding === 'function') {
  10938. cb = encoding;
  10939. encoding = null;
  10940. }
  10941. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  10942. if (typeof cb !== 'function') cb = nop;
  10943. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  10944. state.pendingcb++;
  10945. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  10946. }
  10947. return ret;
  10948. };
  10949. Writable.prototype.cork = function () {
  10950. var state = this._writableState;
  10951. state.corked++;
  10952. };
  10953. Writable.prototype.uncork = function () {
  10954. var state = this._writableState;
  10955. if (state.corked) {
  10956. state.corked--;
  10957. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  10958. }
  10959. };
  10960. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  10961. // node::ParseEncoding() requires lower case.
  10962. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  10963. 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);
  10964. this._writableState.defaultEncoding = encoding;
  10965. return this;
  10966. };
  10967. function decodeChunk(state, chunk, encoding) {
  10968. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  10969. chunk = Buffer.from(chunk, encoding);
  10970. }
  10971. return chunk;
  10972. }
  10973. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  10974. // making it explicit this property is not enumerable
  10975. // because otherwise some prototype manipulation in
  10976. // userland will fail
  10977. enumerable: false,
  10978. get: function () {
  10979. return this._writableState.highWaterMark;
  10980. }
  10981. });
  10982. // if we're already writing something, then just put this
  10983. // in the queue, and wait our turn. Otherwise, call _write
  10984. // If we return false, then we need a drain event, so set that flag.
  10985. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  10986. if (!isBuf) {
  10987. var newChunk = decodeChunk(state, chunk, encoding);
  10988. if (chunk !== newChunk) {
  10989. isBuf = true;
  10990. encoding = 'buffer';
  10991. chunk = newChunk;
  10992. }
  10993. }
  10994. var len = state.objectMode ? 1 : chunk.length;
  10995. state.length += len;
  10996. var ret = state.length < state.highWaterMark;
  10997. // we must ensure that previous needDrain will not be reset to false.
  10998. if (!ret) state.needDrain = true;
  10999. if (state.writing || state.corked) {
  11000. var last = state.lastBufferedRequest;
  11001. state.lastBufferedRequest = {
  11002. chunk: chunk,
  11003. encoding: encoding,
  11004. isBuf: isBuf,
  11005. callback: cb,
  11006. next: null
  11007. };
  11008. if (last) {
  11009. last.next = state.lastBufferedRequest;
  11010. } else {
  11011. state.bufferedRequest = state.lastBufferedRequest;
  11012. }
  11013. state.bufferedRequestCount += 1;
  11014. } else {
  11015. doWrite(stream, state, false, len, chunk, encoding, cb);
  11016. }
  11017. return ret;
  11018. }
  11019. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  11020. state.writelen = len;
  11021. state.writecb = cb;
  11022. state.writing = true;
  11023. state.sync = true;
  11024. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  11025. state.sync = false;
  11026. }
  11027. function onwriteError(stream, state, sync, er, cb) {
  11028. --state.pendingcb;
  11029. if (sync) {
  11030. // defer the callback if we are being called synchronously
  11031. // to avoid piling up things on the stack
  11032. pna.nextTick(cb, er);
  11033. // this can emit finish, and it will always happen
  11034. // after error
  11035. pna.nextTick(finishMaybe, stream, state);
  11036. stream._writableState.errorEmitted = true;
  11037. stream.emit('error', er);
  11038. } else {
  11039. // the caller expect this to happen before if
  11040. // it is async
  11041. cb(er);
  11042. stream._writableState.errorEmitted = true;
  11043. stream.emit('error', er);
  11044. // this can emit finish, but finish must
  11045. // always follow error
  11046. finishMaybe(stream, state);
  11047. }
  11048. }
  11049. function onwriteStateUpdate(state) {
  11050. state.writing = false;
  11051. state.writecb = null;
  11052. state.length -= state.writelen;
  11053. state.writelen = 0;
  11054. }
  11055. function onwrite(stream, er) {
  11056. var state = stream._writableState;
  11057. var sync = state.sync;
  11058. var cb = state.writecb;
  11059. onwriteStateUpdate(state);
  11060. if (er) onwriteError(stream, state, sync, er, cb);else {
  11061. // Check if we're actually ready to finish, but don't emit yet
  11062. var finished = needFinish(state);
  11063. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  11064. clearBuffer(stream, state);
  11065. }
  11066. if (sync) {
  11067. /*<replacement>*/
  11068. asyncWrite(afterWrite, stream, state, finished, cb);
  11069. /*</replacement>*/
  11070. } else {
  11071. afterWrite(stream, state, finished, cb);
  11072. }
  11073. }
  11074. }
  11075. function afterWrite(stream, state, finished, cb) {
  11076. if (!finished) onwriteDrain(stream, state);
  11077. state.pendingcb--;
  11078. cb();
  11079. finishMaybe(stream, state);
  11080. }
  11081. // Must force callback to be called on nextTick, so that we don't
  11082. // emit 'drain' before the write() consumer gets the 'false' return
  11083. // value, and has a chance to attach a 'drain' listener.
  11084. function onwriteDrain(stream, state) {
  11085. if (state.length === 0 && state.needDrain) {
  11086. state.needDrain = false;
  11087. stream.emit('drain');
  11088. }
  11089. }
  11090. // if there's something in the buffer waiting, then process it
  11091. function clearBuffer(stream, state) {
  11092. state.bufferProcessing = true;
  11093. var entry = state.bufferedRequest;
  11094. if (stream._writev && entry && entry.next) {
  11095. // Fast case, write everything using _writev()
  11096. var l = state.bufferedRequestCount;
  11097. var buffer = new Array(l);
  11098. var holder = state.corkedRequestsFree;
  11099. holder.entry = entry;
  11100. var count = 0;
  11101. var allBuffers = true;
  11102. while (entry) {
  11103. buffer[count] = entry;
  11104. if (!entry.isBuf) allBuffers = false;
  11105. entry = entry.next;
  11106. count += 1;
  11107. }
  11108. buffer.allBuffers = allBuffers;
  11109. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  11110. // doWrite is almost always async, defer these to save a bit of time
  11111. // as the hot path ends with doWrite
  11112. state.pendingcb++;
  11113. state.lastBufferedRequest = null;
  11114. if (holder.next) {
  11115. state.corkedRequestsFree = holder.next;
  11116. holder.next = null;
  11117. } else {
  11118. state.corkedRequestsFree = new CorkedRequest(state);
  11119. }
  11120. state.bufferedRequestCount = 0;
  11121. } else {
  11122. // Slow case, write chunks one-by-one
  11123. while (entry) {
  11124. var chunk = entry.chunk;
  11125. var encoding = entry.encoding;
  11126. var cb = entry.callback;
  11127. var len = state.objectMode ? 1 : chunk.length;
  11128. doWrite(stream, state, false, len, chunk, encoding, cb);
  11129. entry = entry.next;
  11130. state.bufferedRequestCount--;
  11131. // if we didn't call the onwrite immediately, then
  11132. // it means that we need to wait until it does.
  11133. // also, that means that the chunk and cb are currently
  11134. // being processed, so move the buffer counter past them.
  11135. if (state.writing) {
  11136. break;
  11137. }
  11138. }
  11139. if (entry === null) state.lastBufferedRequest = null;
  11140. }
  11141. state.bufferedRequest = entry;
  11142. state.bufferProcessing = false;
  11143. }
  11144. Writable.prototype._write = function (chunk, encoding, cb) {
  11145. cb(new Error('_write() is not implemented'));
  11146. };
  11147. Writable.prototype._writev = null;
  11148. Writable.prototype.end = function (chunk, encoding, cb) {
  11149. var state = this._writableState;
  11150. if (typeof chunk === 'function') {
  11151. cb = chunk;
  11152. chunk = null;
  11153. encoding = null;
  11154. } else if (typeof encoding === 'function') {
  11155. cb = encoding;
  11156. encoding = null;
  11157. }
  11158. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  11159. // .end() fully uncorks
  11160. if (state.corked) {
  11161. state.corked = 1;
  11162. this.uncork();
  11163. }
  11164. // ignore unnecessary end() calls.
  11165. if (!state.ending && !state.finished) endWritable(this, state, cb);
  11166. };
  11167. function needFinish(state) {
  11168. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  11169. }
  11170. function callFinal(stream, state) {
  11171. stream._final(function (err) {
  11172. state.pendingcb--;
  11173. if (err) {
  11174. stream.emit('error', err);
  11175. }
  11176. state.prefinished = true;
  11177. stream.emit('prefinish');
  11178. finishMaybe(stream, state);
  11179. });
  11180. }
  11181. function prefinish(stream, state) {
  11182. if (!state.prefinished && !state.finalCalled) {
  11183. if (typeof stream._final === 'function') {
  11184. state.pendingcb++;
  11185. state.finalCalled = true;
  11186. pna.nextTick(callFinal, stream, state);
  11187. } else {
  11188. state.prefinished = true;
  11189. stream.emit('prefinish');
  11190. }
  11191. }
  11192. }
  11193. function finishMaybe(stream, state) {
  11194. var need = needFinish(state);
  11195. if (need) {
  11196. prefinish(stream, state);
  11197. if (state.pendingcb === 0) {
  11198. state.finished = true;
  11199. stream.emit('finish');
  11200. }
  11201. }
  11202. return need;
  11203. }
  11204. function endWritable(stream, state, cb) {
  11205. state.ending = true;
  11206. finishMaybe(stream, state);
  11207. if (cb) {
  11208. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  11209. }
  11210. state.ended = true;
  11211. stream.writable = false;
  11212. }
  11213. function onCorkedFinish(corkReq, state, err) {
  11214. var entry = corkReq.entry;
  11215. corkReq.entry = null;
  11216. while (entry) {
  11217. var cb = entry.callback;
  11218. state.pendingcb--;
  11219. cb(err);
  11220. entry = entry.next;
  11221. }
  11222. if (state.corkedRequestsFree) {
  11223. state.corkedRequestsFree.next = corkReq;
  11224. } else {
  11225. state.corkedRequestsFree = corkReq;
  11226. }
  11227. }
  11228. Object.defineProperty(Writable.prototype, 'destroyed', {
  11229. get: function () {
  11230. if (this._writableState === undefined) {
  11231. return false;
  11232. }
  11233. return this._writableState.destroyed;
  11234. },
  11235. set: function (value) {
  11236. // we ignore the value if the stream
  11237. // has not been initialized yet
  11238. if (!this._writableState) {
  11239. return;
  11240. }
  11241. // backward compatibility, the user is explicitly
  11242. // managing destroyed
  11243. this._writableState.destroyed = value;
  11244. }
  11245. });
  11246. Writable.prototype.destroy = destroyImpl.destroy;
  11247. Writable.prototype._undestroy = destroyImpl.undestroy;
  11248. Writable.prototype._destroy = function (err, cb) {
  11249. this.end();
  11250. cb(err);
  11251. };
  11252. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  11253. },{"./_stream_duplex":106,"./internal/streams/destroy":112,"./internal/streams/stream":113,"_process":100,"core-util-is":13,"inherits":88,"process-nextick-args":99,"safe-buffer":118,"timers":120,"util-deprecate":134}],111:[function(require,module,exports){
  11254. 'use strict';
  11255. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11256. var Buffer = require('safe-buffer').Buffer;
  11257. var util = require('util');
  11258. function copyBuffer(src, target, offset) {
  11259. src.copy(target, offset);
  11260. }
  11261. module.exports = function () {
  11262. function BufferList() {
  11263. _classCallCheck(this, BufferList);
  11264. this.head = null;
  11265. this.tail = null;
  11266. this.length = 0;
  11267. }
  11268. BufferList.prototype.push = function push(v) {
  11269. var entry = { data: v, next: null };
  11270. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  11271. this.tail = entry;
  11272. ++this.length;
  11273. };
  11274. BufferList.prototype.unshift = function unshift(v) {
  11275. var entry = { data: v, next: this.head };
  11276. if (this.length === 0) this.tail = entry;
  11277. this.head = entry;
  11278. ++this.length;
  11279. };
  11280. BufferList.prototype.shift = function shift() {
  11281. if (this.length === 0) return;
  11282. var ret = this.head.data;
  11283. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  11284. --this.length;
  11285. return ret;
  11286. };
  11287. BufferList.prototype.clear = function clear() {
  11288. this.head = this.tail = null;
  11289. this.length = 0;
  11290. };
  11291. BufferList.prototype.join = function join(s) {
  11292. if (this.length === 0) return '';
  11293. var p = this.head;
  11294. var ret = '' + p.data;
  11295. while (p = p.next) {
  11296. ret += s + p.data;
  11297. }return ret;
  11298. };
  11299. BufferList.prototype.concat = function concat(n) {
  11300. if (this.length === 0) return Buffer.alloc(0);
  11301. if (this.length === 1) return this.head.data;
  11302. var ret = Buffer.allocUnsafe(n >>> 0);
  11303. var p = this.head;
  11304. var i = 0;
  11305. while (p) {
  11306. copyBuffer(p.data, ret, i);
  11307. i += p.data.length;
  11308. p = p.next;
  11309. }
  11310. return ret;
  11311. };
  11312. return BufferList;
  11313. }();
  11314. if (util && util.inspect && util.inspect.custom) {
  11315. module.exports.prototype[util.inspect.custom] = function () {
  11316. var obj = util.inspect({ length: this.length });
  11317. return this.constructor.name + ' ' + obj;
  11318. };
  11319. }
  11320. },{"safe-buffer":118,"util":11}],112:[function(require,module,exports){
  11321. 'use strict';
  11322. /*<replacement>*/
  11323. var pna = require('process-nextick-args');
  11324. /*</replacement>*/
  11325. // undocumented cb() API, needed for core, not for public API
  11326. function destroy(err, cb) {
  11327. var _this = this;
  11328. var readableDestroyed = this._readableState && this._readableState.destroyed;
  11329. var writableDestroyed = this._writableState && this._writableState.destroyed;
  11330. if (readableDestroyed || writableDestroyed) {
  11331. if (cb) {
  11332. cb(err);
  11333. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  11334. pna.nextTick(emitErrorNT, this, err);
  11335. }
  11336. return this;
  11337. }
  11338. // we set destroyed to true before firing error callbacks in order
  11339. // to make it re-entrance safe in case destroy() is called within callbacks
  11340. if (this._readableState) {
  11341. this._readableState.destroyed = true;
  11342. }
  11343. // if this is a duplex stream mark the writable part as destroyed as well
  11344. if (this._writableState) {
  11345. this._writableState.destroyed = true;
  11346. }
  11347. this._destroy(err || null, function (err) {
  11348. if (!cb && err) {
  11349. pna.nextTick(emitErrorNT, _this, err);
  11350. if (_this._writableState) {
  11351. _this._writableState.errorEmitted = true;
  11352. }
  11353. } else if (cb) {
  11354. cb(err);
  11355. }
  11356. });
  11357. return this;
  11358. }
  11359. function undestroy() {
  11360. if (this._readableState) {
  11361. this._readableState.destroyed = false;
  11362. this._readableState.reading = false;
  11363. this._readableState.ended = false;
  11364. this._readableState.endEmitted = false;
  11365. }
  11366. if (this._writableState) {
  11367. this._writableState.destroyed = false;
  11368. this._writableState.ended = false;
  11369. this._writableState.ending = false;
  11370. this._writableState.finished = false;
  11371. this._writableState.errorEmitted = false;
  11372. }
  11373. }
  11374. function emitErrorNT(self, err) {
  11375. self.emit('error', err);
  11376. }
  11377. module.exports = {
  11378. destroy: destroy,
  11379. undestroy: undestroy
  11380. };
  11381. },{"process-nextick-args":99}],113:[function(require,module,exports){
  11382. module.exports = require('events').EventEmitter;
  11383. },{"events":83}],114:[function(require,module,exports){
  11384. var toString = {}.toString;
  11385. module.exports = Array.isArray || function (arr) {
  11386. return toString.call(arr) == '[object Array]';
  11387. };
  11388. },{}],115:[function(require,module,exports){
  11389. // Copyright Joyent, Inc. and other Node contributors.
  11390. //
  11391. // Permission is hereby granted, free of charge, to any person obtaining a
  11392. // copy of this software and associated documentation files (the
  11393. // "Software"), to deal in the Software without restriction, including
  11394. // without limitation the rights to use, copy, modify, merge, publish,
  11395. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11396. // persons to whom the Software is furnished to do so, subject to the
  11397. // following conditions:
  11398. //
  11399. // The above copyright notice and this permission notice shall be included
  11400. // in all copies or substantial portions of the Software.
  11401. //
  11402. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11403. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11404. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11405. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11406. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11407. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11408. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11409. 'use strict';
  11410. /*<replacement>*/
  11411. var Buffer = require('safe-buffer').Buffer;
  11412. /*</replacement>*/
  11413. var isEncoding = Buffer.isEncoding || function (encoding) {
  11414. encoding = '' + encoding;
  11415. switch (encoding && encoding.toLowerCase()) {
  11416. 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':
  11417. return true;
  11418. default:
  11419. return false;
  11420. }
  11421. };
  11422. function _normalizeEncoding(enc) {
  11423. if (!enc) return 'utf8';
  11424. var retried;
  11425. while (true) {
  11426. switch (enc) {
  11427. case 'utf8':
  11428. case 'utf-8':
  11429. return 'utf8';
  11430. case 'ucs2':
  11431. case 'ucs-2':
  11432. case 'utf16le':
  11433. case 'utf-16le':
  11434. return 'utf16le';
  11435. case 'latin1':
  11436. case 'binary':
  11437. return 'latin1';
  11438. case 'base64':
  11439. case 'ascii':
  11440. case 'hex':
  11441. return enc;
  11442. default:
  11443. if (retried) return; // undefined
  11444. enc = ('' + enc).toLowerCase();
  11445. retried = true;
  11446. }
  11447. }
  11448. };
  11449. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  11450. // modules monkey-patch it to support additional encodings
  11451. function normalizeEncoding(enc) {
  11452. var nenc = _normalizeEncoding(enc);
  11453. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  11454. return nenc || enc;
  11455. }
  11456. // StringDecoder provides an interface for efficiently splitting a series of
  11457. // buffers into a series of JS strings without breaking apart multi-byte
  11458. // characters.
  11459. exports.StringDecoder = StringDecoder;
  11460. function StringDecoder(encoding) {
  11461. this.encoding = normalizeEncoding(encoding);
  11462. var nb;
  11463. switch (this.encoding) {
  11464. case 'utf16le':
  11465. this.text = utf16Text;
  11466. this.end = utf16End;
  11467. nb = 4;
  11468. break;
  11469. case 'utf8':
  11470. this.fillLast = utf8FillLast;
  11471. nb = 4;
  11472. break;
  11473. case 'base64':
  11474. this.text = base64Text;
  11475. this.end = base64End;
  11476. nb = 3;
  11477. break;
  11478. default:
  11479. this.write = simpleWrite;
  11480. this.end = simpleEnd;
  11481. return;
  11482. }
  11483. this.lastNeed = 0;
  11484. this.lastTotal = 0;
  11485. this.lastChar = Buffer.allocUnsafe(nb);
  11486. }
  11487. StringDecoder.prototype.write = function (buf) {
  11488. if (buf.length === 0) return '';
  11489. var r;
  11490. var i;
  11491. if (this.lastNeed) {
  11492. r = this.fillLast(buf);
  11493. if (r === undefined) return '';
  11494. i = this.lastNeed;
  11495. this.lastNeed = 0;
  11496. } else {
  11497. i = 0;
  11498. }
  11499. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  11500. return r || '';
  11501. };
  11502. StringDecoder.prototype.end = utf8End;
  11503. // Returns only complete characters in a Buffer
  11504. StringDecoder.prototype.text = utf8Text;
  11505. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  11506. StringDecoder.prototype.fillLast = function (buf) {
  11507. if (this.lastNeed <= buf.length) {
  11508. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  11509. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  11510. }
  11511. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  11512. this.lastNeed -= buf.length;
  11513. };
  11514. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  11515. // continuation byte. If an invalid byte is detected, -2 is returned.
  11516. function utf8CheckByte(byte) {
  11517. 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;
  11518. return byte >> 6 === 0x02 ? -1 : -2;
  11519. }
  11520. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  11521. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  11522. // needed to complete the UTF-8 character (if applicable) are returned.
  11523. function utf8CheckIncomplete(self, buf, i) {
  11524. var j = buf.length - 1;
  11525. if (j < i) return 0;
  11526. var nb = utf8CheckByte(buf[j]);
  11527. if (nb >= 0) {
  11528. if (nb > 0) self.lastNeed = nb - 1;
  11529. return nb;
  11530. }
  11531. if (--j < i || nb === -2) return 0;
  11532. nb = utf8CheckByte(buf[j]);
  11533. if (nb >= 0) {
  11534. if (nb > 0) self.lastNeed = nb - 2;
  11535. return nb;
  11536. }
  11537. if (--j < i || nb === -2) return 0;
  11538. nb = utf8CheckByte(buf[j]);
  11539. if (nb >= 0) {
  11540. if (nb > 0) {
  11541. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  11542. }
  11543. return nb;
  11544. }
  11545. return 0;
  11546. }
  11547. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  11548. // needed or are available. If we see a non-continuation byte where we expect
  11549. // one, we "replace" the validated continuation bytes we've seen so far with
  11550. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  11551. // behavior. The continuation byte check is included three times in the case
  11552. // where all of the continuation bytes for a character exist in the same buffer.
  11553. // It is also done this way as a slight performance increase instead of using a
  11554. // loop.
  11555. function utf8CheckExtraBytes(self, buf, p) {
  11556. if ((buf[0] & 0xC0) !== 0x80) {
  11557. self.lastNeed = 0;
  11558. return '\ufffd';
  11559. }
  11560. if (self.lastNeed > 1 && buf.length > 1) {
  11561. if ((buf[1] & 0xC0) !== 0x80) {
  11562. self.lastNeed = 1;
  11563. return '\ufffd';
  11564. }
  11565. if (self.lastNeed > 2 && buf.length > 2) {
  11566. if ((buf[2] & 0xC0) !== 0x80) {
  11567. self.lastNeed = 2;
  11568. return '\ufffd';
  11569. }
  11570. }
  11571. }
  11572. }
  11573. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  11574. function utf8FillLast(buf) {
  11575. var p = this.lastTotal - this.lastNeed;
  11576. var r = utf8CheckExtraBytes(this, buf, p);
  11577. if (r !== undefined) return r;
  11578. if (this.lastNeed <= buf.length) {
  11579. buf.copy(this.lastChar, p, 0, this.lastNeed);
  11580. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  11581. }
  11582. buf.copy(this.lastChar, p, 0, buf.length);
  11583. this.lastNeed -= buf.length;
  11584. }
  11585. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  11586. // partial character, the character's bytes are buffered until the required
  11587. // number of bytes are available.
  11588. function utf8Text(buf, i) {
  11589. var total = utf8CheckIncomplete(this, buf, i);
  11590. if (!this.lastNeed) return buf.toString('utf8', i);
  11591. this.lastTotal = total;
  11592. var end = buf.length - (total - this.lastNeed);
  11593. buf.copy(this.lastChar, 0, end);
  11594. return buf.toString('utf8', i, end);
  11595. }
  11596. // For UTF-8, a replacement character is added when ending on a partial
  11597. // character.
  11598. function utf8End(buf) {
  11599. var r = buf && buf.length ? this.write(buf) : '';
  11600. if (this.lastNeed) return r + '\ufffd';
  11601. return r;
  11602. }
  11603. // UTF-16LE typically needs two bytes per character, but even if we have an even
  11604. // number of bytes available, we need to check if we end on a leading/high
  11605. // surrogate. In that case, we need to wait for the next two bytes in order to
  11606. // decode the last character properly.
  11607. function utf16Text(buf, i) {
  11608. if ((buf.length - i) % 2 === 0) {
  11609. var r = buf.toString('utf16le', i);
  11610. if (r) {
  11611. var c = r.charCodeAt(r.length - 1);
  11612. if (c >= 0xD800 && c <= 0xDBFF) {
  11613. this.lastNeed = 2;
  11614. this.lastTotal = 4;
  11615. this.lastChar[0] = buf[buf.length - 2];
  11616. this.lastChar[1] = buf[buf.length - 1];
  11617. return r.slice(0, -1);
  11618. }
  11619. }
  11620. return r;
  11621. }
  11622. this.lastNeed = 1;
  11623. this.lastTotal = 2;
  11624. this.lastChar[0] = buf[buf.length - 1];
  11625. return buf.toString('utf16le', i, buf.length - 1);
  11626. }
  11627. // For UTF-16LE we do not explicitly append special replacement characters if we
  11628. // end on a partial character, we simply let v8 handle that.
  11629. function utf16End(buf) {
  11630. var r = buf && buf.length ? this.write(buf) : '';
  11631. if (this.lastNeed) {
  11632. var end = this.lastTotal - this.lastNeed;
  11633. return r + this.lastChar.toString('utf16le', 0, end);
  11634. }
  11635. return r;
  11636. }
  11637. function base64Text(buf, i) {
  11638. var n = (buf.length - i) % 3;
  11639. if (n === 0) return buf.toString('base64', i);
  11640. this.lastNeed = 3 - n;
  11641. this.lastTotal = 3;
  11642. if (n === 1) {
  11643. this.lastChar[0] = buf[buf.length - 1];
  11644. } else {
  11645. this.lastChar[0] = buf[buf.length - 2];
  11646. this.lastChar[1] = buf[buf.length - 1];
  11647. }
  11648. return buf.toString('base64', i, buf.length - n);
  11649. }
  11650. function base64End(buf) {
  11651. var r = buf && buf.length ? this.write(buf) : '';
  11652. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  11653. return r;
  11654. }
  11655. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  11656. function simpleWrite(buf) {
  11657. return buf.toString(this.encoding);
  11658. }
  11659. function simpleEnd(buf) {
  11660. return buf && buf.length ? this.write(buf) : '';
  11661. }
  11662. },{"safe-buffer":118}],116:[function(require,module,exports){
  11663. exports = module.exports = require('./lib/_stream_readable.js');
  11664. exports.Stream = exports;
  11665. exports.Readable = exports;
  11666. exports.Writable = require('./lib/_stream_writable.js');
  11667. exports.Duplex = require('./lib/_stream_duplex.js');
  11668. exports.Transform = require('./lib/_stream_transform.js');
  11669. exports.PassThrough = require('./lib/_stream_passthrough.js');
  11670. },{"./lib/_stream_duplex.js":106,"./lib/_stream_passthrough.js":107,"./lib/_stream_readable.js":108,"./lib/_stream_transform.js":109,"./lib/_stream_writable.js":110}],117:[function(require,module,exports){
  11671. 'use strict'
  11672. function ReInterval (callback, interval, args) {
  11673. var self = this;
  11674. this._callback = callback;
  11675. this._args = args;
  11676. this._interval = setInterval(callback, interval, this._args);
  11677. this.reschedule = function (interval) {
  11678. // if no interval entered, use the interval passed in on creation
  11679. if (!interval)
  11680. interval = self._interval;
  11681. if (self._interval)
  11682. clearInterval(self._interval);
  11683. self._interval = setInterval(self._callback, interval, self._args);
  11684. };
  11685. this.clear = function () {
  11686. if (self._interval) {
  11687. clearInterval(self._interval);
  11688. self._interval = undefined;
  11689. }
  11690. };
  11691. this.destroy = function () {
  11692. if (self._interval) {
  11693. clearInterval(self._interval);
  11694. }
  11695. self._callback = undefined;
  11696. self._interval = undefined;
  11697. self._args = undefined;
  11698. };
  11699. }
  11700. function reInterval () {
  11701. if (typeof arguments[0] !== 'function')
  11702. throw new Error('callback needed');
  11703. if (typeof arguments[1] !== 'number')
  11704. throw new Error('interval needed');
  11705. var args;
  11706. if (arguments.length > 0) {
  11707. args = new Array(arguments.length - 2);
  11708. for (var i = 0; i < args.length; i++) {
  11709. args[i] = arguments[i + 2];
  11710. }
  11711. }
  11712. return new ReInterval(arguments[0], arguments[1], args);
  11713. }
  11714. module.exports = reInterval;
  11715. },{}],118:[function(require,module,exports){
  11716. /* eslint-disable node/no-deprecated-api */
  11717. var buffer = require('buffer')
  11718. var Buffer = buffer.Buffer
  11719. // alternative to using Object.keys for old browsers
  11720. function copyProps (src, dst) {
  11721. for (var key in src) {
  11722. dst[key] = src[key]
  11723. }
  11724. }
  11725. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  11726. module.exports = buffer
  11727. } else {
  11728. // Copy properties from require('buffer')
  11729. copyProps(buffer, exports)
  11730. exports.Buffer = SafeBuffer
  11731. }
  11732. function SafeBuffer (arg, encodingOrOffset, length) {
  11733. return Buffer(arg, encodingOrOffset, length)
  11734. }
  11735. // Copy static methods from Buffer
  11736. copyProps(Buffer, SafeBuffer)
  11737. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  11738. if (typeof arg === 'number') {
  11739. throw new TypeError('Argument must not be a number')
  11740. }
  11741. return Buffer(arg, encodingOrOffset, length)
  11742. }
  11743. SafeBuffer.alloc = function (size, fill, encoding) {
  11744. if (typeof size !== 'number') {
  11745. throw new TypeError('Argument must be a number')
  11746. }
  11747. var buf = Buffer(size)
  11748. if (fill !== undefined) {
  11749. if (typeof encoding === 'string') {
  11750. buf.fill(fill, encoding)
  11751. } else {
  11752. buf.fill(fill)
  11753. }
  11754. } else {
  11755. buf.fill(0)
  11756. }
  11757. return buf
  11758. }
  11759. SafeBuffer.allocUnsafe = function (size) {
  11760. if (typeof size !== 'number') {
  11761. throw new TypeError('Argument must be a number')
  11762. }
  11763. return Buffer(size)
  11764. }
  11765. SafeBuffer.allocUnsafeSlow = function (size) {
  11766. if (typeof size !== 'number') {
  11767. throw new TypeError('Argument must be a number')
  11768. }
  11769. return buffer.SlowBuffer(size)
  11770. }
  11771. },{"buffer":12}],119:[function(require,module,exports){
  11772. module.exports = shift
  11773. function shift (stream) {
  11774. var rs = stream._readableState
  11775. if (!rs) return null
  11776. return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs))
  11777. }
  11778. function getStateLength (state) {
  11779. if (state.buffer.length) {
  11780. // Since node 6.3.0 state.buffer is a BufferList not an array
  11781. if (state.buffer.head) {
  11782. return state.buffer.head.data.length
  11783. }
  11784. return state.buffer[0].length
  11785. }
  11786. return state.length
  11787. }
  11788. },{}],120:[function(require,module,exports){
  11789. (function (setImmediate,clearImmediate){
  11790. var nextTick = require('process/browser.js').nextTick;
  11791. var apply = Function.prototype.apply;
  11792. var slice = Array.prototype.slice;
  11793. var immediateIds = {};
  11794. var nextImmediateId = 0;
  11795. // DOM APIs, for completeness
  11796. exports.setTimeout = function() {
  11797. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  11798. };
  11799. exports.setInterval = function() {
  11800. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  11801. };
  11802. exports.clearTimeout =
  11803. exports.clearInterval = function(timeout) { timeout.close(); };
  11804. function Timeout(id, clearFn) {
  11805. this._id = id;
  11806. this._clearFn = clearFn;
  11807. }
  11808. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  11809. Timeout.prototype.close = function() {
  11810. this._clearFn.call(window, this._id);
  11811. };
  11812. // Does not start the time, just sets up the members needed.
  11813. exports.enroll = function(item, msecs) {
  11814. clearTimeout(item._idleTimeoutId);
  11815. item._idleTimeout = msecs;
  11816. };
  11817. exports.unenroll = function(item) {
  11818. clearTimeout(item._idleTimeoutId);
  11819. item._idleTimeout = -1;
  11820. };
  11821. exports._unrefActive = exports.active = function(item) {
  11822. clearTimeout(item._idleTimeoutId);
  11823. var msecs = item._idleTimeout;
  11824. if (msecs >= 0) {
  11825. item._idleTimeoutId = setTimeout(function onTimeout() {
  11826. if (item._onTimeout)
  11827. item._onTimeout();
  11828. }, msecs);
  11829. }
  11830. };
  11831. // That's not how node.js implements it but the exposed api is the same.
  11832. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  11833. var id = nextImmediateId++;
  11834. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  11835. immediateIds[id] = true;
  11836. nextTick(function onNextTick() {
  11837. if (immediateIds[id]) {
  11838. // fn.call() is faster so we optimize for the common use-case
  11839. // @see http://jsperf.com/call-apply-segu
  11840. if (args) {
  11841. fn.apply(null, args);
  11842. } else {
  11843. fn.call(null);
  11844. }
  11845. // Prevent ids from leaking
  11846. exports.clearImmediate(id);
  11847. }
  11848. });
  11849. return id;
  11850. };
  11851. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  11852. delete immediateIds[id];
  11853. };
  11854. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  11855. },{"process/browser.js":100,"timers":120}],121:[function(require,module,exports){
  11856. "use strict";
  11857. var isPrototype = require("../prototype/is");
  11858. module.exports = function (value) {
  11859. if (typeof value !== "function") return false;
  11860. if (!hasOwnProperty.call(value, "length")) return false;
  11861. try {
  11862. if (typeof value.length !== "number") return false;
  11863. if (typeof value.call !== "function") return false;
  11864. if (typeof value.apply !== "function") return false;
  11865. } catch (error) {
  11866. return false;
  11867. }
  11868. return !isPrototype(value);
  11869. };
  11870. },{"../prototype/is":128}],122:[function(require,module,exports){
  11871. "use strict";
  11872. var isValue = require("../value/is")
  11873. , isObject = require("../object/is")
  11874. , stringCoerce = require("../string/coerce")
  11875. , toShortString = require("./to-short-string");
  11876. var resolveMessage = function (message, value) {
  11877. return message.replace("%v", toShortString(value));
  11878. };
  11879. module.exports = function (value, defaultMessage, inputOptions) {
  11880. if (!isObject(inputOptions)) throw new TypeError(resolveMessage(defaultMessage, value));
  11881. if (!isValue(value)) {
  11882. if ("default" in inputOptions) return inputOptions["default"];
  11883. if (inputOptions.isOptional) return null;
  11884. }
  11885. var errorMessage = stringCoerce(inputOptions.errorMessage);
  11886. if (!isValue(errorMessage)) errorMessage = defaultMessage;
  11887. throw new TypeError(resolveMessage(errorMessage, value));
  11888. };
  11889. },{"../object/is":125,"../string/coerce":129,"../value/is":131,"./to-short-string":124}],123:[function(require,module,exports){
  11890. "use strict";
  11891. module.exports = function (value) {
  11892. try {
  11893. return value.toString();
  11894. } catch (error) {
  11895. try { return String(value); }
  11896. catch (error2) { return null; }
  11897. }
  11898. };
  11899. },{}],124:[function(require,module,exports){
  11900. "use strict";
  11901. var safeToString = require("./safe-to-string");
  11902. var reNewLine = /[\n\r\u2028\u2029]/g;
  11903. module.exports = function (value) {
  11904. var string = safeToString(value);
  11905. if (string === null) return "<Non-coercible to string value>";
  11906. // Trim if too long
  11907. if (string.length > 100) string = string.slice(0, 99) + "…";
  11908. // Replace eventual new lines
  11909. string = string.replace(reNewLine, function (char) {
  11910. switch (char) {
  11911. case "\n":
  11912. return "\\n";
  11913. case "\r":
  11914. return "\\r";
  11915. case "\u2028":
  11916. return "\\u2028";
  11917. case "\u2029":
  11918. return "\\u2029";
  11919. /* istanbul ignore next */
  11920. default:
  11921. throw new Error("Unexpected character");
  11922. }
  11923. });
  11924. return string;
  11925. };
  11926. },{"./safe-to-string":123}],125:[function(require,module,exports){
  11927. "use strict";
  11928. var isValue = require("../value/is");
  11929. // prettier-ignore
  11930. var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ };
  11931. module.exports = function (value) {
  11932. if (!isValue(value)) return false;
  11933. return hasOwnProperty.call(possibleTypes, typeof value);
  11934. };
  11935. },{"../value/is":131}],126:[function(require,module,exports){
  11936. "use strict";
  11937. var resolveException = require("../lib/resolve-exception")
  11938. , is = require("./is");
  11939. module.exports = function (value/*, options*/) {
  11940. if (is(value)) return value;
  11941. return resolveException(value, "%v is not a plain function", arguments[1]);
  11942. };
  11943. },{"../lib/resolve-exception":122,"./is":127}],127:[function(require,module,exports){
  11944. "use strict";
  11945. var isFunction = require("../function/is");
  11946. var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString;
  11947. module.exports = function (value) {
  11948. if (!isFunction(value)) return false;
  11949. if (classRe.test(functionToString.call(value))) return false;
  11950. return true;
  11951. };
  11952. },{"../function/is":121}],128:[function(require,module,exports){
  11953. "use strict";
  11954. var isObject = require("../object/is");
  11955. module.exports = function (value) {
  11956. if (!isObject(value)) return false;
  11957. try {
  11958. if (!value.constructor) return false;
  11959. return value.constructor.prototype === value;
  11960. } catch (error) {
  11961. return false;
  11962. }
  11963. };
  11964. },{"../object/is":125}],129:[function(require,module,exports){
  11965. "use strict";
  11966. var isValue = require("../value/is")
  11967. , isObject = require("../object/is");
  11968. var objectToString = Object.prototype.toString;
  11969. module.exports = function (value) {
  11970. if (!isValue(value)) return null;
  11971. if (isObject(value)) {
  11972. // Reject Object.prototype.toString coercion
  11973. var valueToString = value.toString;
  11974. if (typeof valueToString !== "function") return null;
  11975. if (valueToString === objectToString) return null;
  11976. // Note: It can be object coming from other realm, still as there's no ES3 and CSP compliant
  11977. // way to resolve its realm's Object.prototype.toString it's left as not addressed edge case
  11978. }
  11979. try {
  11980. return "" + value; // Ensure implicit coercion
  11981. } catch (error) {
  11982. return null;
  11983. }
  11984. };
  11985. },{"../object/is":125,"../value/is":131}],130:[function(require,module,exports){
  11986. "use strict";
  11987. var resolveException = require("../lib/resolve-exception")
  11988. , is = require("./is");
  11989. module.exports = function (value/*, options*/) {
  11990. if (is(value)) return value;
  11991. return resolveException(value, "Cannot use %v", arguments[1]);
  11992. };
  11993. },{"../lib/resolve-exception":122,"./is":131}],131:[function(require,module,exports){
  11994. "use strict";
  11995. // ES3 safe
  11996. var _undefined = void 0;
  11997. module.exports = function (value) { return value !== _undefined && value !== null; };
  11998. },{}],132:[function(require,module,exports){
  11999. // Copyright Joyent, Inc. and other Node contributors.
  12000. //
  12001. // Permission is hereby granted, free of charge, to any person obtaining a
  12002. // copy of this software and associated documentation files (the
  12003. // "Software"), to deal in the Software without restriction, including
  12004. // without limitation the rights to use, copy, modify, merge, publish,
  12005. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12006. // persons to whom the Software is furnished to do so, subject to the
  12007. // following conditions:
  12008. //
  12009. // The above copyright notice and this permission notice shall be included
  12010. // in all copies or substantial portions of the Software.
  12011. //
  12012. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12013. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12014. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12015. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12016. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12017. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12018. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12019. 'use strict';
  12020. var punycode = require('punycode');
  12021. var util = require('./util');
  12022. exports.parse = urlParse;
  12023. exports.resolve = urlResolve;
  12024. exports.resolveObject = urlResolveObject;
  12025. exports.format = urlFormat;
  12026. exports.Url = Url;
  12027. function Url() {
  12028. this.protocol = null;
  12029. this.slashes = null;
  12030. this.auth = null;
  12031. this.host = null;
  12032. this.port = null;
  12033. this.hostname = null;
  12034. this.hash = null;
  12035. this.search = null;
  12036. this.query = null;
  12037. this.pathname = null;
  12038. this.path = null;
  12039. this.href = null;
  12040. }
  12041. // Reference: RFC 3986, RFC 1808, RFC 2396
  12042. // define these here so at least they only have to be
  12043. // compiled once on the first module load.
  12044. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  12045. portPattern = /:[0-9]*$/,
  12046. // Special case for a simple path URL
  12047. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  12048. // RFC 2396: characters reserved for delimiting URLs.
  12049. // We actually just auto-escape these.
  12050. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  12051. // RFC 2396: characters not allowed for various reasons.
  12052. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  12053. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  12054. autoEscape = ['\''].concat(unwise),
  12055. // Characters that are never ever allowed in a hostname.
  12056. // Note that any invalid chars are also handled, but these
  12057. // are the ones that are *expected* to be seen, so we fast-path
  12058. // them.
  12059. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  12060. hostEndingChars = ['/', '?', '#'],
  12061. hostnameMaxLen = 255,
  12062. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  12063. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  12064. // protocols that can allow "unsafe" and "unwise" chars.
  12065. unsafeProtocol = {
  12066. 'javascript': true,
  12067. 'javascript:': true
  12068. },
  12069. // protocols that never have a hostname.
  12070. hostlessProtocol = {
  12071. 'javascript': true,
  12072. 'javascript:': true
  12073. },
  12074. // protocols that always contain a // bit.
  12075. slashedProtocol = {
  12076. 'http': true,
  12077. 'https': true,
  12078. 'ftp': true,
  12079. 'gopher': true,
  12080. 'file': true,
  12081. 'http:': true,
  12082. 'https:': true,
  12083. 'ftp:': true,
  12084. 'gopher:': true,
  12085. 'file:': true
  12086. },
  12087. querystring = require('querystring');
  12088. function urlParse(url, parseQueryString, slashesDenoteHost) {
  12089. if (url && util.isObject(url) && url instanceof Url) return url;
  12090. var u = new Url;
  12091. u.parse(url, parseQueryString, slashesDenoteHost);
  12092. return u;
  12093. }
  12094. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  12095. if (!util.isString(url)) {
  12096. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  12097. }
  12098. // Copy chrome, IE, opera backslash-handling behavior.
  12099. // Back slashes before the query string get converted to forward slashes
  12100. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  12101. var queryIndex = url.indexOf('?'),
  12102. splitter =
  12103. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  12104. uSplit = url.split(splitter),
  12105. slashRegex = /\\/g;
  12106. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  12107. url = uSplit.join(splitter);
  12108. var rest = url;
  12109. // trim before proceeding.
  12110. // This is to support parse stuff like " http://foo.com \n"
  12111. rest = rest.trim();
  12112. if (!slashesDenoteHost && url.split('#').length === 1) {
  12113. // Try fast path regexp
  12114. var simplePath = simplePathPattern.exec(rest);
  12115. if (simplePath) {
  12116. this.path = rest;
  12117. this.href = rest;
  12118. this.pathname = simplePath[1];
  12119. if (simplePath[2]) {
  12120. this.search = simplePath[2];
  12121. if (parseQueryString) {
  12122. this.query = querystring.parse(this.search.substr(1));
  12123. } else {
  12124. this.query = this.search.substr(1);
  12125. }
  12126. } else if (parseQueryString) {
  12127. this.search = '';
  12128. this.query = {};
  12129. }
  12130. return this;
  12131. }
  12132. }
  12133. var proto = protocolPattern.exec(rest);
  12134. if (proto) {
  12135. proto = proto[0];
  12136. var lowerProto = proto.toLowerCase();
  12137. this.protocol = lowerProto;
  12138. rest = rest.substr(proto.length);
  12139. }
  12140. // figure out if it's got a host
  12141. // user@server is *always* interpreted as a hostname, and url
  12142. // resolution will treat //foo/bar as host=foo,path=bar because that's
  12143. // how the browser resolves relative URLs.
  12144. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  12145. var slashes = rest.substr(0, 2) === '//';
  12146. if (slashes && !(proto && hostlessProtocol[proto])) {
  12147. rest = rest.substr(2);
  12148. this.slashes = true;
  12149. }
  12150. }
  12151. if (!hostlessProtocol[proto] &&
  12152. (slashes || (proto && !slashedProtocol[proto]))) {
  12153. // there's a hostname.
  12154. // the first instance of /, ?, ;, or # ends the host.
  12155. //
  12156. // If there is an @ in the hostname, then non-host chars *are* allowed
  12157. // to the left of the last @ sign, unless some host-ending character
  12158. // comes *before* the @-sign.
  12159. // URLs are obnoxious.
  12160. //
  12161. // ex:
  12162. // http://a@b@c/ => user:a@b host:c
  12163. // http://a@b?@c => user:a host:c path:/?@c
  12164. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  12165. // Review our test case against browsers more comprehensively.
  12166. // find the first instance of any hostEndingChars
  12167. var hostEnd = -1;
  12168. for (var i = 0; i < hostEndingChars.length; i++) {
  12169. var hec = rest.indexOf(hostEndingChars[i]);
  12170. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  12171. hostEnd = hec;
  12172. }
  12173. // at this point, either we have an explicit point where the
  12174. // auth portion cannot go past, or the last @ char is the decider.
  12175. var auth, atSign;
  12176. if (hostEnd === -1) {
  12177. // atSign can be anywhere.
  12178. atSign = rest.lastIndexOf('@');
  12179. } else {
  12180. // atSign must be in auth portion.
  12181. // http://a@b/c@d => host:b auth:a path:/c@d
  12182. atSign = rest.lastIndexOf('@', hostEnd);
  12183. }
  12184. // Now we have a portion which is definitely the auth.
  12185. // Pull that off.
  12186. if (atSign !== -1) {
  12187. auth = rest.slice(0, atSign);
  12188. rest = rest.slice(atSign + 1);
  12189. this.auth = decodeURIComponent(auth);
  12190. }
  12191. // the host is the remaining to the left of the first non-host char
  12192. hostEnd = -1;
  12193. for (var i = 0; i < nonHostChars.length; i++) {
  12194. var hec = rest.indexOf(nonHostChars[i]);
  12195. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  12196. hostEnd = hec;
  12197. }
  12198. // if we still have not hit it, then the entire thing is a host.
  12199. if (hostEnd === -1)
  12200. hostEnd = rest.length;
  12201. this.host = rest.slice(0, hostEnd);
  12202. rest = rest.slice(hostEnd);
  12203. // pull out port.
  12204. this.parseHost();
  12205. // we've indicated that there is a hostname,
  12206. // so even if it's empty, it has to be present.
  12207. this.hostname = this.hostname || '';
  12208. // if hostname begins with [ and ends with ]
  12209. // assume that it's an IPv6 address.
  12210. var ipv6Hostname = this.hostname[0] === '[' &&
  12211. this.hostname[this.hostname.length - 1] === ']';
  12212. // validate a little.
  12213. if (!ipv6Hostname) {
  12214. var hostparts = this.hostname.split(/\./);
  12215. for (var i = 0, l = hostparts.length; i < l; i++) {
  12216. var part = hostparts[i];
  12217. if (!part) continue;
  12218. if (!part.match(hostnamePartPattern)) {
  12219. var newpart = '';
  12220. for (var j = 0, k = part.length; j < k; j++) {
  12221. if (part.charCodeAt(j) > 127) {
  12222. // we replace non-ASCII char with a temporary placeholder
  12223. // we need this to make sure size of hostname is not
  12224. // broken by replacing non-ASCII by nothing
  12225. newpart += 'x';
  12226. } else {
  12227. newpart += part[j];
  12228. }
  12229. }
  12230. // we test again with ASCII char only
  12231. if (!newpart.match(hostnamePartPattern)) {
  12232. var validParts = hostparts.slice(0, i);
  12233. var notHost = hostparts.slice(i + 1);
  12234. var bit = part.match(hostnamePartStart);
  12235. if (bit) {
  12236. validParts.push(bit[1]);
  12237. notHost.unshift(bit[2]);
  12238. }
  12239. if (notHost.length) {
  12240. rest = '/' + notHost.join('.') + rest;
  12241. }
  12242. this.hostname = validParts.join('.');
  12243. break;
  12244. }
  12245. }
  12246. }
  12247. }
  12248. if (this.hostname.length > hostnameMaxLen) {
  12249. this.hostname = '';
  12250. } else {
  12251. // hostnames are always lower case.
  12252. this.hostname = this.hostname.toLowerCase();
  12253. }
  12254. if (!ipv6Hostname) {
  12255. // IDNA Support: Returns a punycoded representation of "domain".
  12256. // It only converts parts of the domain name that
  12257. // have non-ASCII characters, i.e. it doesn't matter if
  12258. // you call it with a domain that already is ASCII-only.
  12259. this.hostname = punycode.toASCII(this.hostname);
  12260. }
  12261. var p = this.port ? ':' + this.port : '';
  12262. var h = this.hostname || '';
  12263. this.host = h + p;
  12264. this.href += this.host;
  12265. // strip [ and ] from the hostname
  12266. // the host field still retains them, though
  12267. if (ipv6Hostname) {
  12268. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  12269. if (rest[0] !== '/') {
  12270. rest = '/' + rest;
  12271. }
  12272. }
  12273. }
  12274. // now rest is set to the post-host stuff.
  12275. // chop off any delim chars.
  12276. if (!unsafeProtocol[lowerProto]) {
  12277. // First, make 100% sure that any "autoEscape" chars get
  12278. // escaped, even if encodeURIComponent doesn't think they
  12279. // need to be.
  12280. for (var i = 0, l = autoEscape.length; i < l; i++) {
  12281. var ae = autoEscape[i];
  12282. if (rest.indexOf(ae) === -1)
  12283. continue;
  12284. var esc = encodeURIComponent(ae);
  12285. if (esc === ae) {
  12286. esc = escape(ae);
  12287. }
  12288. rest = rest.split(ae).join(esc);
  12289. }
  12290. }
  12291. // chop off from the tail first.
  12292. var hash = rest.indexOf('#');
  12293. if (hash !== -1) {
  12294. // got a fragment string.
  12295. this.hash = rest.substr(hash);
  12296. rest = rest.slice(0, hash);
  12297. }
  12298. var qm = rest.indexOf('?');
  12299. if (qm !== -1) {
  12300. this.search = rest.substr(qm);
  12301. this.query = rest.substr(qm + 1);
  12302. if (parseQueryString) {
  12303. this.query = querystring.parse(this.query);
  12304. }
  12305. rest = rest.slice(0, qm);
  12306. } else if (parseQueryString) {
  12307. // no query string, but parseQueryString still requested
  12308. this.search = '';
  12309. this.query = {};
  12310. }
  12311. if (rest) this.pathname = rest;
  12312. if (slashedProtocol[lowerProto] &&
  12313. this.hostname && !this.pathname) {
  12314. this.pathname = '/';
  12315. }
  12316. //to support http.request
  12317. if (this.pathname || this.search) {
  12318. var p = this.pathname || '';
  12319. var s = this.search || '';
  12320. this.path = p + s;
  12321. }
  12322. // finally, reconstruct the href based on what has been validated.
  12323. this.href = this.format();
  12324. return this;
  12325. };
  12326. // format a parsed object into a url string
  12327. function urlFormat(obj) {
  12328. // ensure it's an object, and not a string url.
  12329. // If it's an obj, this is a no-op.
  12330. // this way, you can call url_format() on strings
  12331. // to clean up potentially wonky urls.
  12332. if (util.isString(obj)) obj = urlParse(obj);
  12333. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  12334. return obj.format();
  12335. }
  12336. Url.prototype.format = function() {
  12337. var auth = this.auth || '';
  12338. if (auth) {
  12339. auth = encodeURIComponent(auth);
  12340. auth = auth.replace(/%3A/i, ':');
  12341. auth += '@';
  12342. }
  12343. var protocol = this.protocol || '',
  12344. pathname = this.pathname || '',
  12345. hash = this.hash || '',
  12346. host = false,
  12347. query = '';
  12348. if (this.host) {
  12349. host = auth + this.host;
  12350. } else if (this.hostname) {
  12351. host = auth + (this.hostname.indexOf(':') === -1 ?
  12352. this.hostname :
  12353. '[' + this.hostname + ']');
  12354. if (this.port) {
  12355. host += ':' + this.port;
  12356. }
  12357. }
  12358. if (this.query &&
  12359. util.isObject(this.query) &&
  12360. Object.keys(this.query).length) {
  12361. query = querystring.stringify(this.query);
  12362. }
  12363. var search = this.search || (query && ('?' + query)) || '';
  12364. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  12365. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  12366. // unless they had them to begin with.
  12367. if (this.slashes ||
  12368. (!protocol || slashedProtocol[protocol]) && host !== false) {
  12369. host = '//' + (host || '');
  12370. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  12371. } else if (!host) {
  12372. host = '';
  12373. }
  12374. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  12375. if (search && search.charAt(0) !== '?') search = '?' + search;
  12376. pathname = pathname.replace(/[?#]/g, function(match) {
  12377. return encodeURIComponent(match);
  12378. });
  12379. search = search.replace('#', '%23');
  12380. return protocol + host + pathname + search + hash;
  12381. };
  12382. function urlResolve(source, relative) {
  12383. return urlParse(source, false, true).resolve(relative);
  12384. }
  12385. Url.prototype.resolve = function(relative) {
  12386. return this.resolveObject(urlParse(relative, false, true)).format();
  12387. };
  12388. function urlResolveObject(source, relative) {
  12389. if (!source) return relative;
  12390. return urlParse(source, false, true).resolveObject(relative);
  12391. }
  12392. Url.prototype.resolveObject = function(relative) {
  12393. if (util.isString(relative)) {
  12394. var rel = new Url();
  12395. rel.parse(relative, false, true);
  12396. relative = rel;
  12397. }
  12398. var result = new Url();
  12399. var tkeys = Object.keys(this);
  12400. for (var tk = 0; tk < tkeys.length; tk++) {
  12401. var tkey = tkeys[tk];
  12402. result[tkey] = this[tkey];
  12403. }
  12404. // hash is always overridden, no matter what.
  12405. // even href="" will remove it.
  12406. result.hash = relative.hash;
  12407. // if the relative url is empty, then there's nothing left to do here.
  12408. if (relative.href === '') {
  12409. result.href = result.format();
  12410. return result;
  12411. }
  12412. // hrefs like //foo/bar always cut to the protocol.
  12413. if (relative.slashes && !relative.protocol) {
  12414. // take everything except the protocol from relative
  12415. var rkeys = Object.keys(relative);
  12416. for (var rk = 0; rk < rkeys.length; rk++) {
  12417. var rkey = rkeys[rk];
  12418. if (rkey !== 'protocol')
  12419. result[rkey] = relative[rkey];
  12420. }
  12421. //urlParse appends trailing / to urls like http://www.example.com
  12422. if (slashedProtocol[result.protocol] &&
  12423. result.hostname && !result.pathname) {
  12424. result.path = result.pathname = '/';
  12425. }
  12426. result.href = result.format();
  12427. return result;
  12428. }
  12429. if (relative.protocol && relative.protocol !== result.protocol) {
  12430. // if it's a known url protocol, then changing
  12431. // the protocol does weird things
  12432. // first, if it's not file:, then we MUST have a host,
  12433. // and if there was a path
  12434. // to begin with, then we MUST have a path.
  12435. // if it is file:, then the host is dropped,
  12436. // because that's known to be hostless.
  12437. // anything else is assumed to be absolute.
  12438. if (!slashedProtocol[relative.protocol]) {
  12439. var keys = Object.keys(relative);
  12440. for (var v = 0; v < keys.length; v++) {
  12441. var k = keys[v];
  12442. result[k] = relative[k];
  12443. }
  12444. result.href = result.format();
  12445. return result;
  12446. }
  12447. result.protocol = relative.protocol;
  12448. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  12449. var relPath = (relative.pathname || '').split('/');
  12450. while (relPath.length && !(relative.host = relPath.shift()));
  12451. if (!relative.host) relative.host = '';
  12452. if (!relative.hostname) relative.hostname = '';
  12453. if (relPath[0] !== '') relPath.unshift('');
  12454. if (relPath.length < 2) relPath.unshift('');
  12455. result.pathname = relPath.join('/');
  12456. } else {
  12457. result.pathname = relative.pathname;
  12458. }
  12459. result.search = relative.search;
  12460. result.query = relative.query;
  12461. result.host = relative.host || '';
  12462. result.auth = relative.auth;
  12463. result.hostname = relative.hostname || relative.host;
  12464. result.port = relative.port;
  12465. // to support http.request
  12466. if (result.pathname || result.search) {
  12467. var p = result.pathname || '';
  12468. var s = result.search || '';
  12469. result.path = p + s;
  12470. }
  12471. result.slashes = result.slashes || relative.slashes;
  12472. result.href = result.format();
  12473. return result;
  12474. }
  12475. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  12476. isRelAbs = (
  12477. relative.host ||
  12478. relative.pathname && relative.pathname.charAt(0) === '/'
  12479. ),
  12480. mustEndAbs = (isRelAbs || isSourceAbs ||
  12481. (result.host && relative.pathname)),
  12482. removeAllDots = mustEndAbs,
  12483. srcPath = result.pathname && result.pathname.split('/') || [],
  12484. relPath = relative.pathname && relative.pathname.split('/') || [],
  12485. psychotic = result.protocol && !slashedProtocol[result.protocol];
  12486. // if the url is a non-slashed url, then relative
  12487. // links like ../.. should be able
  12488. // to crawl up to the hostname, as well. This is strange.
  12489. // result.protocol has already been set by now.
  12490. // Later on, put the first path part into the host field.
  12491. if (psychotic) {
  12492. result.hostname = '';
  12493. result.port = null;
  12494. if (result.host) {
  12495. if (srcPath[0] === '') srcPath[0] = result.host;
  12496. else srcPath.unshift(result.host);
  12497. }
  12498. result.host = '';
  12499. if (relative.protocol) {
  12500. relative.hostname = null;
  12501. relative.port = null;
  12502. if (relative.host) {
  12503. if (relPath[0] === '') relPath[0] = relative.host;
  12504. else relPath.unshift(relative.host);
  12505. }
  12506. relative.host = null;
  12507. }
  12508. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  12509. }
  12510. if (isRelAbs) {
  12511. // it's absolute.
  12512. result.host = (relative.host || relative.host === '') ?
  12513. relative.host : result.host;
  12514. result.hostname = (relative.hostname || relative.hostname === '') ?
  12515. relative.hostname : result.hostname;
  12516. result.search = relative.search;
  12517. result.query = relative.query;
  12518. srcPath = relPath;
  12519. // fall through to the dot-handling below.
  12520. } else if (relPath.length) {
  12521. // it's relative
  12522. // throw away the existing file, and take the new path instead.
  12523. if (!srcPath) srcPath = [];
  12524. srcPath.pop();
  12525. srcPath = srcPath.concat(relPath);
  12526. result.search = relative.search;
  12527. result.query = relative.query;
  12528. } else if (!util.isNullOrUndefined(relative.search)) {
  12529. // just pull out the search.
  12530. // like href='?foo'.
  12531. // Put this after the other two cases because it simplifies the booleans
  12532. if (psychotic) {
  12533. result.hostname = result.host = srcPath.shift();
  12534. //occationaly the auth can get stuck only in host
  12535. //this especially happens in cases like
  12536. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  12537. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  12538. result.host.split('@') : false;
  12539. if (authInHost) {
  12540. result.auth = authInHost.shift();
  12541. result.host = result.hostname = authInHost.shift();
  12542. }
  12543. }
  12544. result.search = relative.search;
  12545. result.query = relative.query;
  12546. //to support http.request
  12547. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  12548. result.path = (result.pathname ? result.pathname : '') +
  12549. (result.search ? result.search : '');
  12550. }
  12551. result.href = result.format();
  12552. return result;
  12553. }
  12554. if (!srcPath.length) {
  12555. // no path at all. easy.
  12556. // we've already handled the other stuff above.
  12557. result.pathname = null;
  12558. //to support http.request
  12559. if (result.search) {
  12560. result.path = '/' + result.search;
  12561. } else {
  12562. result.path = null;
  12563. }
  12564. result.href = result.format();
  12565. return result;
  12566. }
  12567. // if a url ENDs in . or .., then it must get a trailing slash.
  12568. // however, if it ends in anything else non-slashy,
  12569. // then it must NOT get a trailing slash.
  12570. var last = srcPath.slice(-1)[0];
  12571. var hasTrailingSlash = (
  12572. (result.host || relative.host || srcPath.length > 1) &&
  12573. (last === '.' || last === '..') || last === '');
  12574. // strip single dots, resolve double dots to parent dir
  12575. // if the path tries to go above the root, `up` ends up > 0
  12576. var up = 0;
  12577. for (var i = srcPath.length; i >= 0; i--) {
  12578. last = srcPath[i];
  12579. if (last === '.') {
  12580. srcPath.splice(i, 1);
  12581. } else if (last === '..') {
  12582. srcPath.splice(i, 1);
  12583. up++;
  12584. } else if (up) {
  12585. srcPath.splice(i, 1);
  12586. up--;
  12587. }
  12588. }
  12589. // if the path is allowed to go above the root, restore leading ..s
  12590. if (!mustEndAbs && !removeAllDots) {
  12591. for (; up--; up) {
  12592. srcPath.unshift('..');
  12593. }
  12594. }
  12595. if (mustEndAbs && srcPath[0] !== '' &&
  12596. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  12597. srcPath.unshift('');
  12598. }
  12599. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  12600. srcPath.push('');
  12601. }
  12602. var isAbsolute = srcPath[0] === '' ||
  12603. (srcPath[0] && srcPath[0].charAt(0) === '/');
  12604. // put the host back
  12605. if (psychotic) {
  12606. result.hostname = result.host = isAbsolute ? '' :
  12607. srcPath.length ? srcPath.shift() : '';
  12608. //occationaly the auth can get stuck only in host
  12609. //this especially happens in cases like
  12610. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  12611. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  12612. result.host.split('@') : false;
  12613. if (authInHost) {
  12614. result.auth = authInHost.shift();
  12615. result.host = result.hostname = authInHost.shift();
  12616. }
  12617. }
  12618. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  12619. if (mustEndAbs && !isAbsolute) {
  12620. srcPath.unshift('');
  12621. }
  12622. if (!srcPath.length) {
  12623. result.pathname = null;
  12624. result.path = null;
  12625. } else {
  12626. result.pathname = srcPath.join('/');
  12627. }
  12628. //to support request.http
  12629. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  12630. result.path = (result.pathname ? result.pathname : '') +
  12631. (result.search ? result.search : '');
  12632. }
  12633. result.auth = relative.auth || result.auth;
  12634. result.slashes = result.slashes || relative.slashes;
  12635. result.href = result.format();
  12636. return result;
  12637. };
  12638. Url.prototype.parseHost = function() {
  12639. var host = this.host;
  12640. var port = portPattern.exec(host);
  12641. if (port) {
  12642. port = port[0];
  12643. if (port !== ':') {
  12644. this.port = port.substr(1);
  12645. }
  12646. host = host.substr(0, host.length - port.length);
  12647. }
  12648. if (host) this.hostname = host;
  12649. };
  12650. },{"./util":133,"punycode":101,"querystring":104}],133:[function(require,module,exports){
  12651. 'use strict';
  12652. module.exports = {
  12653. isString: function(arg) {
  12654. return typeof(arg) === 'string';
  12655. },
  12656. isObject: function(arg) {
  12657. return typeof(arg) === 'object' && arg !== null;
  12658. },
  12659. isNull: function(arg) {
  12660. return arg === null;
  12661. },
  12662. isNullOrUndefined: function(arg) {
  12663. return arg == null;
  12664. }
  12665. };
  12666. },{}],134:[function(require,module,exports){
  12667. (function (global){
  12668. /**
  12669. * Module exports.
  12670. */
  12671. module.exports = deprecate;
  12672. /**
  12673. * Mark that a method should not be used.
  12674. * Returns a modified function which warns once by default.
  12675. *
  12676. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  12677. *
  12678. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  12679. * will throw an Error when invoked.
  12680. *
  12681. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  12682. * will invoke `console.trace()` instead of `console.error()`.
  12683. *
  12684. * @param {Function} fn - the function to deprecate
  12685. * @param {String} msg - the string to print to the console when `fn` is invoked
  12686. * @returns {Function} a new "deprecated" version of `fn`
  12687. * @api public
  12688. */
  12689. function deprecate (fn, msg) {
  12690. if (config('noDeprecation')) {
  12691. return fn;
  12692. }
  12693. var warned = false;
  12694. function deprecated() {
  12695. if (!warned) {
  12696. if (config('throwDeprecation')) {
  12697. throw new Error(msg);
  12698. } else if (config('traceDeprecation')) {
  12699. console.trace(msg);
  12700. } else {
  12701. console.warn(msg);
  12702. }
  12703. warned = true;
  12704. }
  12705. return fn.apply(this, arguments);
  12706. }
  12707. return deprecated;
  12708. }
  12709. /**
  12710. * Checks `localStorage` for boolean values for the given `name`.
  12711. *
  12712. * @param {String} name
  12713. * @returns {Boolean}
  12714. * @api private
  12715. */
  12716. function config (name) {
  12717. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  12718. try {
  12719. if (!global.localStorage) return false;
  12720. } catch (_) {
  12721. return false;
  12722. }
  12723. var val = global.localStorage[name];
  12724. if (null == val) return false;
  12725. return String(val).toLowerCase() === 'true';
  12726. }
  12727. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12728. },{}],135:[function(require,module,exports){
  12729. module.exports = function isBuffer(arg) {
  12730. return arg && typeof arg === 'object'
  12731. && typeof arg.copy === 'function'
  12732. && typeof arg.fill === 'function'
  12733. && typeof arg.readUInt8 === 'function';
  12734. }
  12735. },{}],136:[function(require,module,exports){
  12736. (function (process,global){
  12737. // Copyright Joyent, Inc. and other Node contributors.
  12738. //
  12739. // Permission is hereby granted, free of charge, to any person obtaining a
  12740. // copy of this software and associated documentation files (the
  12741. // "Software"), to deal in the Software without restriction, including
  12742. // without limitation the rights to use, copy, modify, merge, publish,
  12743. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12744. // persons to whom the Software is furnished to do so, subject to the
  12745. // following conditions:
  12746. //
  12747. // The above copyright notice and this permission notice shall be included
  12748. // in all copies or substantial portions of the Software.
  12749. //
  12750. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12751. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12752. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12753. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12754. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12755. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12756. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12757. var formatRegExp = /%[sdj%]/g;
  12758. exports.format = function(f) {
  12759. if (!isString(f)) {
  12760. var objects = [];
  12761. for (var i = 0; i < arguments.length; i++) {
  12762. objects.push(inspect(arguments[i]));
  12763. }
  12764. return objects.join(' ');
  12765. }
  12766. var i = 1;
  12767. var args = arguments;
  12768. var len = args.length;
  12769. var str = String(f).replace(formatRegExp, function(x) {
  12770. if (x === '%%') return '%';
  12771. if (i >= len) return x;
  12772. switch (x) {
  12773. case '%s': return String(args[i++]);
  12774. case '%d': return Number(args[i++]);
  12775. case '%j':
  12776. try {
  12777. return JSON.stringify(args[i++]);
  12778. } catch (_) {
  12779. return '[Circular]';
  12780. }
  12781. default:
  12782. return x;
  12783. }
  12784. });
  12785. for (var x = args[i]; i < len; x = args[++i]) {
  12786. if (isNull(x) || !isObject(x)) {
  12787. str += ' ' + x;
  12788. } else {
  12789. str += ' ' + inspect(x);
  12790. }
  12791. }
  12792. return str;
  12793. };
  12794. // Mark that a method should not be used.
  12795. // Returns a modified function which warns once by default.
  12796. // If --no-deprecation is set, then it is a no-op.
  12797. exports.deprecate = function(fn, msg) {
  12798. // Allow for deprecating things in the process of starting up.
  12799. if (isUndefined(global.process)) {
  12800. return function() {
  12801. return exports.deprecate(fn, msg).apply(this, arguments);
  12802. };
  12803. }
  12804. if (process.noDeprecation === true) {
  12805. return fn;
  12806. }
  12807. var warned = false;
  12808. function deprecated() {
  12809. if (!warned) {
  12810. if (process.throwDeprecation) {
  12811. throw new Error(msg);
  12812. } else if (process.traceDeprecation) {
  12813. console.trace(msg);
  12814. } else {
  12815. console.error(msg);
  12816. }
  12817. warned = true;
  12818. }
  12819. return fn.apply(this, arguments);
  12820. }
  12821. return deprecated;
  12822. };
  12823. var debugs = {};
  12824. var debugEnviron;
  12825. exports.debuglog = function(set) {
  12826. if (isUndefined(debugEnviron))
  12827. debugEnviron = process.env.NODE_DEBUG || '';
  12828. set = set.toUpperCase();
  12829. if (!debugs[set]) {
  12830. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  12831. var pid = process.pid;
  12832. debugs[set] = function() {
  12833. var msg = exports.format.apply(exports, arguments);
  12834. console.error('%s %d: %s', set, pid, msg);
  12835. };
  12836. } else {
  12837. debugs[set] = function() {};
  12838. }
  12839. }
  12840. return debugs[set];
  12841. };
  12842. /**
  12843. * Echos the value of a value. Trys to print the value out
  12844. * in the best way possible given the different types.
  12845. *
  12846. * @param {Object} obj The object to print out.
  12847. * @param {Object} opts Optional options object that alters the output.
  12848. */
  12849. /* legacy: obj, showHidden, depth, colors*/
  12850. function inspect(obj, opts) {
  12851. // default options
  12852. var ctx = {
  12853. seen: [],
  12854. stylize: stylizeNoColor
  12855. };
  12856. // legacy...
  12857. if (arguments.length >= 3) ctx.depth = arguments[2];
  12858. if (arguments.length >= 4) ctx.colors = arguments[3];
  12859. if (isBoolean(opts)) {
  12860. // legacy...
  12861. ctx.showHidden = opts;
  12862. } else if (opts) {
  12863. // got an "options" object
  12864. exports._extend(ctx, opts);
  12865. }
  12866. // set default options
  12867. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  12868. if (isUndefined(ctx.depth)) ctx.depth = 2;
  12869. if (isUndefined(ctx.colors)) ctx.colors = false;
  12870. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  12871. if (ctx.colors) ctx.stylize = stylizeWithColor;
  12872. return formatValue(ctx, obj, ctx.depth);
  12873. }
  12874. exports.inspect = inspect;
  12875. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  12876. inspect.colors = {
  12877. 'bold' : [1, 22],
  12878. 'italic' : [3, 23],
  12879. 'underline' : [4, 24],
  12880. 'inverse' : [7, 27],
  12881. 'white' : [37, 39],
  12882. 'grey' : [90, 39],
  12883. 'black' : [30, 39],
  12884. 'blue' : [34, 39],
  12885. 'cyan' : [36, 39],
  12886. 'green' : [32, 39],
  12887. 'magenta' : [35, 39],
  12888. 'red' : [31, 39],
  12889. 'yellow' : [33, 39]
  12890. };
  12891. // Don't use 'blue' not visible on cmd.exe
  12892. inspect.styles = {
  12893. 'special': 'cyan',
  12894. 'number': 'yellow',
  12895. 'boolean': 'yellow',
  12896. 'undefined': 'grey',
  12897. 'null': 'bold',
  12898. 'string': 'green',
  12899. 'date': 'magenta',
  12900. // "name": intentionally not styling
  12901. 'regexp': 'red'
  12902. };
  12903. function stylizeWithColor(str, styleType) {
  12904. var style = inspect.styles[styleType];
  12905. if (style) {
  12906. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  12907. '\u001b[' + inspect.colors[style][1] + 'm';
  12908. } else {
  12909. return str;
  12910. }
  12911. }
  12912. function stylizeNoColor(str, styleType) {
  12913. return str;
  12914. }
  12915. function arrayToHash(array) {
  12916. var hash = {};
  12917. array.forEach(function(val, idx) {
  12918. hash[val] = true;
  12919. });
  12920. return hash;
  12921. }
  12922. function formatValue(ctx, value, recurseTimes) {
  12923. // Provide a hook for user-specified inspect functions.
  12924. // Check that value is an object with an inspect function on it
  12925. if (ctx.customInspect &&
  12926. value &&
  12927. isFunction(value.inspect) &&
  12928. // Filter out the util module, it's inspect function is special
  12929. value.inspect !== exports.inspect &&
  12930. // Also filter out any prototype objects using the circular check.
  12931. !(value.constructor && value.constructor.prototype === value)) {
  12932. var ret = value.inspect(recurseTimes, ctx);
  12933. if (!isString(ret)) {
  12934. ret = formatValue(ctx, ret, recurseTimes);
  12935. }
  12936. return ret;
  12937. }
  12938. // Primitive types cannot have properties
  12939. var primitive = formatPrimitive(ctx, value);
  12940. if (primitive) {
  12941. return primitive;
  12942. }
  12943. // Look up the keys of the object.
  12944. var keys = Object.keys(value);
  12945. var visibleKeys = arrayToHash(keys);
  12946. if (ctx.showHidden) {
  12947. keys = Object.getOwnPropertyNames(value);
  12948. }
  12949. // IE doesn't make error fields non-enumerable
  12950. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  12951. if (isError(value)
  12952. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  12953. return formatError(value);
  12954. }
  12955. // Some type of object without properties can be shortcutted.
  12956. if (keys.length === 0) {
  12957. if (isFunction(value)) {
  12958. var name = value.name ? ': ' + value.name : '';
  12959. return ctx.stylize('[Function' + name + ']', 'special');
  12960. }
  12961. if (isRegExp(value)) {
  12962. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12963. }
  12964. if (isDate(value)) {
  12965. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  12966. }
  12967. if (isError(value)) {
  12968. return formatError(value);
  12969. }
  12970. }
  12971. var base = '', array = false, braces = ['{', '}'];
  12972. // Make Array say that they are Array
  12973. if (isArray(value)) {
  12974. array = true;
  12975. braces = ['[', ']'];
  12976. }
  12977. // Make functions say that they are functions
  12978. if (isFunction(value)) {
  12979. var n = value.name ? ': ' + value.name : '';
  12980. base = ' [Function' + n + ']';
  12981. }
  12982. // Make RegExps say that they are RegExps
  12983. if (isRegExp(value)) {
  12984. base = ' ' + RegExp.prototype.toString.call(value);
  12985. }
  12986. // Make dates with properties first say the date
  12987. if (isDate(value)) {
  12988. base = ' ' + Date.prototype.toUTCString.call(value);
  12989. }
  12990. // Make error with message first say the error
  12991. if (isError(value)) {
  12992. base = ' ' + formatError(value);
  12993. }
  12994. if (keys.length === 0 && (!array || value.length == 0)) {
  12995. return braces[0] + base + braces[1];
  12996. }
  12997. if (recurseTimes < 0) {
  12998. if (isRegExp(value)) {
  12999. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13000. } else {
  13001. return ctx.stylize('[Object]', 'special');
  13002. }
  13003. }
  13004. ctx.seen.push(value);
  13005. var output;
  13006. if (array) {
  13007. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  13008. } else {
  13009. output = keys.map(function(key) {
  13010. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  13011. });
  13012. }
  13013. ctx.seen.pop();
  13014. return reduceToSingleString(output, base, braces);
  13015. }
  13016. function formatPrimitive(ctx, value) {
  13017. if (isUndefined(value))
  13018. return ctx.stylize('undefined', 'undefined');
  13019. if (isString(value)) {
  13020. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  13021. .replace(/'/g, "\\'")
  13022. .replace(/\\"/g, '"') + '\'';
  13023. return ctx.stylize(simple, 'string');
  13024. }
  13025. if (isNumber(value))
  13026. return ctx.stylize('' + value, 'number');
  13027. if (isBoolean(value))
  13028. return ctx.stylize('' + value, 'boolean');
  13029. // For some reason typeof null is "object", so special case here.
  13030. if (isNull(value))
  13031. return ctx.stylize('null', 'null');
  13032. }
  13033. function formatError(value) {
  13034. return '[' + Error.prototype.toString.call(value) + ']';
  13035. }
  13036. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  13037. var output = [];
  13038. for (var i = 0, l = value.length; i < l; ++i) {
  13039. if (hasOwnProperty(value, String(i))) {
  13040. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13041. String(i), true));
  13042. } else {
  13043. output.push('');
  13044. }
  13045. }
  13046. keys.forEach(function(key) {
  13047. if (!key.match(/^\d+$/)) {
  13048. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13049. key, true));
  13050. }
  13051. });
  13052. return output;
  13053. }
  13054. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  13055. var name, str, desc;
  13056. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  13057. if (desc.get) {
  13058. if (desc.set) {
  13059. str = ctx.stylize('[Getter/Setter]', 'special');
  13060. } else {
  13061. str = ctx.stylize('[Getter]', 'special');
  13062. }
  13063. } else {
  13064. if (desc.set) {
  13065. str = ctx.stylize('[Setter]', 'special');
  13066. }
  13067. }
  13068. if (!hasOwnProperty(visibleKeys, key)) {
  13069. name = '[' + key + ']';
  13070. }
  13071. if (!str) {
  13072. if (ctx.seen.indexOf(desc.value) < 0) {
  13073. if (isNull(recurseTimes)) {
  13074. str = formatValue(ctx, desc.value, null);
  13075. } else {
  13076. str = formatValue(ctx, desc.value, recurseTimes - 1);
  13077. }
  13078. if (str.indexOf('\n') > -1) {
  13079. if (array) {
  13080. str = str.split('\n').map(function(line) {
  13081. return ' ' + line;
  13082. }).join('\n').substr(2);
  13083. } else {
  13084. str = '\n' + str.split('\n').map(function(line) {
  13085. return ' ' + line;
  13086. }).join('\n');
  13087. }
  13088. }
  13089. } else {
  13090. str = ctx.stylize('[Circular]', 'special');
  13091. }
  13092. }
  13093. if (isUndefined(name)) {
  13094. if (array && key.match(/^\d+$/)) {
  13095. return str;
  13096. }
  13097. name = JSON.stringify('' + key);
  13098. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  13099. name = name.substr(1, name.length - 2);
  13100. name = ctx.stylize(name, 'name');
  13101. } else {
  13102. name = name.replace(/'/g, "\\'")
  13103. .replace(/\\"/g, '"')
  13104. .replace(/(^"|"$)/g, "'");
  13105. name = ctx.stylize(name, 'string');
  13106. }
  13107. }
  13108. return name + ': ' + str;
  13109. }
  13110. function reduceToSingleString(output, base, braces) {
  13111. var numLinesEst = 0;
  13112. var length = output.reduce(function(prev, cur) {
  13113. numLinesEst++;
  13114. if (cur.indexOf('\n') >= 0) numLinesEst++;
  13115. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  13116. }, 0);
  13117. if (length > 60) {
  13118. return braces[0] +
  13119. (base === '' ? '' : base + '\n ') +
  13120. ' ' +
  13121. output.join(',\n ') +
  13122. ' ' +
  13123. braces[1];
  13124. }
  13125. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  13126. }
  13127. // NOTE: These type checking functions intentionally don't use `instanceof`
  13128. // because it is fragile and can be easily faked with `Object.create()`.
  13129. function isArray(ar) {
  13130. return Array.isArray(ar);
  13131. }
  13132. exports.isArray = isArray;
  13133. function isBoolean(arg) {
  13134. return typeof arg === 'boolean';
  13135. }
  13136. exports.isBoolean = isBoolean;
  13137. function isNull(arg) {
  13138. return arg === null;
  13139. }
  13140. exports.isNull = isNull;
  13141. function isNullOrUndefined(arg) {
  13142. return arg == null;
  13143. }
  13144. exports.isNullOrUndefined = isNullOrUndefined;
  13145. function isNumber(arg) {
  13146. return typeof arg === 'number';
  13147. }
  13148. exports.isNumber = isNumber;
  13149. function isString(arg) {
  13150. return typeof arg === 'string';
  13151. }
  13152. exports.isString = isString;
  13153. function isSymbol(arg) {
  13154. return typeof arg === 'symbol';
  13155. }
  13156. exports.isSymbol = isSymbol;
  13157. function isUndefined(arg) {
  13158. return arg === void 0;
  13159. }
  13160. exports.isUndefined = isUndefined;
  13161. function isRegExp(re) {
  13162. return isObject(re) && objectToString(re) === '[object RegExp]';
  13163. }
  13164. exports.isRegExp = isRegExp;
  13165. function isObject(arg) {
  13166. return typeof arg === 'object' && arg !== null;
  13167. }
  13168. exports.isObject = isObject;
  13169. function isDate(d) {
  13170. return isObject(d) && objectToString(d) === '[object Date]';
  13171. }
  13172. exports.isDate = isDate;
  13173. function isError(e) {
  13174. return isObject(e) &&
  13175. (objectToString(e) === '[object Error]' || e instanceof Error);
  13176. }
  13177. exports.isError = isError;
  13178. function isFunction(arg) {
  13179. return typeof arg === 'function';
  13180. }
  13181. exports.isFunction = isFunction;
  13182. function isPrimitive(arg) {
  13183. return arg === null ||
  13184. typeof arg === 'boolean' ||
  13185. typeof arg === 'number' ||
  13186. typeof arg === 'string' ||
  13187. typeof arg === 'symbol' || // ES6 symbol
  13188. typeof arg === 'undefined';
  13189. }
  13190. exports.isPrimitive = isPrimitive;
  13191. exports.isBuffer = require('./support/isBuffer');
  13192. function objectToString(o) {
  13193. return Object.prototype.toString.call(o);
  13194. }
  13195. function pad(n) {
  13196. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  13197. }
  13198. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  13199. 'Oct', 'Nov', 'Dec'];
  13200. // 26 Feb 16:19:34
  13201. function timestamp() {
  13202. var d = new Date();
  13203. var time = [pad(d.getHours()),
  13204. pad(d.getMinutes()),
  13205. pad(d.getSeconds())].join(':');
  13206. return [d.getDate(), months[d.getMonth()], time].join(' ');
  13207. }
  13208. // log is just a thin wrapper to console.log that prepends a timestamp
  13209. exports.log = function() {
  13210. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  13211. };
  13212. /**
  13213. * Inherit the prototype methods from one constructor into another.
  13214. *
  13215. * The Function.prototype.inherits from lang.js rewritten as a standalone
  13216. * function (not on Function.prototype). NOTE: If this file is to be loaded
  13217. * during bootstrapping this function needs to be rewritten using some native
  13218. * functions as prototype setup using normal JavaScript does not work as
  13219. * expected during bootstrapping (see mirror.js in r114903).
  13220. *
  13221. * @param {function} ctor Constructor function which needs to inherit the
  13222. * prototype.
  13223. * @param {function} superCtor Constructor function to inherit prototype from.
  13224. */
  13225. exports.inherits = require('inherits');
  13226. exports._extend = function(origin, add) {
  13227. // Don't do anything if add isn't an object
  13228. if (!add || !isObject(add)) return origin;
  13229. var keys = Object.keys(add);
  13230. var i = keys.length;
  13231. while (i--) {
  13232. origin[keys[i]] = add[keys[i]];
  13233. }
  13234. return origin;
  13235. };
  13236. function hasOwnProperty(obj, prop) {
  13237. return Object.prototype.hasOwnProperty.call(obj, prop);
  13238. }
  13239. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13240. },{"./support/isBuffer":135,"_process":100,"inherits":88}],137:[function(require,module,exports){
  13241. (function (process,global){
  13242. 'use strict'
  13243. var Transform = require('readable-stream').Transform
  13244. var duplexify = require('duplexify')
  13245. var WS = require('ws')
  13246. var Buffer = require('safe-buffer').Buffer
  13247. module.exports = WebSocketStream
  13248. function buildProxy (options, socketWrite, socketEnd) {
  13249. var proxy = new Transform({
  13250. objectMode: options.objectMode
  13251. })
  13252. proxy._write = socketWrite
  13253. proxy._flush = socketEnd
  13254. return proxy
  13255. }
  13256. function WebSocketStream(target, protocols, options) {
  13257. var stream, socket
  13258. var isBrowser = process.title === 'browser'
  13259. var isNative = !!global.WebSocket
  13260. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  13261. if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
  13262. // accept the "options" Object as the 2nd argument
  13263. options = protocols
  13264. protocols = null
  13265. if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
  13266. protocols = options.protocol;
  13267. }
  13268. }
  13269. if (!options) options = {}
  13270. if (options.objectMode === undefined) {
  13271. options.objectMode = !(options.binary === true || options.binary === undefined)
  13272. }
  13273. var proxy = buildProxy(options, socketWrite, socketEnd)
  13274. if (!options.objectMode) {
  13275. proxy._writev = writev
  13276. }
  13277. // browser only: sets the maximum socket buffer size before throttling
  13278. var bufferSize = options.browserBufferSize || 1024 * 512
  13279. // browser only: how long to wait when throttling
  13280. var bufferTimeout = options.browserBufferTimeout || 1000
  13281. // use existing WebSocket object that was passed in
  13282. if (typeof target === 'object') {
  13283. socket = target
  13284. // otherwise make a new one
  13285. } else {
  13286. // special constructor treatment for native websockets in browsers, see
  13287. // https://github.com/maxogden/websocket-stream/issues/82
  13288. if (isNative && isBrowser) {
  13289. socket = new WS(target, protocols)
  13290. } else {
  13291. socket = new WS(target, protocols, options)
  13292. }
  13293. socket.binaryType = 'arraybuffer'
  13294. }
  13295. // was already open when passed in
  13296. if (socket.readyState === socket.OPEN) {
  13297. stream = proxy
  13298. } else {
  13299. stream = duplexify.obj()
  13300. socket.onopen = onopen
  13301. }
  13302. stream.socket = socket
  13303. socket.onclose = onclose
  13304. socket.onerror = onerror
  13305. socket.onmessage = onmessage
  13306. proxy.on('close', destroy)
  13307. var coerceToBuffer = !options.objectMode
  13308. function socketWriteNode(chunk, enc, next) {
  13309. // avoid errors, this never happens unless
  13310. // destroy() is called
  13311. if (socket.readyState !== socket.OPEN) {
  13312. next()
  13313. return
  13314. }
  13315. if (coerceToBuffer && typeof chunk === 'string') {
  13316. chunk = Buffer.from(chunk, 'utf8')
  13317. }
  13318. socket.send(chunk, next)
  13319. }
  13320. function socketWriteBrowser(chunk, enc, next) {
  13321. if (socket.bufferedAmount > bufferSize) {
  13322. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  13323. return
  13324. }
  13325. if (coerceToBuffer && typeof chunk === 'string') {
  13326. chunk = Buffer.from(chunk, 'utf8')
  13327. }
  13328. try {
  13329. socket.send(chunk)
  13330. } catch(err) {
  13331. return next(err)
  13332. }
  13333. next()
  13334. }
  13335. function socketEnd(done) {
  13336. socket.close()
  13337. done()
  13338. }
  13339. function onopen() {
  13340. stream.setReadable(proxy)
  13341. stream.setWritable(proxy)
  13342. stream.emit('connect')
  13343. }
  13344. function onclose() {
  13345. stream.end()
  13346. stream.destroy()
  13347. }
  13348. function onerror(err) {
  13349. stream.destroy(err)
  13350. }
  13351. function onmessage(event) {
  13352. var data = event.data
  13353. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  13354. else data = Buffer.from(data, 'utf8')
  13355. proxy.push(data)
  13356. }
  13357. function destroy() {
  13358. socket.close()
  13359. }
  13360. // this is to be enabled only if objectMode is false
  13361. function writev (chunks, cb) {
  13362. var buffers = new Array(chunks.length)
  13363. for (var i = 0; i < chunks.length; i++) {
  13364. if (typeof chunks[i].chunk === 'string') {
  13365. buffers[i] = Buffer.from(chunks[i], 'utf8')
  13366. } else {
  13367. buffers[i] = chunks[i].chunk
  13368. }
  13369. }
  13370. this._write(Buffer.concat(buffers), 'binary', cb)
  13371. }
  13372. return stream
  13373. }
  13374. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13375. },{"_process":100,"duplexify":19,"readable-stream":116,"safe-buffer":118,"ws":138}],138:[function(require,module,exports){
  13376. var ws = null
  13377. if (typeof WebSocket !== 'undefined') {
  13378. ws = WebSocket
  13379. } else if (typeof MozWebSocket !== 'undefined') {
  13380. ws = MozWebSocket
  13381. } else if (typeof window !== 'undefined') {
  13382. ws = window.WebSocket || window.MozWebSocket
  13383. }
  13384. module.exports = ws
  13385. },{}],139:[function(require,module,exports){
  13386. // Returns a wrapper function that returns a wrapped callback
  13387. // The wrapper function should do some stuff, and return a
  13388. // presumably different callback function.
  13389. // This makes sure that own properties are retained, so that
  13390. // decorations and such are not lost along the way.
  13391. module.exports = wrappy
  13392. function wrappy (fn, cb) {
  13393. if (fn && cb) return wrappy(fn)(cb)
  13394. if (typeof fn !== 'function')
  13395. throw new TypeError('need wrapper function')
  13396. Object.keys(fn).forEach(function (k) {
  13397. wrapper[k] = fn[k]
  13398. })
  13399. return wrapper
  13400. function wrapper() {
  13401. var args = new Array(arguments.length)
  13402. for (var i = 0; i < args.length; i++) {
  13403. args[i] = arguments[i]
  13404. }
  13405. var ret = fn.apply(this, args)
  13406. var cb = args[args.length-1]
  13407. if (typeof ret === 'function' && ret !== cb) {
  13408. Object.keys(cb).forEach(function (k) {
  13409. ret[k] = cb[k]
  13410. })
  13411. }
  13412. return ret
  13413. }
  13414. }
  13415. },{}],140:[function(require,module,exports){
  13416. module.exports = extend
  13417. var hasOwnProperty = Object.prototype.hasOwnProperty;
  13418. function extend() {
  13419. var target = {}
  13420. for (var i = 0; i < arguments.length; i++) {
  13421. var source = arguments[i]
  13422. for (var key in source) {
  13423. if (hasOwnProperty.call(source, key)) {
  13424. target[key] = source[key]
  13425. }
  13426. }
  13427. }
  13428. return target
  13429. }
  13430. },{}]},{},[9])(9)
  13431. });