mqtt.js 398 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599
  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 events = require('events')
  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 setImmediate = global.setImmediate || function (callback) {
  16. // works in node v0.8
  17. process.nextTick(callback)
  18. }
  19. var defaultConnectOptions = {
  20. keepalive: 60,
  21. reschedulePings: true,
  22. protocolId: 'MQTT',
  23. protocolVersion: 4,
  24. reconnectPeriod: 1000,
  25. connectTimeout: 30 * 1000,
  26. clean: true,
  27. resubscribe: true
  28. }
  29. var errors = {
  30. 0: '',
  31. 1: 'Unacceptable protocol version',
  32. 2: 'Identifier rejected',
  33. 3: 'Server unavailable',
  34. 4: 'Bad username or password',
  35. 5: 'Not authorized',
  36. 16: 'No matching subscribers',
  37. 17: 'No subscription existed',
  38. 128: 'Unspecified error',
  39. 129: 'Malformed Packet',
  40. 130: 'Protocol Error',
  41. 131: 'Implementation specific error',
  42. 132: 'Unsupported Protocol Version',
  43. 133: 'Client Identifier not valid',
  44. 134: 'Bad User Name or Password',
  45. 135: 'Not authorized',
  46. 136: 'Server unavailable',
  47. 137: 'Server busy',
  48. 138: 'Banned',
  49. 139: 'Server shutting down',
  50. 140: 'Bad authentication method',
  51. 141: 'Keep Alive timeout',
  52. 142: 'Session taken over',
  53. 143: 'Topic Filter invalid',
  54. 144: 'Topic Name invalid',
  55. 145: 'Packet identifier in use',
  56. 146: 'Packet Identifier not found',
  57. 147: 'Receive Maximum exceeded',
  58. 148: 'Topic Alias invalid',
  59. 149: 'Packet too large',
  60. 150: 'Message rate too high',
  61. 151: 'Quota exceeded',
  62. 152: 'Administrative action',
  63. 153: 'Payload format invalid',
  64. 154: 'Retain not supported',
  65. 155: 'QoS not supported',
  66. 156: 'Use another server',
  67. 157: 'Server moved',
  68. 158: 'Shared Subscriptions not supported',
  69. 159: 'Connection rate exceeded',
  70. 160: 'Maximum connect time',
  71. 161: 'Subscription Identifiers not supported',
  72. 162: 'Wildcard Subscriptions not supported'
  73. }
  74. function defaultId () {
  75. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  76. }
  77. function sendPacket (client, packet, cb) {
  78. client.emit('packetsend', packet)
  79. var result = mqttPacket.writeToStream(packet, client.stream, client.options)
  80. if (!result && cb) {
  81. client.stream.once('drain', cb)
  82. } else if (cb) {
  83. cb()
  84. }
  85. }
  86. function flush (queue) {
  87. if (queue) {
  88. Object.keys(queue).forEach(function (messageId) {
  89. if (typeof queue[messageId] === 'function') {
  90. queue[messageId](new Error('Connection closed'))
  91. delete queue[messageId]
  92. }
  93. })
  94. }
  95. }
  96. function storeAndSend (client, packet, cb, cbStorePut) {
  97. client.outgoingStore.put(packet, function storedPacket (err) {
  98. if (err) {
  99. return cb && cb(err)
  100. }
  101. cbStorePut()
  102. sendPacket(client, packet, cb)
  103. })
  104. }
  105. function nop () {}
  106. /**
  107. * MqttClient constructor
  108. *
  109. * @param {Stream} stream - stream
  110. * @param {Object} [options] - connection options
  111. * (see Connection#connect)
  112. */
  113. function MqttClient (streamBuilder, options) {
  114. var k
  115. var that = this
  116. if (!(this instanceof MqttClient)) {
  117. return new MqttClient(streamBuilder, options)
  118. }
  119. this.options = options || {}
  120. // Defaults
  121. for (k in defaultConnectOptions) {
  122. if (typeof this.options[k] === 'undefined') {
  123. this.options[k] = defaultConnectOptions[k]
  124. } else {
  125. this.options[k] = options[k]
  126. }
  127. }
  128. this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
  129. this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
  130. this.streamBuilder = streamBuilder
  131. // Inflight message storages
  132. this.outgoingStore = options.outgoingStore || new Store()
  133. this.incomingStore = options.incomingStore || new Store()
  134. // Should QoS zero messages be queued when the connection is broken?
  135. this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
  136. // map of subscribed topics to support reconnection
  137. this._resubscribeTopics = {}
  138. // map of a subscribe messageId and a topic
  139. this.messageIdToTopic = {}
  140. // Ping timer, setup in _setupPingTimer
  141. this.pingTimer = null
  142. // Is the client connected?
  143. this.connected = false
  144. // Are we disconnecting?
  145. this.disconnecting = false
  146. // Packet queue
  147. this.queue = []
  148. // connack timer
  149. this.connackTimer = null
  150. // Reconnect timer
  151. this.reconnectTimer = null
  152. // Is processing store?
  153. this._storeProcessing = false
  154. // Packet Ids are put into the store during store processing
  155. this._packetIdsDuringStoreProcessing = {}
  156. /**
  157. * MessageIDs starting with 1
  158. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  159. */
  160. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  161. // Inflight callbacks
  162. this.outgoing = {}
  163. // True if connection is first time.
  164. this._firstConnection = true
  165. // Mark disconnected on stream close
  166. this.on('close', function () {
  167. this.connected = false
  168. clearTimeout(this.connackTimer)
  169. })
  170. // Send queued packets
  171. this.on('connect', function () {
  172. var queue = this.queue
  173. function deliver () {
  174. var entry = queue.shift()
  175. var packet = null
  176. if (!entry) {
  177. return
  178. }
  179. packet = entry.packet
  180. that._sendPacket(
  181. packet,
  182. function (err) {
  183. if (entry.cb) {
  184. entry.cb(err)
  185. }
  186. deliver()
  187. }
  188. )
  189. }
  190. deliver()
  191. })
  192. // Clear ping timer
  193. this.on('close', function () {
  194. if (that.pingTimer !== null) {
  195. that.pingTimer.clear()
  196. that.pingTimer = null
  197. }
  198. })
  199. // Setup reconnect timer on disconnect
  200. this.on('close', this._setupReconnect)
  201. events.EventEmitter.call(this)
  202. this._setupStream()
  203. }
  204. inherits(MqttClient, events.EventEmitter)
  205. /**
  206. * setup the event handlers in the inner stream.
  207. *
  208. * @api private
  209. */
  210. MqttClient.prototype._setupStream = function () {
  211. var connectPacket
  212. var that = this
  213. var writable = new Writable()
  214. var parser = mqttPacket.parser(this.options)
  215. var completeParse = null
  216. var packets = []
  217. this._clearReconnect()
  218. this.stream = this.streamBuilder(this)
  219. parser.on('packet', function (packet) {
  220. packets.push(packet)
  221. })
  222. function nextTickWork () {
  223. process.nextTick(work)
  224. }
  225. function work () {
  226. var packet = packets.shift()
  227. var done = completeParse
  228. if (packet) {
  229. that._handlePacket(packet, nextTickWork)
  230. } else {
  231. completeParse = null
  232. done()
  233. }
  234. }
  235. writable._write = function (buf, enc, done) {
  236. completeParse = done
  237. parser.parse(buf)
  238. work()
  239. }
  240. this.stream.pipe(writable)
  241. // Suppress connection errors
  242. this.stream.on('error', nop)
  243. // Echo stream close
  244. this.stream.on('close', function () {
  245. console.log(`this.stream.on('close'`)
  246. that.emit('close')
  247. })
  248. // Send a connect packet
  249. connectPacket = Object.create(this.options)
  250. connectPacket.cmd = 'connect'
  251. // avoid message queue
  252. sendPacket(this, connectPacket)
  253. // Echo connection errors
  254. parser.on('error', this.emit.bind(this, 'error'))
  255. // auth
  256. if (this.options.properties) {
  257. if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
  258. this.emit('error', new Error('Packet has no Authentication Method'))
  259. return this
  260. }
  261. if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
  262. var authPacket = xtend({cmd: 'auth', reasonCode: 0}, this.options.authPacket)
  263. sendPacket(this, authPacket)
  264. }
  265. }
  266. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  267. this.stream.setMaxListeners(1000)
  268. clearTimeout(this.connackTimer)
  269. this.connackTimer = setTimeout(function () {
  270. that._cleanUp(true)
  271. }, this.options.connectTimeout)
  272. }
  273. MqttClient.prototype._handlePacket = function (packet, done) {
  274. var options = this.options
  275. if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
  276. this.emit('error', new Error('exceeding packets size ' + packet.cmd))
  277. this.end({reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }})
  278. return this
  279. }
  280. this.emit('packetreceive', packet)
  281. switch (packet.cmd) {
  282. case 'publish':
  283. this._handlePublish(packet, done)
  284. break
  285. case 'puback':
  286. case 'pubrec':
  287. case 'pubcomp':
  288. case 'suback':
  289. case 'unsuback':
  290. this._handleAck(packet)
  291. done()
  292. break
  293. case 'pubrel':
  294. this._handlePubrel(packet, done)
  295. break
  296. case 'connack':
  297. this._handleConnack(packet)
  298. done()
  299. break
  300. case 'pingresp':
  301. this._handlePingresp(packet)
  302. done()
  303. break
  304. default:
  305. // do nothing
  306. // maybe we should do an error handling
  307. // or just log it
  308. break
  309. }
  310. }
  311. MqttClient.prototype._checkDisconnecting = function (callback) {
  312. if (this.disconnecting) {
  313. if (callback) {
  314. callback(new Error('client disconnecting'))
  315. } else {
  316. this.emit('error', new Error('client disconnecting'))
  317. }
  318. }
  319. return this.disconnecting
  320. }
  321. /**
  322. * publish - publish <message> to <topic>
  323. *
  324. * @param {String} topic - topic to publish to
  325. * @param {String, Buffer} message - message to publish
  326. * @param {Object} [opts] - publish options, includes:
  327. * {Number} qos - qos level to publish on
  328. * {Boolean} retain - whether or not to retain the message
  329. * {Boolean} dup - whether or not mark a message as duplicate
  330. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  331. * @param {Function} [callback] - function(err){}
  332. * called when publish succeeds or fails
  333. * @returns {MqttClient} this - for chaining
  334. * @api public
  335. *
  336. * @example client.publish('topic', 'message');
  337. * @example
  338. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  339. * @example client.publish('topic', 'message', console.log);
  340. */
  341. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  342. var packet
  343. var options = this.options
  344. // .publish(topic, payload, cb);
  345. if (typeof opts === 'function') {
  346. callback = opts
  347. opts = null
  348. }
  349. // default opts
  350. var defaultOpts = {qos: 0, retain: false, dup: false}
  351. opts = xtend(defaultOpts, opts)
  352. if (this._checkDisconnecting(callback)) {
  353. return this
  354. }
  355. packet = {
  356. cmd: 'publish',
  357. topic: topic,
  358. payload: message,
  359. qos: opts.qos,
  360. retain: opts.retain,
  361. messageId: this._nextId(),
  362. dup: opts.dup
  363. }
  364. if (options.protocolVersion === 5) {
  365. packet.properties = opts.properties
  366. if ((!options.properties && packet.properties && packet.properties.topicAlias) || ((opts.properties && options.properties) &&
  367. ((opts.properties.topicAlias && options.properties.topicAliasMaximum && opts.properties.topicAlias > options.properties.topicAliasMaximum) ||
  368. (!options.properties.topicAliasMaximum && opts.properties.topicAlias)))) {
  369. /*
  370. if we are don`t setup topic alias or
  371. topic alias maximum less than topic alias or
  372. server don`t give topic alias maximum,
  373. we are removing topic alias from packet
  374. */
  375. delete packet.properties.topicAlias
  376. }
  377. }
  378. switch (opts.qos) {
  379. case 1:
  380. case 2:
  381. // Add to callbacks
  382. this.outgoing[packet.messageId] = callback || nop
  383. if (this._storeProcessing) {
  384. this._packetIdsDuringStoreProcessing[packet.messageId] = false
  385. this._storePacket(packet, undefined, opts.cbStorePut)
  386. } else {
  387. this._sendPacket(packet, undefined, opts.cbStorePut)
  388. }
  389. break
  390. default:
  391. if (this._storeProcessing) {
  392. this._storePacket(packet, callback, opts.cbStorePut)
  393. } else {
  394. this._sendPacket(packet, callback, opts.cbStorePut)
  395. }
  396. break
  397. }
  398. return this
  399. }
  400. /**
  401. * subscribe - subscribe to <topic>
  402. *
  403. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  404. * @param {Object} [opts] - optional subscription options, includes:
  405. * {Number} qos - subscribe qos level
  406. * @param {Function} [callback] - function(err, granted){} where:
  407. * {Error} err - subscription error (none at the moment!)
  408. * {Array} granted - array of {topic: 't', qos: 0}
  409. * @returns {MqttClient} this - for chaining
  410. * @api public
  411. * @example client.subscribe('topic');
  412. * @example client.subscribe('topic', {qos: 1});
  413. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  414. * @example client.subscribe('topic', console.log);
  415. */
  416. MqttClient.prototype.subscribe = function () {
  417. var packet
  418. var args = new Array(arguments.length)
  419. for (var i = 0; i < arguments.length; i++) {
  420. args[i] = arguments[i]
  421. }
  422. var subs = []
  423. var obj = args.shift()
  424. var resubscribe = obj.resubscribe
  425. var callback = args.pop() || nop
  426. var opts = args.pop()
  427. var invalidTopic
  428. var that = this
  429. var version = this.options.protocolVersion
  430. delete obj.resubscribe
  431. if (typeof obj === 'string') {
  432. obj = [obj]
  433. }
  434. if (typeof callback !== 'function') {
  435. opts = callback
  436. callback = nop
  437. }
  438. invalidTopic = validations.validateTopics(obj)
  439. if (invalidTopic !== null) {
  440. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  441. return this
  442. }
  443. if (this._checkDisconnecting(callback)) {
  444. return this
  445. }
  446. var defaultOpts = {
  447. qos: 0
  448. }
  449. if (version === 5) {
  450. defaultOpts.nl = false
  451. defaultOpts.rap = false
  452. defaultOpts.rh = 0
  453. }
  454. opts = xtend(defaultOpts, opts)
  455. if (Array.isArray(obj)) {
  456. obj.forEach(function (topic) {
  457. if (!that._resubscribeTopics.hasOwnProperty(topic) ||
  458. that._resubscribeTopics[topic].qos < opts.qos ||
  459. resubscribe) {
  460. var currentOpts = {
  461. topic: topic,
  462. qos: opts.qos
  463. }
  464. if (version === 5) {
  465. currentOpts.nl = opts.nl
  466. currentOpts.rap = opts.rap
  467. currentOpts.rh = opts.rh
  468. }
  469. subs.push(currentOpts)
  470. }
  471. })
  472. } else {
  473. Object
  474. .keys(obj)
  475. .forEach(function (k) {
  476. if (!that._resubscribeTopics.hasOwnProperty(k) ||
  477. that._resubscribeTopics[k].qos < obj[k].qos ||
  478. resubscribe) {
  479. var currentOpts = {
  480. topic: k,
  481. qos: obj[k].qos
  482. }
  483. if (version === 5) {
  484. currentOpts.nl = obj[k].nl
  485. currentOpts.rap = obj[k].rap
  486. currentOpts.rh = obj[k].rh
  487. }
  488. subs.push(currentOpts)
  489. }
  490. })
  491. }
  492. packet = {
  493. cmd: 'subscribe',
  494. subscriptions: subs,
  495. qos: 1,
  496. retain: false,
  497. dup: false,
  498. messageId: this._nextId()
  499. }
  500. if (opts.properties) {
  501. packet.properties = opts.properties
  502. }
  503. if (!subs.length) {
  504. callback(null, [])
  505. return
  506. }
  507. // subscriptions to resubscribe to in case of disconnect
  508. if (this.options.resubscribe) {
  509. var topics = []
  510. subs.forEach(function (sub) {
  511. if (that.options.reconnectPeriod > 0) {
  512. var topic = { qos: sub.qos }
  513. if (version === 5) {
  514. topic.nl = sub.nl || false
  515. topic.rap = sub.rap || false
  516. topic.rh = sub.rh || 0
  517. }
  518. that._resubscribeTopics[sub.topic] = topic
  519. topics.push(sub.topic)
  520. }
  521. })
  522. that.messageIdToTopic[packet.messageId] = topics
  523. }
  524. this.outgoing[packet.messageId] = function (err, packet) {
  525. if (!err) {
  526. var granted = packet.granted
  527. for (var i = 0; i < granted.length; i += 1) {
  528. subs[i].qos = granted[i]
  529. }
  530. }
  531. callback(err, subs)
  532. }
  533. this._sendPacket(packet)
  534. return this
  535. }
  536. /**
  537. * unsubscribe - unsubscribe from topic(s)
  538. *
  539. * @param {String, Array} topic - topics to unsubscribe from
  540. * @param {Object} [opts] - optional subscription options, includes:
  541. * {Object} properties - properties of unsubscribe packet
  542. * @param {Function} [callback] - callback fired on unsuback
  543. * @returns {MqttClient} this - for chaining
  544. * @api public
  545. * @example client.unsubscribe('topic');
  546. * @example client.unsubscribe('topic', console.log);
  547. */
  548. MqttClient.prototype.unsubscribe = function () {
  549. var packet = {
  550. cmd: 'unsubscribe',
  551. qos: 1,
  552. messageId: this._nextId()
  553. }
  554. var that = this
  555. var args = new Array(arguments.length)
  556. for (var i = 0; i < arguments.length; i++) {
  557. args[i] = arguments[i]
  558. }
  559. var topic = args.shift()
  560. var callback = args.pop() || nop
  561. var opts = args.pop()
  562. if (typeof topic === 'string') {
  563. topic = [topic]
  564. }
  565. if (typeof callback !== 'function') {
  566. opts = callback
  567. callback = nop
  568. }
  569. if (this._checkDisconnecting(callback)) {
  570. return this
  571. }
  572. if (typeof topic === 'string') {
  573. packet.unsubscriptions = [topic]
  574. } else if (typeof topic === 'object' && topic.length) {
  575. packet.unsubscriptions = topic
  576. }
  577. if (this.options.resubscribe) {
  578. packet.unsubscriptions.forEach(function (topic) {
  579. delete that._resubscribeTopics[topic]
  580. })
  581. }
  582. if (typeof opts === 'object' && opts.properties) {
  583. packet.properties = opts.properties
  584. }
  585. this.outgoing[packet.messageId] = callback
  586. this._sendPacket(packet)
  587. return this
  588. }
  589. /**
  590. * end - close connection
  591. *
  592. * @returns {MqttClient} this - for chaining
  593. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  594. * @param {Function} cb - called when the client has been closed
  595. *
  596. * @api public
  597. */
  598. MqttClient.prototype.end = function () {
  599. var that = this
  600. var force = arguments[0]
  601. var opts = arguments[1]
  602. var cb = arguments[2]
  603. if (force == null || typeof force !== 'boolean') {
  604. cb = opts || nop
  605. opts = force
  606. force = false
  607. if (typeof opts !== 'object') {
  608. cb = opts
  609. opts = null
  610. if (typeof cb !== 'function') {
  611. cb = nop
  612. }
  613. }
  614. }
  615. if (typeof opts !== 'object') {
  616. cb = opts
  617. opts = null
  618. }
  619. cb = cb || nop
  620. function closeStores () {
  621. that.disconnected = true
  622. that.incomingStore.close(function () {
  623. that.outgoingStore.close(function () {
  624. if (cb) {
  625. cb.apply(null, arguments)
  626. }
  627. that.emit('end')
  628. })
  629. })
  630. if (that._deferredReconnect) {
  631. that._deferredReconnect()
  632. }
  633. }
  634. function finish () {
  635. // defer closesStores of an I/O cycle,
  636. // just to make sure things are
  637. // ok for websockets
  638. that._cleanUp(force, setImmediate.bind(null, closeStores), opts)
  639. }
  640. if (this.disconnecting) {
  641. return this
  642. }
  643. this._clearReconnect()
  644. this.disconnecting = true
  645. if (!force && Object.keys(this.outgoing).length > 0) {
  646. // wait 10ms, just to be sure we received all of it
  647. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  648. } else {
  649. finish()
  650. }
  651. return this
  652. }
  653. /**
  654. * removeOutgoingMessage - remove a message in outgoing store
  655. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  656. *
  657. * @param {Number} mid - messageId to remove message
  658. * @returns {MqttClient} this - for chaining
  659. * @api public
  660. *
  661. * @example client.removeOutgoingMessage(client.getLastMessageId());
  662. */
  663. MqttClient.prototype.removeOutgoingMessage = function (mid) {
  664. var cb = this.outgoing[mid]
  665. delete this.outgoing[mid]
  666. this.outgoingStore.del({messageId: mid}, function () {
  667. cb(new Error('Message removed'))
  668. })
  669. return this
  670. }
  671. /**
  672. * reconnect - connect again using the same options as connect()
  673. *
  674. * @param {Object} [opts] - optional reconnect options, includes:
  675. * {Store} incomingStore - a store for the incoming packets
  676. * {Store} outgoingStore - a store for the outgoing packets
  677. * if opts is not given, current stores are used
  678. * @returns {MqttClient} this - for chaining
  679. *
  680. * @api public
  681. */
  682. MqttClient.prototype.reconnect = function (opts) {
  683. var that = this
  684. var f = function () {
  685. if (opts) {
  686. that.options.incomingStore = opts.incomingStore
  687. that.options.outgoingStore = opts.outgoingStore
  688. } else {
  689. that.options.incomingStore = null
  690. that.options.outgoingStore = null
  691. }
  692. that.incomingStore = that.options.incomingStore || new Store()
  693. that.outgoingStore = that.options.outgoingStore || new Store()
  694. that.disconnecting = false
  695. that.disconnected = false
  696. that._deferredReconnect = null
  697. that._reconnect()
  698. }
  699. if (this.disconnecting && !this.disconnected) {
  700. this._deferredReconnect = f
  701. } else {
  702. f()
  703. }
  704. return this
  705. }
  706. /**
  707. * _reconnect - implement reconnection
  708. * @api privateish
  709. */
  710. MqttClient.prototype._reconnect = function () {
  711. this.emit('reconnect')
  712. this._setupStream()
  713. }
  714. /**
  715. * _setupReconnect - setup reconnect timer
  716. */
  717. MqttClient.prototype._setupReconnect = function () {
  718. var that = this
  719. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  720. if (!this.reconnecting) {
  721. this.emit('offline')
  722. this.reconnecting = true
  723. }
  724. that.reconnectTimer = setInterval(function () {
  725. that._reconnect()
  726. }, that.options.reconnectPeriod)
  727. }
  728. }
  729. /**
  730. * _clearReconnect - clear the reconnect timer
  731. */
  732. MqttClient.prototype._clearReconnect = function () {
  733. if (this.reconnectTimer) {
  734. clearInterval(this.reconnectTimer)
  735. this.reconnectTimer = null
  736. }
  737. }
  738. /**
  739. * _cleanUp - clean up on connection end
  740. * @api private
  741. */
  742. MqttClient.prototype._cleanUp = function (forced, done) {
  743. var opts = arguments[2]
  744. if (done) {
  745. this.stream.on('close', done)
  746. }
  747. if (forced) {
  748. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  749. flush(this.outgoing)
  750. }
  751. console.log("_cleanUp this.stream.destroy()")
  752. this.stream.destroy()
  753. } else {
  754. var packet = xtend({ cmd: 'disconnect' }, opts)
  755. this._sendPacket(
  756. packet,
  757. setImmediate.bind(
  758. null,
  759. this.stream.end.bind(this.stream)
  760. )
  761. )
  762. }
  763. if (!this.disconnecting) {
  764. this._clearReconnect()
  765. this._setupReconnect()
  766. }
  767. if (this.pingTimer !== null) {
  768. this.pingTimer.clear()
  769. this.pingTimer = null
  770. }
  771. if (done && !this.connected) {
  772. this.stream.removeListener('close', done)
  773. done()
  774. }
  775. }
  776. /**
  777. * _sendPacket - send or queue a packet
  778. * @param {String} type - packet type (see `protocol`)
  779. * @param {Object} packet - packet options
  780. * @param {Function} cb - callback when the packet is sent
  781. * @param {Function} cbStorePut - called when message is put into outgoingStore
  782. * @api private
  783. */
  784. MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
  785. cbStorePut = cbStorePut || nop
  786. if (!this.connected) {
  787. this._storePacket(packet, cb, cbStorePut)
  788. return
  789. }
  790. // When sending a packet, reschedule the ping timer
  791. this._shiftPingInterval()
  792. switch (packet.cmd) {
  793. case 'publish':
  794. break
  795. case 'pubrel':
  796. storeAndSend(this, packet, cb, cbStorePut)
  797. return
  798. default:
  799. sendPacket(this, packet, cb)
  800. return
  801. }
  802. switch (packet.qos) {
  803. case 2:
  804. case 1:
  805. storeAndSend(this, packet, cb, cbStorePut)
  806. break
  807. /**
  808. * no need of case here since it will be caught by default
  809. * and jshint comply that before default it must be a break
  810. * anyway it will result in -1 evaluation
  811. */
  812. case 0:
  813. /* falls through */
  814. default:
  815. sendPacket(this, packet, cb)
  816. break
  817. }
  818. }
  819. /**
  820. * _storePacket - queue a packet
  821. * @param {String} type - packet type (see `protocol`)
  822. * @param {Object} packet - packet options
  823. * @param {Function} cb - callback when the packet is sent
  824. * @param {Function} cbStorePut - called when message is put into outgoingStore
  825. * @api private
  826. */
  827. MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
  828. cbStorePut = cbStorePut || nop
  829. if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
  830. this.queue.push({ packet: packet, cb: cb })
  831. } else if (packet.qos > 0) {
  832. cb = this.outgoing[packet.messageId]
  833. this.outgoingStore.put(packet, function (err) {
  834. if (err) {
  835. return cb && cb(err)
  836. }
  837. cbStorePut()
  838. })
  839. } else if (cb) {
  840. cb(new Error('No connection to broker'))
  841. }
  842. }
  843. /**
  844. * _setupPingTimer - setup the ping timer
  845. *
  846. * @api private
  847. */
  848. MqttClient.prototype._setupPingTimer = function () {
  849. var that = this
  850. if (!this.pingTimer && this.options.keepalive) {
  851. this.pingResp = true
  852. this.pingTimer = reInterval(function () {
  853. that._checkPing()
  854. }, this.options.keepalive * 1000)
  855. }
  856. }
  857. /**
  858. * _shiftPingInterval - reschedule the ping interval
  859. *
  860. * @api private
  861. */
  862. MqttClient.prototype._shiftPingInterval = function () {
  863. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  864. this.pingTimer.reschedule(this.options.keepalive * 1000)
  865. }
  866. }
  867. /**
  868. * _checkPing - check if a pingresp has come back, and ping the server again
  869. *
  870. * @api private
  871. */
  872. MqttClient.prototype._checkPing = function () {
  873. if (this.pingResp) {
  874. this.pingResp = false
  875. this._sendPacket({ cmd: 'pingreq' })
  876. } else {
  877. // do a forced cleanup since socket will be in bad shape
  878. this._cleanUp(true)
  879. }
  880. }
  881. /**
  882. * _handlePingresp - handle a pingresp
  883. *
  884. * @api private
  885. */
  886. MqttClient.prototype._handlePingresp = function () {
  887. this.pingResp = true
  888. }
  889. /**
  890. * _handleConnack
  891. *
  892. * @param {Object} packet
  893. * @api private
  894. */
  895. MqttClient.prototype._handleConnack = function (packet) {
  896. var options = this.options
  897. var version = options.protocolVersion
  898. var rc = version === 5 ? packet.reasonCode : packet.returnCode
  899. clearTimeout(this.connackTimer)
  900. if (packet.properties) {
  901. if (packet.properties.topicAliasMaximum) {
  902. if (!options.properties) { options.properties = {} }
  903. options.properties.topicAliasMaximum = packet.properties.topicAliasMaximum
  904. }
  905. if (packet.properties.serverKeepAlive && options.keepalive) {
  906. options.keepalive = packet.properties.serverKeepAlive
  907. this._shiftPingInterval()
  908. }
  909. if (packet.properties.maximumPacketSize) {
  910. if (!options.properties) { options.properties = {} }
  911. options.properties.maximumPacketSize = packet.properties.maximumPacketSize
  912. }
  913. }
  914. if (rc === 0) {
  915. this.reconnecting = false
  916. this._onConnect(packet)
  917. } else if (rc > 0) {
  918. var err = new Error('Connection refused: ' + errors[rc])
  919. err.code = rc
  920. this.emit('error', err)
  921. }
  922. }
  923. /**
  924. * _handlePublish
  925. *
  926. * @param {Object} packet
  927. * @api private
  928. */
  929. /*
  930. those late 2 case should be rewrite to comply with coding style:
  931. case 1:
  932. case 0:
  933. // do not wait sending a puback
  934. // no callback passed
  935. if (1 === qos) {
  936. this._sendPacket({
  937. cmd: 'puback',
  938. messageId: mid
  939. });
  940. }
  941. // emit the message event for both qos 1 and 0
  942. this.emit('message', topic, message, packet);
  943. this.handleMessage(packet, done);
  944. break;
  945. default:
  946. // do nothing but every switch mus have a default
  947. // log or throw an error about unknown qos
  948. break;
  949. for now i just suppressed the warnings
  950. */
  951. MqttClient.prototype._handlePublish = function (packet, done) {
  952. done = typeof done !== 'undefined' ? done : nop
  953. var topic = packet.topic.toString()
  954. var message = packet.payload
  955. var qos = packet.qos
  956. var mid = packet.messageId
  957. var that = this
  958. var options = this.options
  959. var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  960. switch (qos) {
  961. case 2: {
  962. options.customHandleAcks(topic, message, packet, function (error, code) {
  963. if (!(error instanceof Error)) {
  964. code = error
  965. error = null
  966. }
  967. if (error) { return that.emit('error', error) }
  968. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
  969. if (code) {
  970. that._sendPacket({cmd: 'pubrec', messageId: mid, reasonCode: code}, done)
  971. } else {
  972. that.incomingStore.put(packet, function () {
  973. that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
  974. })
  975. }
  976. })
  977. break
  978. }
  979. case 1: {
  980. // emit the message event
  981. options.customHandleAcks(topic, message, packet, function (error, code) {
  982. if (!(error instanceof Error)) {
  983. code = error
  984. error = null
  985. }
  986. if (error) { return that.emit('error', error) }
  987. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
  988. if (!code) { that.emit('message', topic, message, packet) }
  989. that.handleMessage(packet, function (err) {
  990. if (err) {
  991. return done && done(err)
  992. }
  993. that._sendPacket({cmd: 'puback', messageId: mid, reasonCode: code}, done)
  994. })
  995. })
  996. break
  997. }
  998. case 0:
  999. // emit the message event
  1000. this.emit('message', topic, message, packet)
  1001. this.handleMessage(packet, done)
  1002. break
  1003. default:
  1004. // do nothing
  1005. // log or throw an error about unknown qos
  1006. break
  1007. }
  1008. }
  1009. /**
  1010. * Handle messages with backpressure support, one at a time.
  1011. * Override at will.
  1012. *
  1013. * @param Packet packet the packet
  1014. * @param Function callback call when finished
  1015. * @api public
  1016. */
  1017. MqttClient.prototype.handleMessage = function (packet, callback) {
  1018. callback()
  1019. }
  1020. /**
  1021. * _handleAck
  1022. *
  1023. * @param {Object} packet
  1024. * @api private
  1025. */
  1026. MqttClient.prototype._handleAck = function (packet) {
  1027. /* eslint no-fallthrough: "off" */
  1028. var mid = packet.messageId
  1029. var type = packet.cmd
  1030. var response = null
  1031. var cb = this.outgoing[mid]
  1032. var that = this
  1033. var err
  1034. if (!cb) {
  1035. // Server sent an ack in error, ignore it.
  1036. return
  1037. }
  1038. // Process
  1039. switch (type) {
  1040. case 'pubcomp':
  1041. // same thing as puback for QoS 2
  1042. case 'puback':
  1043. var pubackRC = packet.reasonCode
  1044. // Callback - we're done
  1045. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1046. err = new Error('Publish error: ' + errors[pubackRC])
  1047. err.code = pubackRC
  1048. cb(err, packet)
  1049. }
  1050. delete this.outgoing[mid]
  1051. this.outgoingStore.del(packet, cb)
  1052. break
  1053. case 'pubrec':
  1054. response = {
  1055. cmd: 'pubrel',
  1056. qos: 2,
  1057. messageId: mid
  1058. }
  1059. var pubrecRC = packet.reasonCode
  1060. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1061. err = new Error('Publish error: ' + errors[pubrecRC])
  1062. err.code = pubrecRC
  1063. cb(err, packet)
  1064. } else {
  1065. this._sendPacket(response)
  1066. }
  1067. break
  1068. case 'suback':
  1069. delete this.outgoing[mid]
  1070. for (var grantedI = 0; grantedI < packet.granted.length; grantedI++) {
  1071. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1072. // suback with Failure status
  1073. var topics = this.messageIdToTopic[mid]
  1074. if (topics) {
  1075. topics.forEach(function (topic) {
  1076. delete that._resubscribeTopics[topic]
  1077. })
  1078. }
  1079. }
  1080. }
  1081. cb(null, packet)
  1082. break
  1083. case 'unsuback':
  1084. delete this.outgoing[mid]
  1085. cb(null)
  1086. break
  1087. default:
  1088. that.emit('error', new Error('unrecognized packet type'))
  1089. }
  1090. if (this.disconnecting &&
  1091. Object.keys(this.outgoing).length === 0) {
  1092. this.emit('outgoingEmpty')
  1093. }
  1094. }
  1095. /**
  1096. * _handlePubrel
  1097. *
  1098. * @param {Object} packet
  1099. * @api private
  1100. */
  1101. MqttClient.prototype._handlePubrel = function (packet, callback) {
  1102. callback = typeof callback !== 'undefined' ? callback : nop
  1103. var mid = packet.messageId
  1104. var that = this
  1105. var comp = {cmd: 'pubcomp', messageId: mid}
  1106. that.incomingStore.get(packet, function (err, pub) {
  1107. if (!err) {
  1108. that.emit('message', pub.topic, pub.payload, pub)
  1109. that.handleMessage(pub, function (err) {
  1110. if (err) {
  1111. return callback(err)
  1112. }
  1113. that.incomingStore.del(pub, nop)
  1114. that._sendPacket(comp, callback)
  1115. })
  1116. } else {
  1117. that._sendPacket(comp, callback)
  1118. }
  1119. })
  1120. }
  1121. /**
  1122. * _nextId
  1123. * @return unsigned int
  1124. */
  1125. MqttClient.prototype._nextId = function () {
  1126. // id becomes current state of this.nextId and increments afterwards
  1127. var id = this.nextId++
  1128. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  1129. if (this.nextId === 65536) {
  1130. this.nextId = 1
  1131. }
  1132. return id
  1133. }
  1134. /**
  1135. * getLastMessageId
  1136. * @return unsigned int
  1137. */
  1138. MqttClient.prototype.getLastMessageId = function () {
  1139. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  1140. }
  1141. /**
  1142. * _resubscribe
  1143. * @api private
  1144. */
  1145. MqttClient.prototype._resubscribe = function (connack) {
  1146. if (!this._firstConnection &&
  1147. (this.options.clean || (this.options.protocolVersion === 5 && !connack.sessionPresent)) &&
  1148. Object.keys(this._resubscribeTopics).length > 0) {
  1149. if (this.options.resubscribe) {
  1150. this._resubscribeTopics.resubscribe = true
  1151. this.subscribe(this._resubscribeTopics)
  1152. } else {
  1153. this._resubscribeTopics = {}
  1154. }
  1155. }
  1156. this._firstConnection = false
  1157. }
  1158. /**
  1159. * _onConnect
  1160. *
  1161. * @api private
  1162. */
  1163. MqttClient.prototype._onConnect = function (packet) {
  1164. if (this.disconnected) {
  1165. this.emit('connect', packet)
  1166. return
  1167. }
  1168. var that = this
  1169. this._setupPingTimer()
  1170. this._resubscribe(packet)
  1171. this.connected = true
  1172. function startStreamProcess () {
  1173. var outStore = that.outgoingStore.createStream()
  1174. function clearStoreProcessing () {
  1175. that._storeProcessing = false
  1176. that._packetIdsDuringStoreProcessing = {}
  1177. }
  1178. that.once('close', remove)
  1179. outStore.on('error', function (err) {
  1180. clearStoreProcessing()
  1181. that.removeListener('close', remove)
  1182. that.emit('error', err)
  1183. })
  1184. function remove () {
  1185. outStore.destroy()
  1186. outStore = null
  1187. clearStoreProcessing()
  1188. }
  1189. function storeDeliver () {
  1190. // edge case, we wrapped this twice
  1191. if (!outStore) {
  1192. return
  1193. }
  1194. that._storeProcessing = true
  1195. var packet = outStore.read(1)
  1196. var cb
  1197. if (!packet) {
  1198. // read when data is available in the future
  1199. outStore.once('readable', storeDeliver)
  1200. return
  1201. }
  1202. // Skip already processed store packets
  1203. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1204. storeDeliver()
  1205. return
  1206. }
  1207. // Avoid unnecessary stream read operations when disconnected
  1208. if (!that.disconnecting && !that.reconnectTimer) {
  1209. cb = that.outgoing[packet.messageId]
  1210. that.outgoing[packet.messageId] = function (err, status) {
  1211. // Ensure that the original callback passed in to publish gets invoked
  1212. if (cb) {
  1213. cb(err, status)
  1214. }
  1215. storeDeliver()
  1216. }
  1217. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1218. that._sendPacket(packet)
  1219. } else if (outStore.destroy) {
  1220. outStore.destroy()
  1221. }
  1222. }
  1223. outStore.on('end', function () {
  1224. var allProcessed = true
  1225. for (var id in that._packetIdsDuringStoreProcessing) {
  1226. if (!that._packetIdsDuringStoreProcessing[id]) {
  1227. allProcessed = false
  1228. break
  1229. }
  1230. }
  1231. if (allProcessed) {
  1232. clearStoreProcessing()
  1233. that.removeListener('close', remove)
  1234. that.emit('connect', packet)
  1235. } else {
  1236. startStreamProcess()
  1237. }
  1238. })
  1239. storeDeliver()
  1240. }
  1241. // start flowing
  1242. startStreamProcess()
  1243. }
  1244. module.exports = MqttClient
  1245. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1246. },{"./store":7,"./validations":8,"_process":92,"events":13,"inherits":80,"mqtt-packet":84,"readable-stream":108,"reinterval":109,"xtend":121}],2:[function(require,module,exports){
  1247. (function (Buffer){
  1248. 'use strict'
  1249. var Transform = require('readable-stream').Transform
  1250. var duplexify = require('duplexify')
  1251. var base64 = require('base64-js')
  1252. /* global FileReader */
  1253. var my
  1254. var proxy
  1255. var stream
  1256. var isInitialized = false
  1257. function buildProxy () {
  1258. var proxy = new Transform()
  1259. proxy._write = function (chunk, encoding, next) {
  1260. my.sendSocketMessage({
  1261. data: chunk.buffer,
  1262. success: function () {
  1263. next()
  1264. },
  1265. fail: function () {
  1266. next(new Error())
  1267. }
  1268. })
  1269. }
  1270. proxy._flush = function socketEnd (done) {
  1271. my.closeSocket({
  1272. success: function () {
  1273. done()
  1274. }
  1275. })
  1276. }
  1277. return proxy
  1278. }
  1279. function setDefaultOpts (opts) {
  1280. if (!opts.hostname) {
  1281. opts.hostname = 'localhost'
  1282. }
  1283. if (!opts.path) {
  1284. opts.path = '/'
  1285. }
  1286. if (!opts.wsOptions) {
  1287. opts.wsOptions = {}
  1288. }
  1289. }
  1290. function buildUrl (opts, client) {
  1291. var protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1292. var url = protocol + '://' + opts.hostname + opts.path
  1293. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1294. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1295. }
  1296. if (typeof (opts.transformWsUrl) === 'function') {
  1297. url = opts.transformWsUrl(url, opts, client)
  1298. }
  1299. return url
  1300. }
  1301. function bindEventHandler () {
  1302. if (isInitialized) return
  1303. isInitialized = true
  1304. my.onSocketOpen(function () {
  1305. stream.setReadable(proxy)
  1306. stream.setWritable(proxy)
  1307. stream.emit('connect')
  1308. })
  1309. my.onSocketMessage(function (res) {
  1310. if (typeof res.data === 'string') {
  1311. var array = base64.toByteArray(res.data)
  1312. var buffer = Buffer.from(array)
  1313. proxy.push(buffer)
  1314. } else {
  1315. var reader = new FileReader()
  1316. reader.addEventListener('load', function () {
  1317. var data = reader.result
  1318. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1319. else data = Buffer.from(data, 'utf8')
  1320. proxy.push(data)
  1321. })
  1322. reader.readAsArrayBuffer(res.data)
  1323. }
  1324. })
  1325. my.onSocketClose(function () {
  1326. stream.end()
  1327. stream.destroy()
  1328. })
  1329. my.onSocketError(function (res) {
  1330. stream.destroy(res)
  1331. })
  1332. }
  1333. function buildStream (client, opts) {
  1334. opts.hostname = opts.hostname || opts.host
  1335. if (!opts.hostname) {
  1336. throw new Error('Could not determine host. Specify host manually.')
  1337. }
  1338. var websocketSubProtocol =
  1339. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1340. ? 'mqttv3.1'
  1341. : 'mqtt'
  1342. setDefaultOpts(opts)
  1343. var url = buildUrl(opts, client)
  1344. my = opts.my
  1345. my.connectSocket({
  1346. url: url,
  1347. protocols: websocketSubProtocol
  1348. })
  1349. proxy = buildProxy()
  1350. stream = duplexify.obj()
  1351. bindEventHandler()
  1352. return stream
  1353. }
  1354. module.exports = buildStream
  1355. }).call(this,require("buffer").Buffer)
  1356. },{"base64-js":10,"buffer":12,"duplexify":17,"readable-stream":108}],3:[function(require,module,exports){
  1357. 'use strict'
  1358. var net = require('net')
  1359. /*
  1360. variables port and host can be removed since
  1361. you have all required information in opts object
  1362. */
  1363. function buildBuilder (client, opts) {
  1364. var port, host
  1365. opts.port = opts.port || 1883
  1366. opts.hostname = opts.hostname || opts.host || 'localhost'
  1367. port = opts.port
  1368. host = opts.hostname
  1369. return net.createConnection(port, host)
  1370. }
  1371. module.exports = buildBuilder
  1372. },{"net":11}],4:[function(require,module,exports){
  1373. 'use strict'
  1374. var tls = require('tls')
  1375. function buildBuilder (mqttClient, opts) {
  1376. var connection
  1377. opts.port = opts.port || 8883
  1378. opts.host = opts.hostname || opts.host || 'localhost'
  1379. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1380. delete opts.path
  1381. connection = tls.connect(opts)
  1382. /* eslint no-use-before-define: [2, "nofunc"] */
  1383. connection.on('secureConnect', function () {
  1384. if (opts.rejectUnauthorized && !connection.authorized) {
  1385. connection.emit('error', new Error('TLS not authorized'))
  1386. } else {
  1387. connection.removeListener('error', handleTLSerrors)
  1388. }
  1389. })
  1390. function handleTLSerrors (err) {
  1391. // How can I get verify this error is a tls error?
  1392. if (opts.rejectUnauthorized) {
  1393. mqttClient.emit('error', err)
  1394. }
  1395. // close this connection to match the behaviour of net
  1396. // otherwise all we get is an error from the connection
  1397. // and close event doesn't fire. This is a work around
  1398. // to enable the reconnect code to work the same as with
  1399. // net.createConnection
  1400. connection.end()
  1401. }
  1402. connection.on('error', handleTLSerrors)
  1403. return connection
  1404. }
  1405. module.exports = buildBuilder
  1406. },{"tls":11}],5:[function(require,module,exports){
  1407. (function (process){
  1408. 'use strict'
  1409. var websocket = require('websocket-stream')
  1410. var urlModule = require('url')
  1411. var WSS_OPTIONS = [
  1412. 'rejectUnauthorized',
  1413. 'ca',
  1414. 'cert',
  1415. 'key',
  1416. 'pfx',
  1417. 'passphrase'
  1418. ]
  1419. var IS_BROWSER = process.title === 'browser'
  1420. function buildUrl (opts, client) {
  1421. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1422. if (typeof (opts.transformWsUrl) === 'function') {
  1423. url = opts.transformWsUrl(url, opts, client)
  1424. }
  1425. return url
  1426. }
  1427. function setDefaultOpts (opts) {
  1428. if (!opts.hostname) {
  1429. opts.hostname = 'localhost'
  1430. }
  1431. if (!opts.port) {
  1432. if (opts.protocol === 'wss') {
  1433. opts.port = 443
  1434. } else {
  1435. opts.port = 80
  1436. }
  1437. }
  1438. if (!opts.path) {
  1439. opts.path = '/'
  1440. }
  1441. if (!opts.wsOptions) {
  1442. opts.wsOptions = {}
  1443. }
  1444. if (!IS_BROWSER && opts.protocol === 'wss') {
  1445. // Add cert/key/ca etc options
  1446. WSS_OPTIONS.forEach(function (prop) {
  1447. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  1448. opts.wsOptions[prop] = opts[prop]
  1449. }
  1450. })
  1451. }
  1452. }
  1453. function createWebSocket (client, opts) {
  1454. var websocketSubProtocol =
  1455. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1456. ? 'mqttv3.1'
  1457. : 'mqtt'
  1458. setDefaultOpts(opts)
  1459. var url = buildUrl(opts, client)
  1460. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1461. }
  1462. function buildBuilder (client, opts) {
  1463. return createWebSocket(client, opts)
  1464. }
  1465. function buildBuilderBrowser (client, opts) {
  1466. if (!opts.hostname) {
  1467. opts.hostname = opts.host
  1468. }
  1469. if (!opts.hostname) {
  1470. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1471. // can not determine the `hostname` automatically. If connecting to
  1472. // localhost, please supply the `hostname` as an argument.
  1473. if (typeof (document) === 'undefined') {
  1474. throw new Error('Could not determine host. Specify host manually.')
  1475. }
  1476. var parsed = urlModule.parse(document.URL)
  1477. opts.hostname = parsed.hostname
  1478. if (!opts.port) {
  1479. opts.port = parsed.port
  1480. }
  1481. }
  1482. return createWebSocket(client, opts)
  1483. }
  1484. if (IS_BROWSER) {
  1485. module.exports = buildBuilderBrowser
  1486. } else {
  1487. module.exports = buildBuilder
  1488. }
  1489. }).call(this,require('_process'))
  1490. },{"_process":92,"url":113,"websocket-stream":118}],6:[function(require,module,exports){
  1491. (function (process,Buffer){
  1492. 'use strict'
  1493. var Transform = require('readable-stream').Transform
  1494. var duplexify = require('duplexify')
  1495. /* global wx */
  1496. var socketTask
  1497. var proxy
  1498. var stream
  1499. function buildProxy () {
  1500. var proxy = new Transform()
  1501. proxy._write = function (chunk, encoding, next) {
  1502. socketTask.send({
  1503. data: chunk.buffer,
  1504. success: function () {
  1505. next()
  1506. },
  1507. fail: function (errMsg) {
  1508. next(new Error(errMsg))
  1509. }
  1510. })
  1511. }
  1512. proxy._flush = function socketEnd (done) {
  1513. socketTask.close({
  1514. success: function () {
  1515. done()
  1516. },
  1517. fail:function(err){
  1518. }
  1519. })
  1520. }
  1521. return proxy
  1522. }
  1523. function setDefaultOpts (opts) {
  1524. if (!opts.hostname) {
  1525. opts.hostname = 'localhost'
  1526. }
  1527. if (!opts.path) {
  1528. opts.path = '/'
  1529. }
  1530. if (!opts.wsOptions) {
  1531. opts.wsOptions = {}
  1532. }
  1533. }
  1534. function buildUrl (opts, client) {
  1535. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1536. var url = protocol + '://' + opts.hostname + opts.path
  1537. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1538. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1539. }
  1540. if (typeof (opts.transformWsUrl) === 'function') {
  1541. url = opts.transformWsUrl(url, opts, client)
  1542. }
  1543. return url
  1544. }
  1545. function bindEventHandler () {
  1546. socketTask.onOpen(function () {
  1547. stream.setReadable(proxy)
  1548. stream.setWritable(proxy)
  1549. stream.emit('connect')
  1550. })
  1551. socketTask.onMessage(function (res) {
  1552. var data = res.data
  1553. if (data instanceof ArrayBuffer){
  1554. data = Buffer.from(data)
  1555. }
  1556. else{
  1557. data = Buffer.from(data, 'utf8')
  1558. }
  1559. proxy.push(data)
  1560. })
  1561. socketTask.onClose(function () {
  1562. console.log(`socketTask.onClose`)
  1563. stream.end()
  1564. stream.destroy()
  1565. stream.emit('close')
  1566. })
  1567. socketTask.onError(function (res) {
  1568. console.log(`socketTask.onError res = ${res}`)
  1569. stream.destroy(new Error(res.errMsg))
  1570. })
  1571. }
  1572. function buildStream (client, opts) {
  1573. var that = this
  1574. opts.hostname = opts.hostname || opts.host
  1575. if (!opts.hostname) {
  1576. throw new Error('Could not determine host. Specify host manually.')
  1577. }
  1578. var websocketSubProtocol =
  1579. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1580. ? 'mqttv3.1'
  1581. : 'mqtt'
  1582. setDefaultOpts(opts)
  1583. var url = buildUrl(opts, client)
  1584. socketTask = wx.connectSocket({
  1585. url: url,
  1586. protocols: websocketSubProtocol,
  1587. success(res){
  1588. },
  1589. fail(err){
  1590. }
  1591. })
  1592. proxy = buildProxy()
  1593. stream = duplexify.obj()
  1594. stream._destroy = function (err, cb) {
  1595. socketTask.close({
  1596. success: function () {
  1597. cb && cb(err)
  1598. },
  1599. fail:function (err) {
  1600. },
  1601. complete:function(){
  1602. //cb && cb(err)
  1603. }
  1604. })
  1605. }
  1606. var destroyRef = stream.destroy
  1607. stream.destroy = function () {
  1608. stream.destroy = destroyRef
  1609. var self = this
  1610. process.nextTick(function () {
  1611. socketTask.close({
  1612. success:function(){
  1613. },
  1614. fail: function (err) {
  1615. self._destroy(new Error())
  1616. }
  1617. })
  1618. })
  1619. }.bind(stream)
  1620. bindEventHandler()
  1621. return stream
  1622. }
  1623. module.exports = buildStream
  1624. }).call(this,require('_process'),require("buffer").Buffer)
  1625. },{"_process":92,"buffer":12,"duplexify":17,"readable-stream":108}],7:[function(require,module,exports){
  1626. (function (process){
  1627. 'use strict'
  1628. /**
  1629. * Module dependencies
  1630. */
  1631. var xtend = require('xtend')
  1632. var Readable = require('readable-stream').Readable
  1633. var streamsOpts = { objectMode: true }
  1634. var defaultStoreOptions = {
  1635. clean: true
  1636. }
  1637. /**
  1638. * es6-map can preserve insertion order even if ES version is older.
  1639. *
  1640. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
  1641. * It should be noted that a Map which is a map of an object, especially
  1642. * a dictionary of dictionaries, will only map to the object's insertion
  1643. * order. In ES2015 this is ordered for objects but for older versions of
  1644. * ES, this may be random and not ordered.
  1645. *
  1646. */
  1647. var Map = require('es6-map')
  1648. /**
  1649. * In-memory implementation of the message store
  1650. * This can actually be saved into files.
  1651. *
  1652. * @param {Object} [options] - store options
  1653. */
  1654. function Store (options) {
  1655. if (!(this instanceof Store)) {
  1656. return new Store(options)
  1657. }
  1658. this.options = options || {}
  1659. // Defaults
  1660. this.options = xtend(defaultStoreOptions, options)
  1661. this._inflights = new Map()
  1662. }
  1663. /**
  1664. * Adds a packet to the store, a packet is
  1665. * anything that has a messageId property.
  1666. *
  1667. */
  1668. Store.prototype.put = function (packet, cb) {
  1669. this._inflights.set(packet.messageId, packet)
  1670. if (cb) {
  1671. cb()
  1672. }
  1673. return this
  1674. }
  1675. /**
  1676. * Creates a stream with all the packets in the store
  1677. *
  1678. */
  1679. Store.prototype.createStream = function () {
  1680. var stream = new Readable(streamsOpts)
  1681. var destroyed = false
  1682. var values = []
  1683. var i = 0
  1684. this._inflights.forEach(function (value, key) {
  1685. values.push(value)
  1686. })
  1687. stream._read = function () {
  1688. if (!destroyed && i < values.length) {
  1689. this.push(values[i++])
  1690. } else {
  1691. this.push(null)
  1692. }
  1693. }
  1694. stream.destroy = function () {
  1695. if (destroyed) {
  1696. return
  1697. }
  1698. var self = this
  1699. destroyed = true
  1700. process.nextTick(function () {
  1701. self.emit('close')
  1702. })
  1703. }
  1704. return stream
  1705. }
  1706. /**
  1707. * deletes a packet from the store.
  1708. */
  1709. Store.prototype.del = function (packet, cb) {
  1710. packet = this._inflights.get(packet.messageId)
  1711. if (packet) {
  1712. this._inflights.delete(packet.messageId)
  1713. cb(null, packet)
  1714. } else if (cb) {
  1715. cb(new Error('missing packet'))
  1716. }
  1717. return this
  1718. }
  1719. /**
  1720. * get a packet from the store.
  1721. */
  1722. Store.prototype.get = function (packet, cb) {
  1723. packet = this._inflights.get(packet.messageId)
  1724. if (packet) {
  1725. cb(null, packet)
  1726. } else if (cb) {
  1727. cb(new Error('missing packet'))
  1728. }
  1729. return this
  1730. }
  1731. /**
  1732. * Close the store
  1733. */
  1734. Store.prototype.close = function (cb) {
  1735. if (this.options.clean) {
  1736. this._inflights = null
  1737. }
  1738. if (cb) {
  1739. cb()
  1740. }
  1741. }
  1742. module.exports = Store
  1743. }).call(this,require('_process'))
  1744. },{"_process":92,"es6-map":67,"readable-stream":108,"xtend":121}],8:[function(require,module,exports){
  1745. 'use strict'
  1746. /**
  1747. * Validate a topic to see if it's valid or not.
  1748. * A topic is valid if it follow below rules:
  1749. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1750. * - Rule #2: Part `#` must be located at the end of the mailbox
  1751. *
  1752. * @param {String} topic - A topic
  1753. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1754. */
  1755. function validateTopic (topic) {
  1756. var parts = topic.split('/')
  1757. for (var i = 0; i < parts.length; i++) {
  1758. if (parts[i] === '+') {
  1759. continue
  1760. }
  1761. if (parts[i] === '#') {
  1762. // for Rule #2
  1763. return i === parts.length - 1
  1764. }
  1765. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1766. return false
  1767. }
  1768. }
  1769. return true
  1770. }
  1771. /**
  1772. * Validate an array of topics to see if any of them is valid or not
  1773. * @param {Array} topics - Array of topics
  1774. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1775. */
  1776. function validateTopics (topics) {
  1777. if (topics.length === 0) {
  1778. return 'empty_topic_list'
  1779. }
  1780. for (var i = 0; i < topics.length; i++) {
  1781. if (!validateTopic(topics[i])) {
  1782. return topics[i]
  1783. }
  1784. }
  1785. return null
  1786. }
  1787. module.exports = {
  1788. validateTopics: validateTopics
  1789. }
  1790. },{}],9:[function(require,module,exports){
  1791. (function (process){
  1792. 'use strict'
  1793. var MqttClient = require('../client')
  1794. var Store = require('../store')
  1795. var url = require('url')
  1796. var xtend = require('xtend')
  1797. var protocols = {}
  1798. if (process.title !== 'browser') {
  1799. protocols.mqtt = require('./tcp')
  1800. protocols.tcp = require('./tcp')
  1801. protocols.ssl = require('./tls')
  1802. protocols.tls = require('./tls')
  1803. protocols.mqtts = require('./tls')
  1804. } else {
  1805. protocols.wx = require('./wx')
  1806. protocols.wxs = require('./wx')
  1807. protocols.ali = require('./ali')
  1808. protocols.alis = require('./ali')
  1809. }
  1810. protocols.ws = require('./ws')
  1811. protocols.wss = require('./ws')
  1812. /**
  1813. * Parse the auth attribute and merge username and password in the options object.
  1814. *
  1815. * @param {Object} [opts] option object
  1816. */
  1817. function parseAuthOptions (opts) {
  1818. var matches
  1819. if (opts.auth) {
  1820. matches = opts.auth.match(/^(.+):(.+)$/)
  1821. if (matches) {
  1822. opts.username = matches[1]
  1823. opts.password = matches[2]
  1824. } else {
  1825. opts.username = opts.auth
  1826. }
  1827. }
  1828. }
  1829. /**
  1830. * connect - connect to an MQTT broker.
  1831. *
  1832. * @param {String} [brokerUrl] - url of the broker, optional
  1833. * @param {Object} opts - see MqttClient#constructor
  1834. */
  1835. function connect (brokerUrl, opts) {
  1836. if ((typeof brokerUrl === 'object') && !opts) {
  1837. opts = brokerUrl
  1838. brokerUrl = null
  1839. }
  1840. opts = opts || {}
  1841. if (brokerUrl) {
  1842. var parsed = url.parse(brokerUrl, true)
  1843. if (parsed.port != null) {
  1844. parsed.port = Number(parsed.port)
  1845. }
  1846. opts = xtend(parsed, opts)
  1847. if (opts.protocol === null) {
  1848. throw new Error('Missing protocol')
  1849. }
  1850. opts.protocol = opts.protocol.replace(/:$/, '')
  1851. }
  1852. // merge in the auth options if supplied
  1853. parseAuthOptions(opts)
  1854. // support clientId passed in the query string of the url
  1855. if (opts.query && typeof opts.query.clientId === 'string') {
  1856. opts.clientId = opts.query.clientId
  1857. }
  1858. if (opts.cert && opts.key) {
  1859. if (opts.protocol) {
  1860. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  1861. switch (opts.protocol) {
  1862. case 'mqtt':
  1863. opts.protocol = 'mqtts'
  1864. break
  1865. case 'ws':
  1866. opts.protocol = 'wss'
  1867. break
  1868. case 'wx':
  1869. opts.protocol = 'wxs'
  1870. break
  1871. case 'ali':
  1872. opts.protocol = 'alis'
  1873. break
  1874. default:
  1875. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  1876. }
  1877. }
  1878. } else {
  1879. // don't know what protocol he want to use, mqtts or wss
  1880. throw new Error('Missing secure protocol key')
  1881. }
  1882. }
  1883. if (!protocols[opts.protocol]) {
  1884. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  1885. opts.protocol = [
  1886. 'mqtt',
  1887. 'mqtts',
  1888. 'ws',
  1889. 'wss',
  1890. 'wx',
  1891. 'wxs',
  1892. 'ali',
  1893. 'alis'
  1894. ].filter(function (key, index) {
  1895. if (isSecure && index % 2 === 0) {
  1896. // Skip insecure protocols when requesting a secure one.
  1897. return false
  1898. }
  1899. return (typeof protocols[key] === 'function')
  1900. })[0]
  1901. }
  1902. if (opts.clean === false && !opts.clientId) {
  1903. throw new Error('Missing clientId for unclean clients')
  1904. }
  1905. if (opts.protocol) {
  1906. opts.defaultProtocol = opts.protocol
  1907. }
  1908. function wrapper (client) {
  1909. if (opts.servers) {
  1910. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  1911. client._reconnectCount = 0
  1912. }
  1913. opts.host = opts.servers[client._reconnectCount].host
  1914. opts.port = opts.servers[client._reconnectCount].port
  1915. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  1916. opts.hostname = opts.host
  1917. client._reconnectCount++
  1918. }
  1919. return protocols[opts.protocol](client, opts)
  1920. }
  1921. return new MqttClient(wrapper, opts)
  1922. }
  1923. module.exports = connect
  1924. module.exports.connect = connect
  1925. module.exports.MqttClient = MqttClient
  1926. module.exports.Store = Store
  1927. }).call(this,require('_process'))
  1928. },{"../client":1,"../store":7,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,"_process":92,"url":113,"xtend":121}],10:[function(require,module,exports){
  1929. 'use strict'
  1930. exports.byteLength = byteLength
  1931. exports.toByteArray = toByteArray
  1932. exports.fromByteArray = fromByteArray
  1933. var lookup = []
  1934. var revLookup = []
  1935. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1936. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1937. for (var i = 0, len = code.length; i < len; ++i) {
  1938. lookup[i] = code[i]
  1939. revLookup[code.charCodeAt(i)] = i
  1940. }
  1941. // Support decoding URL-safe base64 strings, as Node.js does.
  1942. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  1943. revLookup['-'.charCodeAt(0)] = 62
  1944. revLookup['_'.charCodeAt(0)] = 63
  1945. function getLens (b64) {
  1946. var len = b64.length
  1947. if (len % 4 > 0) {
  1948. throw new Error('Invalid string. Length must be a multiple of 4')
  1949. }
  1950. // Trim off extra bytes after placeholder bytes are found
  1951. // See: https://github.com/beatgammit/base64-js/issues/42
  1952. var validLen = b64.indexOf('=')
  1953. if (validLen === -1) validLen = len
  1954. var placeHoldersLen = validLen === len
  1955. ? 0
  1956. : 4 - (validLen % 4)
  1957. return [validLen, placeHoldersLen]
  1958. }
  1959. // base64 is 4/3 + up to two characters of the original data
  1960. function byteLength (b64) {
  1961. var lens = getLens(b64)
  1962. var validLen = lens[0]
  1963. var placeHoldersLen = lens[1]
  1964. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1965. }
  1966. function _byteLength (b64, validLen, placeHoldersLen) {
  1967. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1968. }
  1969. function toByteArray (b64) {
  1970. var tmp
  1971. var lens = getLens(b64)
  1972. var validLen = lens[0]
  1973. var placeHoldersLen = lens[1]
  1974. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  1975. var curByte = 0
  1976. // if there are placeholders, only get up to the last complete 4 chars
  1977. var len = placeHoldersLen > 0
  1978. ? validLen - 4
  1979. : validLen
  1980. for (var i = 0; i < len; i += 4) {
  1981. tmp =
  1982. (revLookup[b64.charCodeAt(i)] << 18) |
  1983. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  1984. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  1985. revLookup[b64.charCodeAt(i + 3)]
  1986. arr[curByte++] = (tmp >> 16) & 0xFF
  1987. arr[curByte++] = (tmp >> 8) & 0xFF
  1988. arr[curByte++] = tmp & 0xFF
  1989. }
  1990. if (placeHoldersLen === 2) {
  1991. tmp =
  1992. (revLookup[b64.charCodeAt(i)] << 2) |
  1993. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1994. arr[curByte++] = tmp & 0xFF
  1995. }
  1996. if (placeHoldersLen === 1) {
  1997. tmp =
  1998. (revLookup[b64.charCodeAt(i)] << 10) |
  1999. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2000. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2001. arr[curByte++] = (tmp >> 8) & 0xFF
  2002. arr[curByte++] = tmp & 0xFF
  2003. }
  2004. return arr
  2005. }
  2006. function tripletToBase64 (num) {
  2007. return lookup[num >> 18 & 0x3F] +
  2008. lookup[num >> 12 & 0x3F] +
  2009. lookup[num >> 6 & 0x3F] +
  2010. lookup[num & 0x3F]
  2011. }
  2012. function encodeChunk (uint8, start, end) {
  2013. var tmp
  2014. var output = []
  2015. for (var i = start; i < end; i += 3) {
  2016. tmp =
  2017. ((uint8[i] << 16) & 0xFF0000) +
  2018. ((uint8[i + 1] << 8) & 0xFF00) +
  2019. (uint8[i + 2] & 0xFF)
  2020. output.push(tripletToBase64(tmp))
  2021. }
  2022. return output.join('')
  2023. }
  2024. function fromByteArray (uint8) {
  2025. var tmp
  2026. var len = uint8.length
  2027. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2028. var parts = []
  2029. var maxChunkLength = 16383 // must be multiple of 3
  2030. // go through the array every three bytes, we'll deal with trailing stuff later
  2031. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2032. parts.push(encodeChunk(
  2033. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2034. ))
  2035. }
  2036. // pad the end with zeros, but make sure to not forget the extra bytes
  2037. if (extraBytes === 1) {
  2038. tmp = uint8[len - 1]
  2039. parts.push(
  2040. lookup[tmp >> 2] +
  2041. lookup[(tmp << 4) & 0x3F] +
  2042. '=='
  2043. )
  2044. } else if (extraBytes === 2) {
  2045. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2046. parts.push(
  2047. lookup[tmp >> 10] +
  2048. lookup[(tmp >> 4) & 0x3F] +
  2049. lookup[(tmp << 2) & 0x3F] +
  2050. '='
  2051. )
  2052. }
  2053. return parts.join('')
  2054. }
  2055. },{}],11:[function(require,module,exports){
  2056. },{}],12:[function(require,module,exports){
  2057. /*!
  2058. * The buffer module from node.js, for the browser.
  2059. *
  2060. * @author Feross Aboukhadijeh <https://feross.org>
  2061. * @license MIT
  2062. */
  2063. /* eslint-disable no-proto */
  2064. 'use strict'
  2065. var base64 = require('base64-js')
  2066. var ieee754 = require('ieee754')
  2067. exports.Buffer = Buffer
  2068. exports.SlowBuffer = SlowBuffer
  2069. exports.INSPECT_MAX_BYTES = 50
  2070. var K_MAX_LENGTH = 0x7fffffff
  2071. exports.kMaxLength = K_MAX_LENGTH
  2072. /**
  2073. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2074. * === true Use Uint8Array implementation (fastest)
  2075. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2076. * implementation (most compatible, even IE6)
  2077. *
  2078. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2079. * Opera 11.6+, iOS 4.2+.
  2080. *
  2081. * We report that the browser does not support typed arrays if the are not subclassable
  2082. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2083. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2084. * for __proto__ and has a buggy typed array implementation.
  2085. */
  2086. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2087. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2088. typeof console.error === 'function') {
  2089. console.error(
  2090. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2091. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2092. )
  2093. }
  2094. function typedArraySupport () {
  2095. // Can typed array instances can be augmented?
  2096. try {
  2097. var arr = new Uint8Array(1)
  2098. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2099. return arr.foo() === 42
  2100. } catch (e) {
  2101. return false
  2102. }
  2103. }
  2104. Object.defineProperty(Buffer.prototype, 'parent', {
  2105. enumerable: true,
  2106. get: function () {
  2107. if (!Buffer.isBuffer(this)) return undefined
  2108. return this.buffer
  2109. }
  2110. })
  2111. Object.defineProperty(Buffer.prototype, 'offset', {
  2112. enumerable: true,
  2113. get: function () {
  2114. if (!Buffer.isBuffer(this)) return undefined
  2115. return this.byteOffset
  2116. }
  2117. })
  2118. function createBuffer (length) {
  2119. if (length > K_MAX_LENGTH) {
  2120. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2121. }
  2122. // Return an augmented `Uint8Array` instance
  2123. var buf = new Uint8Array(length)
  2124. buf.__proto__ = Buffer.prototype
  2125. return buf
  2126. }
  2127. /**
  2128. * The Buffer constructor returns instances of `Uint8Array` that have their
  2129. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2130. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2131. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2132. * returns a single octet.
  2133. *
  2134. * The `Uint8Array` prototype remains unmodified.
  2135. */
  2136. function Buffer (arg, encodingOrOffset, length) {
  2137. // Common case.
  2138. if (typeof arg === 'number') {
  2139. if (typeof encodingOrOffset === 'string') {
  2140. throw new TypeError(
  2141. 'The "string" argument must be of type string. Received type number'
  2142. )
  2143. }
  2144. return allocUnsafe(arg)
  2145. }
  2146. return from(arg, encodingOrOffset, length)
  2147. }
  2148. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2149. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2150. Buffer[Symbol.species] === Buffer) {
  2151. Object.defineProperty(Buffer, Symbol.species, {
  2152. value: null,
  2153. configurable: true,
  2154. enumerable: false,
  2155. writable: false
  2156. })
  2157. }
  2158. Buffer.poolSize = 8192 // not used by this implementation
  2159. function from (value, encodingOrOffset, length) {
  2160. if (typeof value === 'string') {
  2161. return fromString(value, encodingOrOffset)
  2162. }
  2163. if (ArrayBuffer.isView(value)) {
  2164. return fromArrayLike(value)
  2165. }
  2166. if (value == null) {
  2167. throw TypeError(
  2168. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2169. 'or Array-like Object. Received type ' + (typeof value)
  2170. )
  2171. }
  2172. if (isInstance(value, ArrayBuffer) ||
  2173. (value && isInstance(value.buffer, ArrayBuffer))) {
  2174. return fromArrayBuffer(value, encodingOrOffset, length)
  2175. }
  2176. if (typeof value === 'number') {
  2177. throw new TypeError(
  2178. 'The "value" argument must not be of type number. Received type number'
  2179. )
  2180. }
  2181. var valueOf = value.valueOf && value.valueOf()
  2182. if (valueOf != null && valueOf !== value) {
  2183. return Buffer.from(valueOf, encodingOrOffset, length)
  2184. }
  2185. var b = fromObject(value)
  2186. if (b) return b
  2187. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2188. typeof value[Symbol.toPrimitive] === 'function') {
  2189. return Buffer.from(
  2190. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2191. )
  2192. }
  2193. throw new TypeError(
  2194. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2195. 'or Array-like Object. Received type ' + (typeof value)
  2196. )
  2197. }
  2198. /**
  2199. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2200. * if value is a number.
  2201. * Buffer.from(str[, encoding])
  2202. * Buffer.from(array)
  2203. * Buffer.from(buffer)
  2204. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2205. **/
  2206. Buffer.from = function (value, encodingOrOffset, length) {
  2207. return from(value, encodingOrOffset, length)
  2208. }
  2209. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2210. // https://github.com/feross/buffer/pull/148
  2211. Buffer.prototype.__proto__ = Uint8Array.prototype
  2212. Buffer.__proto__ = Uint8Array
  2213. function assertSize (size) {
  2214. if (typeof size !== 'number') {
  2215. throw new TypeError('"size" argument must be of type number')
  2216. } else if (size < 0) {
  2217. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2218. }
  2219. }
  2220. function alloc (size, fill, encoding) {
  2221. assertSize(size)
  2222. if (size <= 0) {
  2223. return createBuffer(size)
  2224. }
  2225. if (fill !== undefined) {
  2226. // Only pay attention to encoding if it's a string. This
  2227. // prevents accidentally sending in a number that would
  2228. // be interpretted as a start offset.
  2229. return typeof encoding === 'string'
  2230. ? createBuffer(size).fill(fill, encoding)
  2231. : createBuffer(size).fill(fill)
  2232. }
  2233. return createBuffer(size)
  2234. }
  2235. /**
  2236. * Creates a new filled Buffer instance.
  2237. * alloc(size[, fill[, encoding]])
  2238. **/
  2239. Buffer.alloc = function (size, fill, encoding) {
  2240. return alloc(size, fill, encoding)
  2241. }
  2242. function allocUnsafe (size) {
  2243. assertSize(size)
  2244. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2245. }
  2246. /**
  2247. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2248. * */
  2249. Buffer.allocUnsafe = function (size) {
  2250. return allocUnsafe(size)
  2251. }
  2252. /**
  2253. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2254. */
  2255. Buffer.allocUnsafeSlow = function (size) {
  2256. return allocUnsafe(size)
  2257. }
  2258. function fromString (string, encoding) {
  2259. if (typeof encoding !== 'string' || encoding === '') {
  2260. encoding = 'utf8'
  2261. }
  2262. if (!Buffer.isEncoding(encoding)) {
  2263. throw new TypeError('Unknown encoding: ' + encoding)
  2264. }
  2265. var length = byteLength(string, encoding) | 0
  2266. var buf = createBuffer(length)
  2267. var actual = buf.write(string, encoding)
  2268. if (actual !== length) {
  2269. // Writing a hex string, for example, that contains invalid characters will
  2270. // cause everything after the first invalid character to be ignored. (e.g.
  2271. // 'abxxcd' will be treated as 'ab')
  2272. buf = buf.slice(0, actual)
  2273. }
  2274. return buf
  2275. }
  2276. function fromArrayLike (array) {
  2277. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2278. var buf = createBuffer(length)
  2279. for (var i = 0; i < length; i += 1) {
  2280. buf[i] = array[i] & 255
  2281. }
  2282. return buf
  2283. }
  2284. function fromArrayBuffer (array, byteOffset, length) {
  2285. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2286. throw new RangeError('"offset" is outside of buffer bounds')
  2287. }
  2288. if (array.byteLength < byteOffset + (length || 0)) {
  2289. throw new RangeError('"length" is outside of buffer bounds')
  2290. }
  2291. var buf
  2292. if (byteOffset === undefined && length === undefined) {
  2293. buf = new Uint8Array(array)
  2294. } else if (length === undefined) {
  2295. buf = new Uint8Array(array, byteOffset)
  2296. } else {
  2297. buf = new Uint8Array(array, byteOffset, length)
  2298. }
  2299. // Return an augmented `Uint8Array` instance
  2300. buf.__proto__ = Buffer.prototype
  2301. return buf
  2302. }
  2303. function fromObject (obj) {
  2304. if (Buffer.isBuffer(obj)) {
  2305. var len = checked(obj.length) | 0
  2306. var buf = createBuffer(len)
  2307. if (buf.length === 0) {
  2308. return buf
  2309. }
  2310. obj.copy(buf, 0, 0, len)
  2311. return buf
  2312. }
  2313. if (obj.length !== undefined) {
  2314. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2315. return createBuffer(0)
  2316. }
  2317. return fromArrayLike(obj)
  2318. }
  2319. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2320. return fromArrayLike(obj.data)
  2321. }
  2322. }
  2323. function checked (length) {
  2324. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2325. // length is NaN (which is otherwise coerced to zero.)
  2326. if (length >= K_MAX_LENGTH) {
  2327. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2328. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2329. }
  2330. return length | 0
  2331. }
  2332. function SlowBuffer (length) {
  2333. if (+length != length) { // eslint-disable-line eqeqeq
  2334. length = 0
  2335. }
  2336. return Buffer.alloc(+length)
  2337. }
  2338. Buffer.isBuffer = function isBuffer (b) {
  2339. return b != null && b._isBuffer === true &&
  2340. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2341. }
  2342. Buffer.compare = function compare (a, b) {
  2343. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2344. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2345. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2346. throw new TypeError(
  2347. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2348. )
  2349. }
  2350. if (a === b) return 0
  2351. var x = a.length
  2352. var y = b.length
  2353. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2354. if (a[i] !== b[i]) {
  2355. x = a[i]
  2356. y = b[i]
  2357. break
  2358. }
  2359. }
  2360. if (x < y) return -1
  2361. if (y < x) return 1
  2362. return 0
  2363. }
  2364. Buffer.isEncoding = function isEncoding (encoding) {
  2365. switch (String(encoding).toLowerCase()) {
  2366. case 'hex':
  2367. case 'utf8':
  2368. case 'utf-8':
  2369. case 'ascii':
  2370. case 'latin1':
  2371. case 'binary':
  2372. case 'base64':
  2373. case 'ucs2':
  2374. case 'ucs-2':
  2375. case 'utf16le':
  2376. case 'utf-16le':
  2377. return true
  2378. default:
  2379. return false
  2380. }
  2381. }
  2382. Buffer.concat = function concat (list, length) {
  2383. if (!Array.isArray(list)) {
  2384. throw new TypeError('"list" argument must be an Array of Buffers')
  2385. }
  2386. if (list.length === 0) {
  2387. return Buffer.alloc(0)
  2388. }
  2389. var i
  2390. if (length === undefined) {
  2391. length = 0
  2392. for (i = 0; i < list.length; ++i) {
  2393. length += list[i].length
  2394. }
  2395. }
  2396. var buffer = Buffer.allocUnsafe(length)
  2397. var pos = 0
  2398. for (i = 0; i < list.length; ++i) {
  2399. var buf = list[i]
  2400. if (isInstance(buf, Uint8Array)) {
  2401. buf = Buffer.from(buf)
  2402. }
  2403. if (!Buffer.isBuffer(buf)) {
  2404. throw new TypeError('"list" argument must be an Array of Buffers')
  2405. }
  2406. buf.copy(buffer, pos)
  2407. pos += buf.length
  2408. }
  2409. return buffer
  2410. }
  2411. function byteLength (string, encoding) {
  2412. if (Buffer.isBuffer(string)) {
  2413. return string.length
  2414. }
  2415. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2416. return string.byteLength
  2417. }
  2418. if (typeof string !== 'string') {
  2419. throw new TypeError(
  2420. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2421. 'Received type ' + typeof string
  2422. )
  2423. }
  2424. var len = string.length
  2425. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2426. if (!mustMatch && len === 0) return 0
  2427. // Use a for loop to avoid recursion
  2428. var loweredCase = false
  2429. for (;;) {
  2430. switch (encoding) {
  2431. case 'ascii':
  2432. case 'latin1':
  2433. case 'binary':
  2434. return len
  2435. case 'utf8':
  2436. case 'utf-8':
  2437. return utf8ToBytes(string).length
  2438. case 'ucs2':
  2439. case 'ucs-2':
  2440. case 'utf16le':
  2441. case 'utf-16le':
  2442. return len * 2
  2443. case 'hex':
  2444. return len >>> 1
  2445. case 'base64':
  2446. return base64ToBytes(string).length
  2447. default:
  2448. if (loweredCase) {
  2449. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2450. }
  2451. encoding = ('' + encoding).toLowerCase()
  2452. loweredCase = true
  2453. }
  2454. }
  2455. }
  2456. Buffer.byteLength = byteLength
  2457. function slowToString (encoding, start, end) {
  2458. var loweredCase = false
  2459. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2460. // property of a typed array.
  2461. // This behaves neither like String nor Uint8Array in that we set start/end
  2462. // to their upper/lower bounds if the value passed is out of range.
  2463. // undefined is handled specially as per ECMA-262 6th Edition,
  2464. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2465. if (start === undefined || start < 0) {
  2466. start = 0
  2467. }
  2468. // Return early if start > this.length. Done here to prevent potential uint32
  2469. // coercion fail below.
  2470. if (start > this.length) {
  2471. return ''
  2472. }
  2473. if (end === undefined || end > this.length) {
  2474. end = this.length
  2475. }
  2476. if (end <= 0) {
  2477. return ''
  2478. }
  2479. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2480. end >>>= 0
  2481. start >>>= 0
  2482. if (end <= start) {
  2483. return ''
  2484. }
  2485. if (!encoding) encoding = 'utf8'
  2486. while (true) {
  2487. switch (encoding) {
  2488. case 'hex':
  2489. return hexSlice(this, start, end)
  2490. case 'utf8':
  2491. case 'utf-8':
  2492. return utf8Slice(this, start, end)
  2493. case 'ascii':
  2494. return asciiSlice(this, start, end)
  2495. case 'latin1':
  2496. case 'binary':
  2497. return latin1Slice(this, start, end)
  2498. case 'base64':
  2499. return base64Slice(this, start, end)
  2500. case 'ucs2':
  2501. case 'ucs-2':
  2502. case 'utf16le':
  2503. case 'utf-16le':
  2504. return utf16leSlice(this, start, end)
  2505. default:
  2506. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2507. encoding = (encoding + '').toLowerCase()
  2508. loweredCase = true
  2509. }
  2510. }
  2511. }
  2512. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2513. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2514. // reliably in a browserify context because there could be multiple different
  2515. // copies of the 'buffer' package in use. This method works even for Buffer
  2516. // instances that were created from another copy of the `buffer` package.
  2517. // See: https://github.com/feross/buffer/issues/154
  2518. Buffer.prototype._isBuffer = true
  2519. function swap (b, n, m) {
  2520. var i = b[n]
  2521. b[n] = b[m]
  2522. b[m] = i
  2523. }
  2524. Buffer.prototype.swap16 = function swap16 () {
  2525. var len = this.length
  2526. if (len % 2 !== 0) {
  2527. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2528. }
  2529. for (var i = 0; i < len; i += 2) {
  2530. swap(this, i, i + 1)
  2531. }
  2532. return this
  2533. }
  2534. Buffer.prototype.swap32 = function swap32 () {
  2535. var len = this.length
  2536. if (len % 4 !== 0) {
  2537. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2538. }
  2539. for (var i = 0; i < len; i += 4) {
  2540. swap(this, i, i + 3)
  2541. swap(this, i + 1, i + 2)
  2542. }
  2543. return this
  2544. }
  2545. Buffer.prototype.swap64 = function swap64 () {
  2546. var len = this.length
  2547. if (len % 8 !== 0) {
  2548. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2549. }
  2550. for (var i = 0; i < len; i += 8) {
  2551. swap(this, i, i + 7)
  2552. swap(this, i + 1, i + 6)
  2553. swap(this, i + 2, i + 5)
  2554. swap(this, i + 3, i + 4)
  2555. }
  2556. return this
  2557. }
  2558. Buffer.prototype.toString = function toString () {
  2559. var length = this.length
  2560. if (length === 0) return ''
  2561. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2562. return slowToString.apply(this, arguments)
  2563. }
  2564. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2565. Buffer.prototype.equals = function equals (b) {
  2566. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2567. if (this === b) return true
  2568. return Buffer.compare(this, b) === 0
  2569. }
  2570. Buffer.prototype.inspect = function inspect () {
  2571. var str = ''
  2572. var max = exports.INSPECT_MAX_BYTES
  2573. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2574. if (this.length > max) str += ' ... '
  2575. return '<Buffer ' + str + '>'
  2576. }
  2577. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2578. if (isInstance(target, Uint8Array)) {
  2579. target = Buffer.from(target, target.offset, target.byteLength)
  2580. }
  2581. if (!Buffer.isBuffer(target)) {
  2582. throw new TypeError(
  2583. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2584. 'Received type ' + (typeof target)
  2585. )
  2586. }
  2587. if (start === undefined) {
  2588. start = 0
  2589. }
  2590. if (end === undefined) {
  2591. end = target ? target.length : 0
  2592. }
  2593. if (thisStart === undefined) {
  2594. thisStart = 0
  2595. }
  2596. if (thisEnd === undefined) {
  2597. thisEnd = this.length
  2598. }
  2599. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2600. throw new RangeError('out of range index')
  2601. }
  2602. if (thisStart >= thisEnd && start >= end) {
  2603. return 0
  2604. }
  2605. if (thisStart >= thisEnd) {
  2606. return -1
  2607. }
  2608. if (start >= end) {
  2609. return 1
  2610. }
  2611. start >>>= 0
  2612. end >>>= 0
  2613. thisStart >>>= 0
  2614. thisEnd >>>= 0
  2615. if (this === target) return 0
  2616. var x = thisEnd - thisStart
  2617. var y = end - start
  2618. var len = Math.min(x, y)
  2619. var thisCopy = this.slice(thisStart, thisEnd)
  2620. var targetCopy = target.slice(start, end)
  2621. for (var i = 0; i < len; ++i) {
  2622. if (thisCopy[i] !== targetCopy[i]) {
  2623. x = thisCopy[i]
  2624. y = targetCopy[i]
  2625. break
  2626. }
  2627. }
  2628. if (x < y) return -1
  2629. if (y < x) return 1
  2630. return 0
  2631. }
  2632. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2633. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2634. //
  2635. // Arguments:
  2636. // - buffer - a Buffer to search
  2637. // - val - a string, Buffer, or number
  2638. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2639. // - encoding - an optional encoding, relevant is val is a string
  2640. // - dir - true for indexOf, false for lastIndexOf
  2641. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2642. // Empty buffer means no match
  2643. if (buffer.length === 0) return -1
  2644. // Normalize byteOffset
  2645. if (typeof byteOffset === 'string') {
  2646. encoding = byteOffset
  2647. byteOffset = 0
  2648. } else if (byteOffset > 0x7fffffff) {
  2649. byteOffset = 0x7fffffff
  2650. } else if (byteOffset < -0x80000000) {
  2651. byteOffset = -0x80000000
  2652. }
  2653. byteOffset = +byteOffset // Coerce to Number.
  2654. if (numberIsNaN(byteOffset)) {
  2655. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2656. byteOffset = dir ? 0 : (buffer.length - 1)
  2657. }
  2658. // Normalize byteOffset: negative offsets start from the end of the buffer
  2659. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2660. if (byteOffset >= buffer.length) {
  2661. if (dir) return -1
  2662. else byteOffset = buffer.length - 1
  2663. } else if (byteOffset < 0) {
  2664. if (dir) byteOffset = 0
  2665. else return -1
  2666. }
  2667. // Normalize val
  2668. if (typeof val === 'string') {
  2669. val = Buffer.from(val, encoding)
  2670. }
  2671. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2672. if (Buffer.isBuffer(val)) {
  2673. // Special case: looking for empty string/buffer always fails
  2674. if (val.length === 0) {
  2675. return -1
  2676. }
  2677. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2678. } else if (typeof val === 'number') {
  2679. val = val & 0xFF // Search for a byte value [0-255]
  2680. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2681. if (dir) {
  2682. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2683. } else {
  2684. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2685. }
  2686. }
  2687. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2688. }
  2689. throw new TypeError('val must be string, number or Buffer')
  2690. }
  2691. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2692. var indexSize = 1
  2693. var arrLength = arr.length
  2694. var valLength = val.length
  2695. if (encoding !== undefined) {
  2696. encoding = String(encoding).toLowerCase()
  2697. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2698. encoding === 'utf16le' || encoding === 'utf-16le') {
  2699. if (arr.length < 2 || val.length < 2) {
  2700. return -1
  2701. }
  2702. indexSize = 2
  2703. arrLength /= 2
  2704. valLength /= 2
  2705. byteOffset /= 2
  2706. }
  2707. }
  2708. function read (buf, i) {
  2709. if (indexSize === 1) {
  2710. return buf[i]
  2711. } else {
  2712. return buf.readUInt16BE(i * indexSize)
  2713. }
  2714. }
  2715. var i
  2716. if (dir) {
  2717. var foundIndex = -1
  2718. for (i = byteOffset; i < arrLength; i++) {
  2719. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2720. if (foundIndex === -1) foundIndex = i
  2721. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2722. } else {
  2723. if (foundIndex !== -1) i -= i - foundIndex
  2724. foundIndex = -1
  2725. }
  2726. }
  2727. } else {
  2728. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2729. for (i = byteOffset; i >= 0; i--) {
  2730. var found = true
  2731. for (var j = 0; j < valLength; j++) {
  2732. if (read(arr, i + j) !== read(val, j)) {
  2733. found = false
  2734. break
  2735. }
  2736. }
  2737. if (found) return i
  2738. }
  2739. }
  2740. return -1
  2741. }
  2742. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2743. return this.indexOf(val, byteOffset, encoding) !== -1
  2744. }
  2745. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2746. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2747. }
  2748. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2749. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2750. }
  2751. function hexWrite (buf, string, offset, length) {
  2752. offset = Number(offset) || 0
  2753. var remaining = buf.length - offset
  2754. if (!length) {
  2755. length = remaining
  2756. } else {
  2757. length = Number(length)
  2758. if (length > remaining) {
  2759. length = remaining
  2760. }
  2761. }
  2762. var strLen = string.length
  2763. if (length > strLen / 2) {
  2764. length = strLen / 2
  2765. }
  2766. for (var i = 0; i < length; ++i) {
  2767. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2768. if (numberIsNaN(parsed)) return i
  2769. buf[offset + i] = parsed
  2770. }
  2771. return i
  2772. }
  2773. function utf8Write (buf, string, offset, length) {
  2774. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2775. }
  2776. function asciiWrite (buf, string, offset, length) {
  2777. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2778. }
  2779. function latin1Write (buf, string, offset, length) {
  2780. return asciiWrite(buf, string, offset, length)
  2781. }
  2782. function base64Write (buf, string, offset, length) {
  2783. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2784. }
  2785. function ucs2Write (buf, string, offset, length) {
  2786. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2787. }
  2788. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2789. // Buffer#write(string)
  2790. if (offset === undefined) {
  2791. encoding = 'utf8'
  2792. length = this.length
  2793. offset = 0
  2794. // Buffer#write(string, encoding)
  2795. } else if (length === undefined && typeof offset === 'string') {
  2796. encoding = offset
  2797. length = this.length
  2798. offset = 0
  2799. // Buffer#write(string, offset[, length][, encoding])
  2800. } else if (isFinite(offset)) {
  2801. offset = offset >>> 0
  2802. if (isFinite(length)) {
  2803. length = length >>> 0
  2804. if (encoding === undefined) encoding = 'utf8'
  2805. } else {
  2806. encoding = length
  2807. length = undefined
  2808. }
  2809. } else {
  2810. throw new Error(
  2811. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2812. )
  2813. }
  2814. var remaining = this.length - offset
  2815. if (length === undefined || length > remaining) length = remaining
  2816. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2817. throw new RangeError('Attempt to write outside buffer bounds')
  2818. }
  2819. if (!encoding) encoding = 'utf8'
  2820. var loweredCase = false
  2821. for (;;) {
  2822. switch (encoding) {
  2823. case 'hex':
  2824. return hexWrite(this, string, offset, length)
  2825. case 'utf8':
  2826. case 'utf-8':
  2827. return utf8Write(this, string, offset, length)
  2828. case 'ascii':
  2829. return asciiWrite(this, string, offset, length)
  2830. case 'latin1':
  2831. case 'binary':
  2832. return latin1Write(this, string, offset, length)
  2833. case 'base64':
  2834. // Warning: maxLength not taken into account in base64Write
  2835. return base64Write(this, string, offset, length)
  2836. case 'ucs2':
  2837. case 'ucs-2':
  2838. case 'utf16le':
  2839. case 'utf-16le':
  2840. return ucs2Write(this, string, offset, length)
  2841. default:
  2842. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2843. encoding = ('' + encoding).toLowerCase()
  2844. loweredCase = true
  2845. }
  2846. }
  2847. }
  2848. Buffer.prototype.toJSON = function toJSON () {
  2849. return {
  2850. type: 'Buffer',
  2851. data: Array.prototype.slice.call(this._arr || this, 0)
  2852. }
  2853. }
  2854. function base64Slice (buf, start, end) {
  2855. if (start === 0 && end === buf.length) {
  2856. return base64.fromByteArray(buf)
  2857. } else {
  2858. return base64.fromByteArray(buf.slice(start, end))
  2859. }
  2860. }
  2861. function utf8Slice (buf, start, end) {
  2862. end = Math.min(buf.length, end)
  2863. var res = []
  2864. var i = start
  2865. while (i < end) {
  2866. var firstByte = buf[i]
  2867. var codePoint = null
  2868. var bytesPerSequence = (firstByte > 0xEF) ? 4
  2869. : (firstByte > 0xDF) ? 3
  2870. : (firstByte > 0xBF) ? 2
  2871. : 1
  2872. if (i + bytesPerSequence <= end) {
  2873. var secondByte, thirdByte, fourthByte, tempCodePoint
  2874. switch (bytesPerSequence) {
  2875. case 1:
  2876. if (firstByte < 0x80) {
  2877. codePoint = firstByte
  2878. }
  2879. break
  2880. case 2:
  2881. secondByte = buf[i + 1]
  2882. if ((secondByte & 0xC0) === 0x80) {
  2883. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  2884. if (tempCodePoint > 0x7F) {
  2885. codePoint = tempCodePoint
  2886. }
  2887. }
  2888. break
  2889. case 3:
  2890. secondByte = buf[i + 1]
  2891. thirdByte = buf[i + 2]
  2892. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  2893. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  2894. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  2895. codePoint = tempCodePoint
  2896. }
  2897. }
  2898. break
  2899. case 4:
  2900. secondByte = buf[i + 1]
  2901. thirdByte = buf[i + 2]
  2902. fourthByte = buf[i + 3]
  2903. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  2904. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  2905. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  2906. codePoint = tempCodePoint
  2907. }
  2908. }
  2909. }
  2910. }
  2911. if (codePoint === null) {
  2912. // we did not generate a valid codePoint so insert a
  2913. // replacement char (U+FFFD) and advance only 1 byte
  2914. codePoint = 0xFFFD
  2915. bytesPerSequence = 1
  2916. } else if (codePoint > 0xFFFF) {
  2917. // encode to utf16 (surrogate pair dance)
  2918. codePoint -= 0x10000
  2919. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  2920. codePoint = 0xDC00 | codePoint & 0x3FF
  2921. }
  2922. res.push(codePoint)
  2923. i += bytesPerSequence
  2924. }
  2925. return decodeCodePointsArray(res)
  2926. }
  2927. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  2928. // the lowest limit is Chrome, with 0x10000 args.
  2929. // We go 1 magnitude less, for safety
  2930. var MAX_ARGUMENTS_LENGTH = 0x1000
  2931. function decodeCodePointsArray (codePoints) {
  2932. var len = codePoints.length
  2933. if (len <= MAX_ARGUMENTS_LENGTH) {
  2934. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  2935. }
  2936. // Decode in chunks to avoid "call stack size exceeded".
  2937. var res = ''
  2938. var i = 0
  2939. while (i < len) {
  2940. res += String.fromCharCode.apply(
  2941. String,
  2942. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  2943. )
  2944. }
  2945. return res
  2946. }
  2947. function asciiSlice (buf, start, end) {
  2948. var ret = ''
  2949. end = Math.min(buf.length, end)
  2950. for (var i = start; i < end; ++i) {
  2951. ret += String.fromCharCode(buf[i] & 0x7F)
  2952. }
  2953. return ret
  2954. }
  2955. function latin1Slice (buf, start, end) {
  2956. var ret = ''
  2957. end = Math.min(buf.length, end)
  2958. for (var i = start; i < end; ++i) {
  2959. ret += String.fromCharCode(buf[i])
  2960. }
  2961. return ret
  2962. }
  2963. function hexSlice (buf, start, end) {
  2964. var len = buf.length
  2965. if (!start || start < 0) start = 0
  2966. if (!end || end < 0 || end > len) end = len
  2967. var out = ''
  2968. for (var i = start; i < end; ++i) {
  2969. out += toHex(buf[i])
  2970. }
  2971. return out
  2972. }
  2973. function utf16leSlice (buf, start, end) {
  2974. var bytes = buf.slice(start, end)
  2975. var res = ''
  2976. for (var i = 0; i < bytes.length; i += 2) {
  2977. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  2978. }
  2979. return res
  2980. }
  2981. Buffer.prototype.slice = function slice (start, end) {
  2982. var len = this.length
  2983. start = ~~start
  2984. end = end === undefined ? len : ~~end
  2985. if (start < 0) {
  2986. start += len
  2987. if (start < 0) start = 0
  2988. } else if (start > len) {
  2989. start = len
  2990. }
  2991. if (end < 0) {
  2992. end += len
  2993. if (end < 0) end = 0
  2994. } else if (end > len) {
  2995. end = len
  2996. }
  2997. if (end < start) end = start
  2998. var newBuf = this.subarray(start, end)
  2999. // Return an augmented `Uint8Array` instance
  3000. newBuf.__proto__ = Buffer.prototype
  3001. return newBuf
  3002. }
  3003. /*
  3004. * Need to make sure that buffer isn't trying to write out of bounds.
  3005. */
  3006. function checkOffset (offset, ext, length) {
  3007. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3008. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3009. }
  3010. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3011. offset = offset >>> 0
  3012. byteLength = byteLength >>> 0
  3013. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3014. var val = this[offset]
  3015. var mul = 1
  3016. var i = 0
  3017. while (++i < byteLength && (mul *= 0x100)) {
  3018. val += this[offset + i] * mul
  3019. }
  3020. return val
  3021. }
  3022. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3023. offset = offset >>> 0
  3024. byteLength = byteLength >>> 0
  3025. if (!noAssert) {
  3026. checkOffset(offset, byteLength, this.length)
  3027. }
  3028. var val = this[offset + --byteLength]
  3029. var mul = 1
  3030. while (byteLength > 0 && (mul *= 0x100)) {
  3031. val += this[offset + --byteLength] * mul
  3032. }
  3033. return val
  3034. }
  3035. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3036. offset = offset >>> 0
  3037. if (!noAssert) checkOffset(offset, 1, this.length)
  3038. return this[offset]
  3039. }
  3040. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3041. offset = offset >>> 0
  3042. if (!noAssert) checkOffset(offset, 2, this.length)
  3043. return this[offset] | (this[offset + 1] << 8)
  3044. }
  3045. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3046. offset = offset >>> 0
  3047. if (!noAssert) checkOffset(offset, 2, this.length)
  3048. return (this[offset] << 8) | this[offset + 1]
  3049. }
  3050. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3051. offset = offset >>> 0
  3052. if (!noAssert) checkOffset(offset, 4, this.length)
  3053. return ((this[offset]) |
  3054. (this[offset + 1] << 8) |
  3055. (this[offset + 2] << 16)) +
  3056. (this[offset + 3] * 0x1000000)
  3057. }
  3058. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3059. offset = offset >>> 0
  3060. if (!noAssert) checkOffset(offset, 4, this.length)
  3061. return (this[offset] * 0x1000000) +
  3062. ((this[offset + 1] << 16) |
  3063. (this[offset + 2] << 8) |
  3064. this[offset + 3])
  3065. }
  3066. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3067. offset = offset >>> 0
  3068. byteLength = byteLength >>> 0
  3069. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3070. var val = this[offset]
  3071. var mul = 1
  3072. var i = 0
  3073. while (++i < byteLength && (mul *= 0x100)) {
  3074. val += this[offset + i] * mul
  3075. }
  3076. mul *= 0x80
  3077. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3078. return val
  3079. }
  3080. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3081. offset = offset >>> 0
  3082. byteLength = byteLength >>> 0
  3083. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3084. var i = byteLength
  3085. var mul = 1
  3086. var val = this[offset + --i]
  3087. while (i > 0 && (mul *= 0x100)) {
  3088. val += this[offset + --i] * mul
  3089. }
  3090. mul *= 0x80
  3091. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3092. return val
  3093. }
  3094. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3095. offset = offset >>> 0
  3096. if (!noAssert) checkOffset(offset, 1, this.length)
  3097. if (!(this[offset] & 0x80)) return (this[offset])
  3098. return ((0xff - this[offset] + 1) * -1)
  3099. }
  3100. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3101. offset = offset >>> 0
  3102. if (!noAssert) checkOffset(offset, 2, this.length)
  3103. var val = this[offset] | (this[offset + 1] << 8)
  3104. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3105. }
  3106. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3107. offset = offset >>> 0
  3108. if (!noAssert) checkOffset(offset, 2, this.length)
  3109. var val = this[offset + 1] | (this[offset] << 8)
  3110. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3111. }
  3112. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3113. offset = offset >>> 0
  3114. if (!noAssert) checkOffset(offset, 4, this.length)
  3115. return (this[offset]) |
  3116. (this[offset + 1] << 8) |
  3117. (this[offset + 2] << 16) |
  3118. (this[offset + 3] << 24)
  3119. }
  3120. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3121. offset = offset >>> 0
  3122. if (!noAssert) checkOffset(offset, 4, this.length)
  3123. return (this[offset] << 24) |
  3124. (this[offset + 1] << 16) |
  3125. (this[offset + 2] << 8) |
  3126. (this[offset + 3])
  3127. }
  3128. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3129. offset = offset >>> 0
  3130. if (!noAssert) checkOffset(offset, 4, this.length)
  3131. return ieee754.read(this, offset, true, 23, 4)
  3132. }
  3133. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3134. offset = offset >>> 0
  3135. if (!noAssert) checkOffset(offset, 4, this.length)
  3136. return ieee754.read(this, offset, false, 23, 4)
  3137. }
  3138. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3139. offset = offset >>> 0
  3140. if (!noAssert) checkOffset(offset, 8, this.length)
  3141. return ieee754.read(this, offset, true, 52, 8)
  3142. }
  3143. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3144. offset = offset >>> 0
  3145. if (!noAssert) checkOffset(offset, 8, this.length)
  3146. return ieee754.read(this, offset, false, 52, 8)
  3147. }
  3148. function checkInt (buf, value, offset, ext, max, min) {
  3149. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3150. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3151. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3152. }
  3153. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3154. value = +value
  3155. offset = offset >>> 0
  3156. byteLength = byteLength >>> 0
  3157. if (!noAssert) {
  3158. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3159. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3160. }
  3161. var mul = 1
  3162. var i = 0
  3163. this[offset] = value & 0xFF
  3164. while (++i < byteLength && (mul *= 0x100)) {
  3165. this[offset + i] = (value / mul) & 0xFF
  3166. }
  3167. return offset + byteLength
  3168. }
  3169. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3170. value = +value
  3171. offset = offset >>> 0
  3172. byteLength = byteLength >>> 0
  3173. if (!noAssert) {
  3174. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3175. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3176. }
  3177. var i = byteLength - 1
  3178. var mul = 1
  3179. this[offset + i] = value & 0xFF
  3180. while (--i >= 0 && (mul *= 0x100)) {
  3181. this[offset + i] = (value / mul) & 0xFF
  3182. }
  3183. return offset + byteLength
  3184. }
  3185. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3186. value = +value
  3187. offset = offset >>> 0
  3188. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3189. this[offset] = (value & 0xff)
  3190. return offset + 1
  3191. }
  3192. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3193. value = +value
  3194. offset = offset >>> 0
  3195. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3196. this[offset] = (value & 0xff)
  3197. this[offset + 1] = (value >>> 8)
  3198. return offset + 2
  3199. }
  3200. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3201. value = +value
  3202. offset = offset >>> 0
  3203. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3204. this[offset] = (value >>> 8)
  3205. this[offset + 1] = (value & 0xff)
  3206. return offset + 2
  3207. }
  3208. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3209. value = +value
  3210. offset = offset >>> 0
  3211. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3212. this[offset + 3] = (value >>> 24)
  3213. this[offset + 2] = (value >>> 16)
  3214. this[offset + 1] = (value >>> 8)
  3215. this[offset] = (value & 0xff)
  3216. return offset + 4
  3217. }
  3218. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3219. value = +value
  3220. offset = offset >>> 0
  3221. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3222. this[offset] = (value >>> 24)
  3223. this[offset + 1] = (value >>> 16)
  3224. this[offset + 2] = (value >>> 8)
  3225. this[offset + 3] = (value & 0xff)
  3226. return offset + 4
  3227. }
  3228. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3229. value = +value
  3230. offset = offset >>> 0
  3231. if (!noAssert) {
  3232. var limit = Math.pow(2, (8 * byteLength) - 1)
  3233. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3234. }
  3235. var i = 0
  3236. var mul = 1
  3237. var sub = 0
  3238. this[offset] = value & 0xFF
  3239. while (++i < byteLength && (mul *= 0x100)) {
  3240. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3241. sub = 1
  3242. }
  3243. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3244. }
  3245. return offset + byteLength
  3246. }
  3247. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3248. value = +value
  3249. offset = offset >>> 0
  3250. if (!noAssert) {
  3251. var limit = Math.pow(2, (8 * byteLength) - 1)
  3252. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3253. }
  3254. var i = byteLength - 1
  3255. var mul = 1
  3256. var sub = 0
  3257. this[offset + i] = value & 0xFF
  3258. while (--i >= 0 && (mul *= 0x100)) {
  3259. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3260. sub = 1
  3261. }
  3262. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3263. }
  3264. return offset + byteLength
  3265. }
  3266. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3267. value = +value
  3268. offset = offset >>> 0
  3269. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3270. if (value < 0) value = 0xff + value + 1
  3271. this[offset] = (value & 0xff)
  3272. return offset + 1
  3273. }
  3274. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3275. value = +value
  3276. offset = offset >>> 0
  3277. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3278. this[offset] = (value & 0xff)
  3279. this[offset + 1] = (value >>> 8)
  3280. return offset + 2
  3281. }
  3282. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3283. value = +value
  3284. offset = offset >>> 0
  3285. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3286. this[offset] = (value >>> 8)
  3287. this[offset + 1] = (value & 0xff)
  3288. return offset + 2
  3289. }
  3290. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3291. value = +value
  3292. offset = offset >>> 0
  3293. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3294. this[offset] = (value & 0xff)
  3295. this[offset + 1] = (value >>> 8)
  3296. this[offset + 2] = (value >>> 16)
  3297. this[offset + 3] = (value >>> 24)
  3298. return offset + 4
  3299. }
  3300. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3301. value = +value
  3302. offset = offset >>> 0
  3303. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3304. if (value < 0) value = 0xffffffff + value + 1
  3305. this[offset] = (value >>> 24)
  3306. this[offset + 1] = (value >>> 16)
  3307. this[offset + 2] = (value >>> 8)
  3308. this[offset + 3] = (value & 0xff)
  3309. return offset + 4
  3310. }
  3311. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3312. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3313. if (offset < 0) throw new RangeError('Index out of range')
  3314. }
  3315. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3316. value = +value
  3317. offset = offset >>> 0
  3318. if (!noAssert) {
  3319. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3320. }
  3321. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3322. return offset + 4
  3323. }
  3324. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3325. return writeFloat(this, value, offset, true, noAssert)
  3326. }
  3327. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3328. return writeFloat(this, value, offset, false, noAssert)
  3329. }
  3330. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3331. value = +value
  3332. offset = offset >>> 0
  3333. if (!noAssert) {
  3334. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3335. }
  3336. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3337. return offset + 8
  3338. }
  3339. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3340. return writeDouble(this, value, offset, true, noAssert)
  3341. }
  3342. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3343. return writeDouble(this, value, offset, false, noAssert)
  3344. }
  3345. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3346. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3347. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3348. if (!start) start = 0
  3349. if (!end && end !== 0) end = this.length
  3350. if (targetStart >= target.length) targetStart = target.length
  3351. if (!targetStart) targetStart = 0
  3352. if (end > 0 && end < start) end = start
  3353. // Copy 0 bytes; we're done
  3354. if (end === start) return 0
  3355. if (target.length === 0 || this.length === 0) return 0
  3356. // Fatal error conditions
  3357. if (targetStart < 0) {
  3358. throw new RangeError('targetStart out of bounds')
  3359. }
  3360. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3361. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3362. // Are we oob?
  3363. if (end > this.length) end = this.length
  3364. if (target.length - targetStart < end - start) {
  3365. end = target.length - targetStart + start
  3366. }
  3367. var len = end - start
  3368. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3369. // Use built-in when available, missing from IE11
  3370. this.copyWithin(targetStart, start, end)
  3371. } else if (this === target && start < targetStart && targetStart < end) {
  3372. // descending copy from end
  3373. for (var i = len - 1; i >= 0; --i) {
  3374. target[i + targetStart] = this[i + start]
  3375. }
  3376. } else {
  3377. Uint8Array.prototype.set.call(
  3378. target,
  3379. this.subarray(start, end),
  3380. targetStart
  3381. )
  3382. }
  3383. return len
  3384. }
  3385. // Usage:
  3386. // buffer.fill(number[, offset[, end]])
  3387. // buffer.fill(buffer[, offset[, end]])
  3388. // buffer.fill(string[, offset[, end]][, encoding])
  3389. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3390. // Handle string cases:
  3391. if (typeof val === 'string') {
  3392. if (typeof start === 'string') {
  3393. encoding = start
  3394. start = 0
  3395. end = this.length
  3396. } else if (typeof end === 'string') {
  3397. encoding = end
  3398. end = this.length
  3399. }
  3400. if (encoding !== undefined && typeof encoding !== 'string') {
  3401. throw new TypeError('encoding must be a string')
  3402. }
  3403. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3404. throw new TypeError('Unknown encoding: ' + encoding)
  3405. }
  3406. if (val.length === 1) {
  3407. var code = val.charCodeAt(0)
  3408. if ((encoding === 'utf8' && code < 128) ||
  3409. encoding === 'latin1') {
  3410. // Fast path: If `val` fits into a single byte, use that numeric value.
  3411. val = code
  3412. }
  3413. }
  3414. } else if (typeof val === 'number') {
  3415. val = val & 255
  3416. }
  3417. // Invalid ranges are not set to a default, so can range check early.
  3418. if (start < 0 || this.length < start || this.length < end) {
  3419. throw new RangeError('Out of range index')
  3420. }
  3421. if (end <= start) {
  3422. return this
  3423. }
  3424. start = start >>> 0
  3425. end = end === undefined ? this.length : end >>> 0
  3426. if (!val) val = 0
  3427. var i
  3428. if (typeof val === 'number') {
  3429. for (i = start; i < end; ++i) {
  3430. this[i] = val
  3431. }
  3432. } else {
  3433. var bytes = Buffer.isBuffer(val)
  3434. ? val
  3435. : Buffer.from(val, encoding)
  3436. var len = bytes.length
  3437. if (len === 0) {
  3438. throw new TypeError('The value "' + val +
  3439. '" is invalid for argument "value"')
  3440. }
  3441. for (i = 0; i < end - start; ++i) {
  3442. this[i + start] = bytes[i % len]
  3443. }
  3444. }
  3445. return this
  3446. }
  3447. // HELPER FUNCTIONS
  3448. // ================
  3449. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3450. function base64clean (str) {
  3451. // Node takes equal signs as end of the Base64 encoding
  3452. str = str.split('=')[0]
  3453. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3454. str = str.trim().replace(INVALID_BASE64_RE, '')
  3455. // Node converts strings with length < 2 to ''
  3456. if (str.length < 2) return ''
  3457. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3458. while (str.length % 4 !== 0) {
  3459. str = str + '='
  3460. }
  3461. return str
  3462. }
  3463. function toHex (n) {
  3464. if (n < 16) return '0' + n.toString(16)
  3465. return n.toString(16)
  3466. }
  3467. function utf8ToBytes (string, units) {
  3468. units = units || Infinity
  3469. var codePoint
  3470. var length = string.length
  3471. var leadSurrogate = null
  3472. var bytes = []
  3473. for (var i = 0; i < length; ++i) {
  3474. codePoint = string.charCodeAt(i)
  3475. // is surrogate component
  3476. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3477. // last char was a lead
  3478. if (!leadSurrogate) {
  3479. // no lead yet
  3480. if (codePoint > 0xDBFF) {
  3481. // unexpected trail
  3482. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3483. continue
  3484. } else if (i + 1 === length) {
  3485. // unpaired lead
  3486. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3487. continue
  3488. }
  3489. // valid lead
  3490. leadSurrogate = codePoint
  3491. continue
  3492. }
  3493. // 2 leads in a row
  3494. if (codePoint < 0xDC00) {
  3495. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3496. leadSurrogate = codePoint
  3497. continue
  3498. }
  3499. // valid surrogate pair
  3500. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3501. } else if (leadSurrogate) {
  3502. // valid bmp char, but last char was a lead
  3503. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3504. }
  3505. leadSurrogate = null
  3506. // encode utf8
  3507. if (codePoint < 0x80) {
  3508. if ((units -= 1) < 0) break
  3509. bytes.push(codePoint)
  3510. } else if (codePoint < 0x800) {
  3511. if ((units -= 2) < 0) break
  3512. bytes.push(
  3513. codePoint >> 0x6 | 0xC0,
  3514. codePoint & 0x3F | 0x80
  3515. )
  3516. } else if (codePoint < 0x10000) {
  3517. if ((units -= 3) < 0) break
  3518. bytes.push(
  3519. codePoint >> 0xC | 0xE0,
  3520. codePoint >> 0x6 & 0x3F | 0x80,
  3521. codePoint & 0x3F | 0x80
  3522. )
  3523. } else if (codePoint < 0x110000) {
  3524. if ((units -= 4) < 0) break
  3525. bytes.push(
  3526. codePoint >> 0x12 | 0xF0,
  3527. codePoint >> 0xC & 0x3F | 0x80,
  3528. codePoint >> 0x6 & 0x3F | 0x80,
  3529. codePoint & 0x3F | 0x80
  3530. )
  3531. } else {
  3532. throw new Error('Invalid code point')
  3533. }
  3534. }
  3535. return bytes
  3536. }
  3537. function asciiToBytes (str) {
  3538. var byteArray = []
  3539. for (var i = 0; i < str.length; ++i) {
  3540. // Node's code seems to be doing this and not & 0x7F..
  3541. byteArray.push(str.charCodeAt(i) & 0xFF)
  3542. }
  3543. return byteArray
  3544. }
  3545. function utf16leToBytes (str, units) {
  3546. var c, hi, lo
  3547. var byteArray = []
  3548. for (var i = 0; i < str.length; ++i) {
  3549. if ((units -= 2) < 0) break
  3550. c = str.charCodeAt(i)
  3551. hi = c >> 8
  3552. lo = c % 256
  3553. byteArray.push(lo)
  3554. byteArray.push(hi)
  3555. }
  3556. return byteArray
  3557. }
  3558. function base64ToBytes (str) {
  3559. return base64.toByteArray(base64clean(str))
  3560. }
  3561. function blitBuffer (src, dst, offset, length) {
  3562. for (var i = 0; i < length; ++i) {
  3563. if ((i + offset >= dst.length) || (i >= src.length)) break
  3564. dst[i + offset] = src[i]
  3565. }
  3566. return i
  3567. }
  3568. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3569. // the `instanceof` check but they should be treated as of that type.
  3570. // See: https://github.com/feross/buffer/issues/166
  3571. function isInstance (obj, type) {
  3572. return obj instanceof type ||
  3573. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3574. obj.constructor.name === type.name)
  3575. }
  3576. function numberIsNaN (obj) {
  3577. // For IE11 support
  3578. return obj !== obj // eslint-disable-line no-self-compare
  3579. }
  3580. },{"base64-js":10,"ieee754":79}],13:[function(require,module,exports){
  3581. // Copyright Joyent, Inc. and other Node contributors.
  3582. //
  3583. // Permission is hereby granted, free of charge, to any person obtaining a
  3584. // copy of this software and associated documentation files (the
  3585. // "Software"), to deal in the Software without restriction, including
  3586. // without limitation the rights to use, copy, modify, merge, publish,
  3587. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3588. // persons to whom the Software is furnished to do so, subject to the
  3589. // following conditions:
  3590. //
  3591. // The above copyright notice and this permission notice shall be included
  3592. // in all copies or substantial portions of the Software.
  3593. //
  3594. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3595. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3596. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3597. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3598. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3599. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3600. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3601. var objectCreate = Object.create || objectCreatePolyfill
  3602. var objectKeys = Object.keys || objectKeysPolyfill
  3603. var bind = Function.prototype.bind || functionBindPolyfill
  3604. function EventEmitter() {
  3605. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  3606. this._events = objectCreate(null);
  3607. this._eventsCount = 0;
  3608. }
  3609. this._maxListeners = this._maxListeners || undefined;
  3610. }
  3611. module.exports = EventEmitter;
  3612. // Backwards-compat with node 0.10.x
  3613. EventEmitter.EventEmitter = EventEmitter;
  3614. EventEmitter.prototype._events = undefined;
  3615. EventEmitter.prototype._maxListeners = undefined;
  3616. // By default EventEmitters will print a warning if more than 10 listeners are
  3617. // added to it. This is a useful default which helps finding memory leaks.
  3618. var defaultMaxListeners = 10;
  3619. var hasDefineProperty;
  3620. try {
  3621. var o = {};
  3622. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  3623. hasDefineProperty = o.x === 0;
  3624. } catch (err) { hasDefineProperty = false }
  3625. if (hasDefineProperty) {
  3626. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  3627. enumerable: true,
  3628. get: function() {
  3629. return defaultMaxListeners;
  3630. },
  3631. set: function(arg) {
  3632. // check whether the input is a positive number (whose value is zero or
  3633. // greater and not a NaN).
  3634. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  3635. throw new TypeError('"defaultMaxListeners" must be a positive number');
  3636. defaultMaxListeners = arg;
  3637. }
  3638. });
  3639. } else {
  3640. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  3641. }
  3642. // Obviously not all Emitters should be limited to 10. This function allows
  3643. // that to be increased. Set to zero for unlimited.
  3644. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  3645. if (typeof n !== 'number' || n < 0 || isNaN(n))
  3646. throw new TypeError('"n" argument must be a positive number');
  3647. this._maxListeners = n;
  3648. return this;
  3649. };
  3650. function $getMaxListeners(that) {
  3651. if (that._maxListeners === undefined)
  3652. return EventEmitter.defaultMaxListeners;
  3653. return that._maxListeners;
  3654. }
  3655. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  3656. return $getMaxListeners(this);
  3657. };
  3658. // These standalone emit* functions are used to optimize calling of event
  3659. // handlers for fast cases because emit() itself often has a variable number of
  3660. // arguments and can be deoptimized because of that. These functions always have
  3661. // the same number of arguments and thus do not get deoptimized, so the code
  3662. // inside them can execute faster.
  3663. function emitNone(handler, isFn, self) {
  3664. if (isFn)
  3665. handler.call(self);
  3666. else {
  3667. var len = handler.length;
  3668. var listeners = arrayClone(handler, len);
  3669. for (var i = 0; i < len; ++i)
  3670. listeners[i].call(self);
  3671. }
  3672. }
  3673. function emitOne(handler, isFn, self, arg1) {
  3674. if (isFn)
  3675. handler.call(self, arg1);
  3676. else {
  3677. var len = handler.length;
  3678. var listeners = arrayClone(handler, len);
  3679. for (var i = 0; i < len; ++i)
  3680. listeners[i].call(self, arg1);
  3681. }
  3682. }
  3683. function emitTwo(handler, isFn, self, arg1, arg2) {
  3684. if (isFn)
  3685. handler.call(self, arg1, arg2);
  3686. else {
  3687. var len = handler.length;
  3688. var listeners = arrayClone(handler, len);
  3689. for (var i = 0; i < len; ++i)
  3690. listeners[i].call(self, arg1, arg2);
  3691. }
  3692. }
  3693. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  3694. if (isFn)
  3695. handler.call(self, arg1, arg2, arg3);
  3696. else {
  3697. var len = handler.length;
  3698. var listeners = arrayClone(handler, len);
  3699. for (var i = 0; i < len; ++i)
  3700. listeners[i].call(self, arg1, arg2, arg3);
  3701. }
  3702. }
  3703. function emitMany(handler, isFn, self, args) {
  3704. if (isFn)
  3705. handler.apply(self, args);
  3706. else {
  3707. var len = handler.length;
  3708. var listeners = arrayClone(handler, len);
  3709. for (var i = 0; i < len; ++i)
  3710. listeners[i].apply(self, args);
  3711. }
  3712. }
  3713. EventEmitter.prototype.emit = function emit(type) {
  3714. var er, handler, len, args, i, events;
  3715. var doError = (type === 'error');
  3716. events = this._events;
  3717. if (events)
  3718. doError = (doError && events.error == null);
  3719. else if (!doError)
  3720. return false;
  3721. // If there is no 'error' event listener then throw.
  3722. if (doError) {
  3723. if (arguments.length > 1)
  3724. er = arguments[1];
  3725. if (er instanceof Error) {
  3726. throw er; // Unhandled 'error' event
  3727. } else {
  3728. // At least give some kind of context to the user
  3729. var err = new Error('Unhandled "error" event. (' + er + ')');
  3730. err.context = er;
  3731. throw err;
  3732. }
  3733. return false;
  3734. }
  3735. handler = events[type];
  3736. if (!handler)
  3737. return false;
  3738. var isFn = typeof handler === 'function';
  3739. len = arguments.length;
  3740. switch (len) {
  3741. // fast cases
  3742. case 1:
  3743. emitNone(handler, isFn, this);
  3744. break;
  3745. case 2:
  3746. emitOne(handler, isFn, this, arguments[1]);
  3747. break;
  3748. case 3:
  3749. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  3750. break;
  3751. case 4:
  3752. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  3753. break;
  3754. // slower
  3755. default:
  3756. args = new Array(len - 1);
  3757. for (i = 1; i < len; i++)
  3758. args[i - 1] = arguments[i];
  3759. emitMany(handler, isFn, this, args);
  3760. }
  3761. return true;
  3762. };
  3763. function _addListener(target, type, listener, prepend) {
  3764. var m;
  3765. var events;
  3766. var existing;
  3767. if (typeof listener !== 'function')
  3768. throw new TypeError('"listener" argument must be a function');
  3769. events = target._events;
  3770. if (!events) {
  3771. events = target._events = objectCreate(null);
  3772. target._eventsCount = 0;
  3773. } else {
  3774. // To avoid recursion in the case that type === "newListener"! Before
  3775. // adding it to the listeners, first emit "newListener".
  3776. if (events.newListener) {
  3777. target.emit('newListener', type,
  3778. listener.listener ? listener.listener : listener);
  3779. // Re-assign `events` because a newListener handler could have caused the
  3780. // this._events to be assigned to a new object
  3781. events = target._events;
  3782. }
  3783. existing = events[type];
  3784. }
  3785. if (!existing) {
  3786. // Optimize the case of one listener. Don't need the extra array object.
  3787. existing = events[type] = listener;
  3788. ++target._eventsCount;
  3789. } else {
  3790. if (typeof existing === 'function') {
  3791. // Adding the second element, need to change to array.
  3792. existing = events[type] =
  3793. prepend ? [listener, existing] : [existing, listener];
  3794. } else {
  3795. // If we've already got an array, just append.
  3796. if (prepend) {
  3797. existing.unshift(listener);
  3798. } else {
  3799. existing.push(listener);
  3800. }
  3801. }
  3802. // Check for listener leak
  3803. if (!existing.warned) {
  3804. m = $getMaxListeners(target);
  3805. if (m && m > 0 && existing.length > m) {
  3806. existing.warned = true;
  3807. var w = new Error('Possible EventEmitter memory leak detected. ' +
  3808. existing.length + ' "' + String(type) + '" listeners ' +
  3809. 'added. Use emitter.setMaxListeners() to ' +
  3810. 'increase limit.');
  3811. w.name = 'MaxListenersExceededWarning';
  3812. w.emitter = target;
  3813. w.type = type;
  3814. w.count = existing.length;
  3815. if (typeof console === 'object' && console.warn) {
  3816. console.warn('%s: %s', w.name, w.message);
  3817. }
  3818. }
  3819. }
  3820. }
  3821. return target;
  3822. }
  3823. EventEmitter.prototype.addListener = function addListener(type, listener) {
  3824. return _addListener(this, type, listener, false);
  3825. };
  3826. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  3827. EventEmitter.prototype.prependListener =
  3828. function prependListener(type, listener) {
  3829. return _addListener(this, type, listener, true);
  3830. };
  3831. function onceWrapper() {
  3832. if (!this.fired) {
  3833. this.target.removeListener(this.type, this.wrapFn);
  3834. this.fired = true;
  3835. switch (arguments.length) {
  3836. case 0:
  3837. return this.listener.call(this.target);
  3838. case 1:
  3839. return this.listener.call(this.target, arguments[0]);
  3840. case 2:
  3841. return this.listener.call(this.target, arguments[0], arguments[1]);
  3842. case 3:
  3843. return this.listener.call(this.target, arguments[0], arguments[1],
  3844. arguments[2]);
  3845. default:
  3846. var args = new Array(arguments.length);
  3847. for (var i = 0; i < args.length; ++i)
  3848. args[i] = arguments[i];
  3849. this.listener.apply(this.target, args);
  3850. }
  3851. }
  3852. }
  3853. function _onceWrap(target, type, listener) {
  3854. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  3855. var wrapped = bind.call(onceWrapper, state);
  3856. wrapped.listener = listener;
  3857. state.wrapFn = wrapped;
  3858. return wrapped;
  3859. }
  3860. EventEmitter.prototype.once = function once(type, listener) {
  3861. if (typeof listener !== 'function')
  3862. throw new TypeError('"listener" argument must be a function');
  3863. this.on(type, _onceWrap(this, type, listener));
  3864. return this;
  3865. };
  3866. EventEmitter.prototype.prependOnceListener =
  3867. function prependOnceListener(type, listener) {
  3868. if (typeof listener !== 'function')
  3869. throw new TypeError('"listener" argument must be a function');
  3870. this.prependListener(type, _onceWrap(this, type, listener));
  3871. return this;
  3872. };
  3873. // Emits a 'removeListener' event if and only if the listener was removed.
  3874. EventEmitter.prototype.removeListener =
  3875. function removeListener(type, listener) {
  3876. var list, events, position, i, originalListener;
  3877. if (typeof listener !== 'function')
  3878. throw new TypeError('"listener" argument must be a function');
  3879. events = this._events;
  3880. if (!events)
  3881. return this;
  3882. list = events[type];
  3883. if (!list)
  3884. return this;
  3885. if (list === listener || list.listener === listener) {
  3886. if (--this._eventsCount === 0)
  3887. this._events = objectCreate(null);
  3888. else {
  3889. delete events[type];
  3890. if (events.removeListener)
  3891. this.emit('removeListener', type, list.listener || listener);
  3892. }
  3893. } else if (typeof list !== 'function') {
  3894. position = -1;
  3895. for (i = list.length - 1; i >= 0; i--) {
  3896. if (list[i] === listener || list[i].listener === listener) {
  3897. originalListener = list[i].listener;
  3898. position = i;
  3899. break;
  3900. }
  3901. }
  3902. if (position < 0)
  3903. return this;
  3904. if (position === 0)
  3905. list.shift();
  3906. else
  3907. spliceOne(list, position);
  3908. if (list.length === 1)
  3909. events[type] = list[0];
  3910. if (events.removeListener)
  3911. this.emit('removeListener', type, originalListener || listener);
  3912. }
  3913. return this;
  3914. };
  3915. EventEmitter.prototype.removeAllListeners =
  3916. function removeAllListeners(type) {
  3917. var listeners, events, i;
  3918. events = this._events;
  3919. if (!events)
  3920. return this;
  3921. // not listening for removeListener, no need to emit
  3922. if (!events.removeListener) {
  3923. if (arguments.length === 0) {
  3924. this._events = objectCreate(null);
  3925. this._eventsCount = 0;
  3926. } else if (events[type]) {
  3927. if (--this._eventsCount === 0)
  3928. this._events = objectCreate(null);
  3929. else
  3930. delete events[type];
  3931. }
  3932. return this;
  3933. }
  3934. // emit removeListener for all listeners on all events
  3935. if (arguments.length === 0) {
  3936. var keys = objectKeys(events);
  3937. var key;
  3938. for (i = 0; i < keys.length; ++i) {
  3939. key = keys[i];
  3940. if (key === 'removeListener') continue;
  3941. this.removeAllListeners(key);
  3942. }
  3943. this.removeAllListeners('removeListener');
  3944. this._events = objectCreate(null);
  3945. this._eventsCount = 0;
  3946. return this;
  3947. }
  3948. listeners = events[type];
  3949. if (typeof listeners === 'function') {
  3950. this.removeListener(type, listeners);
  3951. } else if (listeners) {
  3952. // LIFO order
  3953. for (i = listeners.length - 1; i >= 0; i--) {
  3954. this.removeListener(type, listeners[i]);
  3955. }
  3956. }
  3957. return this;
  3958. };
  3959. function _listeners(target, type, unwrap) {
  3960. var events = target._events;
  3961. if (!events)
  3962. return [];
  3963. var evlistener = events[type];
  3964. if (!evlistener)
  3965. return [];
  3966. if (typeof evlistener === 'function')
  3967. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  3968. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  3969. }
  3970. EventEmitter.prototype.listeners = function listeners(type) {
  3971. return _listeners(this, type, true);
  3972. };
  3973. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  3974. return _listeners(this, type, false);
  3975. };
  3976. EventEmitter.listenerCount = function(emitter, type) {
  3977. if (typeof emitter.listenerCount === 'function') {
  3978. return emitter.listenerCount(type);
  3979. } else {
  3980. return listenerCount.call(emitter, type);
  3981. }
  3982. };
  3983. EventEmitter.prototype.listenerCount = listenerCount;
  3984. function listenerCount(type) {
  3985. var events = this._events;
  3986. if (events) {
  3987. var evlistener = events[type];
  3988. if (typeof evlistener === 'function') {
  3989. return 1;
  3990. } else if (evlistener) {
  3991. return evlistener.length;
  3992. }
  3993. }
  3994. return 0;
  3995. }
  3996. EventEmitter.prototype.eventNames = function eventNames() {
  3997. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  3998. };
  3999. // About 1.5x faster than the two-arg version of Array#splice().
  4000. function spliceOne(list, index) {
  4001. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  4002. list[i] = list[k];
  4003. list.pop();
  4004. }
  4005. function arrayClone(arr, n) {
  4006. var copy = new Array(n);
  4007. for (var i = 0; i < n; ++i)
  4008. copy[i] = arr[i];
  4009. return copy;
  4010. }
  4011. function unwrapListeners(arr) {
  4012. var ret = new Array(arr.length);
  4013. for (var i = 0; i < ret.length; ++i) {
  4014. ret[i] = arr[i].listener || arr[i];
  4015. }
  4016. return ret;
  4017. }
  4018. function objectCreatePolyfill(proto) {
  4019. var F = function() {};
  4020. F.prototype = proto;
  4021. return new F;
  4022. }
  4023. function objectKeysPolyfill(obj) {
  4024. var keys = [];
  4025. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  4026. keys.push(k);
  4027. }
  4028. return k;
  4029. }
  4030. function functionBindPolyfill(context) {
  4031. var fn = this;
  4032. return function () {
  4033. return fn.apply(context, arguments);
  4034. };
  4035. }
  4036. },{}],14:[function(require,module,exports){
  4037. (function (Buffer){
  4038. // Copyright Joyent, Inc. and other Node contributors.
  4039. //
  4040. // Permission is hereby granted, free of charge, to any person obtaining a
  4041. // copy of this software and associated documentation files (the
  4042. // "Software"), to deal in the Software without restriction, including
  4043. // without limitation the rights to use, copy, modify, merge, publish,
  4044. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4045. // persons to whom the Software is furnished to do so, subject to the
  4046. // following conditions:
  4047. //
  4048. // The above copyright notice and this permission notice shall be included
  4049. // in all copies or substantial portions of the Software.
  4050. //
  4051. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4052. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4053. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4054. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4055. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4056. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4057. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4058. // NOTE: These type checking functions intentionally don't use `instanceof`
  4059. // because it is fragile and can be easily faked with `Object.create()`.
  4060. function isArray(arg) {
  4061. if (Array.isArray) {
  4062. return Array.isArray(arg);
  4063. }
  4064. return objectToString(arg) === '[object Array]';
  4065. }
  4066. exports.isArray = isArray;
  4067. function isBoolean(arg) {
  4068. return typeof arg === 'boolean';
  4069. }
  4070. exports.isBoolean = isBoolean;
  4071. function isNull(arg) {
  4072. return arg === null;
  4073. }
  4074. exports.isNull = isNull;
  4075. function isNullOrUndefined(arg) {
  4076. return arg == null;
  4077. }
  4078. exports.isNullOrUndefined = isNullOrUndefined;
  4079. function isNumber(arg) {
  4080. return typeof arg === 'number';
  4081. }
  4082. exports.isNumber = isNumber;
  4083. function isString(arg) {
  4084. return typeof arg === 'string';
  4085. }
  4086. exports.isString = isString;
  4087. function isSymbol(arg) {
  4088. return typeof arg === 'symbol';
  4089. }
  4090. exports.isSymbol = isSymbol;
  4091. function isUndefined(arg) {
  4092. return arg === void 0;
  4093. }
  4094. exports.isUndefined = isUndefined;
  4095. function isRegExp(re) {
  4096. return objectToString(re) === '[object RegExp]';
  4097. }
  4098. exports.isRegExp = isRegExp;
  4099. function isObject(arg) {
  4100. return typeof arg === 'object' && arg !== null;
  4101. }
  4102. exports.isObject = isObject;
  4103. function isDate(d) {
  4104. return objectToString(d) === '[object Date]';
  4105. }
  4106. exports.isDate = isDate;
  4107. function isError(e) {
  4108. return (objectToString(e) === '[object Error]' || e instanceof Error);
  4109. }
  4110. exports.isError = isError;
  4111. function isFunction(arg) {
  4112. return typeof arg === 'function';
  4113. }
  4114. exports.isFunction = isFunction;
  4115. function isPrimitive(arg) {
  4116. return arg === null ||
  4117. typeof arg === 'boolean' ||
  4118. typeof arg === 'number' ||
  4119. typeof arg === 'string' ||
  4120. typeof arg === 'symbol' || // ES6 symbol
  4121. typeof arg === 'undefined';
  4122. }
  4123. exports.isPrimitive = isPrimitive;
  4124. exports.isBuffer = Buffer.isBuffer;
  4125. function objectToString(o) {
  4126. return Object.prototype.toString.call(o);
  4127. }
  4128. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  4129. },{"../../is-buffer/index.js":81}],15:[function(require,module,exports){
  4130. 'use strict';
  4131. var copy = require('es5-ext/object/copy')
  4132. , normalizeOptions = require('es5-ext/object/normalize-options')
  4133. , ensureCallable = require('es5-ext/object/valid-callable')
  4134. , map = require('es5-ext/object/map')
  4135. , callable = require('es5-ext/object/valid-callable')
  4136. , validValue = require('es5-ext/object/valid-value')
  4137. , bind = Function.prototype.bind, defineProperty = Object.defineProperty
  4138. , hasOwnProperty = Object.prototype.hasOwnProperty
  4139. , define;
  4140. define = function (name, desc, options) {
  4141. var value = validValue(desc) && callable(desc.value), dgs;
  4142. dgs = copy(desc);
  4143. delete dgs.writable;
  4144. delete dgs.value;
  4145. dgs.get = function () {
  4146. if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
  4147. desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
  4148. defineProperty(this, name, desc);
  4149. return this[name];
  4150. };
  4151. return dgs;
  4152. };
  4153. module.exports = function (props/*, options*/) {
  4154. var options = normalizeOptions(arguments[1]);
  4155. if (options.resolveContext != null) ensureCallable(options.resolveContext);
  4156. return map(props, function (desc, name) { return define(name, desc, options); });
  4157. };
  4158. },{"es5-ext/object/copy":39,"es5-ext/object/map":48,"es5-ext/object/normalize-options":49,"es5-ext/object/valid-callable":54,"es5-ext/object/valid-value":55}],16:[function(require,module,exports){
  4159. 'use strict';
  4160. var assign = require('es5-ext/object/assign')
  4161. , normalizeOpts = require('es5-ext/object/normalize-options')
  4162. , isCallable = require('es5-ext/object/is-callable')
  4163. , contains = require('es5-ext/string/#/contains')
  4164. , d;
  4165. d = module.exports = function (dscr, value/*, options*/) {
  4166. var c, e, w, options, desc;
  4167. if ((arguments.length < 2) || (typeof dscr !== 'string')) {
  4168. options = value;
  4169. value = dscr;
  4170. dscr = null;
  4171. } else {
  4172. options = arguments[2];
  4173. }
  4174. if (dscr == null) {
  4175. c = w = true;
  4176. e = false;
  4177. } else {
  4178. c = contains.call(dscr, 'c');
  4179. e = contains.call(dscr, 'e');
  4180. w = contains.call(dscr, 'w');
  4181. }
  4182. desc = { value: value, configurable: c, enumerable: e, writable: w };
  4183. return !options ? desc : assign(normalizeOpts(options), desc);
  4184. };
  4185. d.gs = function (dscr, get, set/*, options*/) {
  4186. var c, e, options, desc;
  4187. if (typeof dscr !== 'string') {
  4188. options = set;
  4189. set = get;
  4190. get = dscr;
  4191. dscr = null;
  4192. } else {
  4193. options = arguments[3];
  4194. }
  4195. if (get == null) {
  4196. get = undefined;
  4197. } else if (!isCallable(get)) {
  4198. options = get;
  4199. get = set = undefined;
  4200. } else if (set == null) {
  4201. set = undefined;
  4202. } else if (!isCallable(set)) {
  4203. options = set;
  4204. set = undefined;
  4205. }
  4206. if (dscr == null) {
  4207. c = true;
  4208. e = false;
  4209. } else {
  4210. c = contains.call(dscr, 'c');
  4211. e = contains.call(dscr, 'e');
  4212. }
  4213. desc = { get: get, set: set, configurable: c, enumerable: e };
  4214. return !options ? desc : assign(normalizeOpts(options), desc);
  4215. };
  4216. },{"es5-ext/object/assign":36,"es5-ext/object/is-callable":42,"es5-ext/object/normalize-options":49,"es5-ext/string/#/contains":56}],17:[function(require,module,exports){
  4217. (function (process,Buffer){
  4218. var stream = require('readable-stream')
  4219. var eos = require('end-of-stream')
  4220. var inherits = require('inherits')
  4221. var shift = require('stream-shift')
  4222. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  4223. ? Buffer.from([0])
  4224. : new Buffer([0])
  4225. var onuncork = function(self, fn) {
  4226. if (self._corked) self.once('uncork', fn)
  4227. else fn()
  4228. }
  4229. var autoDestroy = function (self, err) {
  4230. if (self._autoDestroy) self.destroy(err)
  4231. }
  4232. var destroyer = function(self, end) {
  4233. return function(err) {
  4234. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  4235. else if (end && !self._ended) self.end()
  4236. }
  4237. }
  4238. var end = function(ws, fn) {
  4239. if (!ws) return fn()
  4240. if (ws._writableState && ws._writableState.finished) return fn()
  4241. if (ws._writableState) return ws.end(fn)
  4242. ws.end()
  4243. fn()
  4244. }
  4245. var toStreams2 = function(rs) {
  4246. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  4247. }
  4248. var Duplexify = function(writable, readable, opts) {
  4249. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  4250. stream.Duplex.call(this, opts)
  4251. this._writable = null
  4252. this._readable = null
  4253. this._readable2 = null
  4254. this._autoDestroy = !opts || opts.autoDestroy !== false
  4255. this._forwardDestroy = !opts || opts.destroy !== false
  4256. this._forwardEnd = !opts || opts.end !== false
  4257. this._corked = 1 // start corked
  4258. this._ondrain = null
  4259. this._drained = false
  4260. this._forwarding = false
  4261. this._unwrite = null
  4262. this._unread = null
  4263. this._ended = false
  4264. this.destroyed = false
  4265. if (writable) this.setWritable(writable)
  4266. if (readable) this.setReadable(readable)
  4267. }
  4268. inherits(Duplexify, stream.Duplex)
  4269. Duplexify.obj = function(writable, readable, opts) {
  4270. if (!opts) opts = {}
  4271. opts.objectMode = true
  4272. opts.highWaterMark = 16
  4273. return new Duplexify(writable, readable, opts)
  4274. }
  4275. Duplexify.prototype.cork = function() {
  4276. if (++this._corked === 1) this.emit('cork')
  4277. }
  4278. Duplexify.prototype.uncork = function() {
  4279. if (this._corked && --this._corked === 0) this.emit('uncork')
  4280. }
  4281. Duplexify.prototype.setWritable = function(writable) {
  4282. if (this._unwrite) this._unwrite()
  4283. if (this.destroyed) {
  4284. if (writable && writable.destroy) writable.destroy()
  4285. return
  4286. }
  4287. if (writable === null || writable === false) {
  4288. this.end()
  4289. return
  4290. }
  4291. var self = this
  4292. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  4293. var ondrain = function() {
  4294. var ondrain = self._ondrain
  4295. self._ondrain = null
  4296. if (ondrain) ondrain()
  4297. }
  4298. var clear = function() {
  4299. self._writable.removeListener('drain', ondrain)
  4300. unend()
  4301. }
  4302. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  4303. this._writable = writable
  4304. this._writable.on('drain', ondrain)
  4305. this._unwrite = clear
  4306. this.uncork() // always uncork setWritable
  4307. }
  4308. Duplexify.prototype.setReadable = function(readable) {
  4309. if (this._unread) this._unread()
  4310. if (this.destroyed) {
  4311. if (readable && readable.destroy) readable.destroy()
  4312. return
  4313. }
  4314. if (readable === null || readable === false) {
  4315. this.push(null)
  4316. this.resume()
  4317. return
  4318. }
  4319. var self = this
  4320. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  4321. var onreadable = function() {
  4322. self._forward()
  4323. }
  4324. var onend = function() {
  4325. self.push(null)
  4326. }
  4327. var clear = function() {
  4328. self._readable2.removeListener('readable', onreadable)
  4329. self._readable2.removeListener('end', onend)
  4330. unend()
  4331. }
  4332. this._drained = true
  4333. this._readable = readable
  4334. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  4335. this._readable2.on('readable', onreadable)
  4336. this._readable2.on('end', onend)
  4337. this._unread = clear
  4338. this._forward()
  4339. }
  4340. Duplexify.prototype._read = function() {
  4341. this._drained = true
  4342. this._forward()
  4343. }
  4344. Duplexify.prototype._forward = function() {
  4345. if (this._forwarding || !this._readable2 || !this._drained) return
  4346. this._forwarding = true
  4347. var data
  4348. while (this._drained && (data = shift(this._readable2)) !== null) {
  4349. if (this.destroyed) continue
  4350. this._drained = this.push(data)
  4351. }
  4352. this._forwarding = false
  4353. }
  4354. Duplexify.prototype.destroy = function(err) {
  4355. if (this.destroyed) return
  4356. this.destroyed = true
  4357. var self = this
  4358. process.nextTick(function() {
  4359. self._destroy(err)
  4360. })
  4361. }
  4362. Duplexify.prototype._destroy = function(err) {
  4363. if (err) {
  4364. var ondrain = this._ondrain
  4365. this._ondrain = null
  4366. if (ondrain) ondrain(err)
  4367. else this.emit('error', err)
  4368. }
  4369. if (this._forwardDestroy) {
  4370. if (this._readable && this._readable.destroy) this._readable.destroy()
  4371. if (this._writable && this._writable.destroy) this._writable.destroy()
  4372. }
  4373. console.log(`Duplexify.prototype._destroy`)
  4374. this.emit('close')
  4375. }
  4376. Duplexify.prototype._write = function(data, enc, cb) {
  4377. if (this.destroyed) return cb()
  4378. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  4379. if (data === SIGNAL_FLUSH) return this._finish(cb)
  4380. if (!this._writable) return cb()
  4381. if (this._writable.write(data) === false) this._ondrain = cb
  4382. else cb()
  4383. }
  4384. Duplexify.prototype._finish = function(cb) {
  4385. var self = this
  4386. this.emit('preend')
  4387. onuncork(this, function() {
  4388. end(self._forwardEnd && self._writable, function() {
  4389. // haxx to not emit prefinish twice
  4390. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  4391. self.emit('prefinish')
  4392. onuncork(self, cb)
  4393. })
  4394. })
  4395. }
  4396. Duplexify.prototype.end = function(data, enc, cb) {
  4397. if (typeof data === 'function') return this.end(null, null, data)
  4398. if (typeof enc === 'function') return this.end(data, null, enc)
  4399. this._ended = true
  4400. if (data) this.write(data)
  4401. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  4402. return stream.Writable.prototype.end.call(this, cb)
  4403. }
  4404. module.exports = Duplexify
  4405. }).call(this,require('_process'),require("buffer").Buffer)
  4406. },{"_process":92,"buffer":12,"end-of-stream":18,"inherits":80,"readable-stream":108,"stream-shift":111}],18:[function(require,module,exports){
  4407. var once = require('once');
  4408. var noop = function() {};
  4409. var isRequest = function(stream) {
  4410. return stream.setHeader && typeof stream.abort === 'function';
  4411. };
  4412. var isChildProcess = function(stream) {
  4413. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  4414. };
  4415. var eos = function(stream, opts, callback) {
  4416. if (typeof opts === 'function') return eos(stream, null, opts);
  4417. if (!opts) opts = {};
  4418. callback = once(callback || noop);
  4419. var ws = stream._writableState;
  4420. var rs = stream._readableState;
  4421. var readable = opts.readable || (opts.readable !== false && stream.readable);
  4422. var writable = opts.writable || (opts.writable !== false && stream.writable);
  4423. var onlegacyfinish = function() {
  4424. if (!stream.writable) onfinish();
  4425. };
  4426. var onfinish = function() {
  4427. writable = false;
  4428. if (!readable) callback.call(stream);
  4429. };
  4430. var onend = function() {
  4431. readable = false;
  4432. if (!writable) callback.call(stream);
  4433. };
  4434. var onexit = function(exitCode) {
  4435. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  4436. };
  4437. var onerror = function(err) {
  4438. callback.call(stream, err);
  4439. };
  4440. var onclose = function() {
  4441. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  4442. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  4443. };
  4444. var onrequest = function() {
  4445. stream.req.on('finish', onfinish);
  4446. };
  4447. if (isRequest(stream)) {
  4448. stream.on('complete', onfinish);
  4449. stream.on('abort', onclose);
  4450. if (stream.req) onrequest();
  4451. else stream.on('request', onrequest);
  4452. } else if (writable && !ws) { // legacy streams
  4453. stream.on('end', onlegacyfinish);
  4454. stream.on('close', onlegacyfinish);
  4455. }
  4456. if (isChildProcess(stream)) stream.on('exit', onexit);
  4457. stream.on('end', onend);
  4458. stream.on('finish', onfinish);
  4459. if (opts.error !== false) stream.on('error', onerror);
  4460. stream.on('close', onclose);
  4461. return function() {
  4462. stream.removeListener('complete', onfinish);
  4463. stream.removeListener('abort', onclose);
  4464. stream.removeListener('request', onrequest);
  4465. if (stream.req) stream.req.removeListener('finish', onfinish);
  4466. stream.removeListener('end', onlegacyfinish);
  4467. stream.removeListener('close', onlegacyfinish);
  4468. stream.removeListener('finish', onfinish);
  4469. stream.removeListener('exit', onexit);
  4470. stream.removeListener('end', onend);
  4471. stream.removeListener('error', onerror);
  4472. stream.removeListener('close', onclose);
  4473. };
  4474. };
  4475. module.exports = eos;
  4476. },{"once":90}],19:[function(require,module,exports){
  4477. // Inspired by Google Closure:
  4478. // http://closure-library.googlecode.com/svn/docs/
  4479. // closure_goog_array_array.js.html#goog.array.clear
  4480. "use strict";
  4481. var value = require("../../object/valid-value");
  4482. module.exports = function () {
  4483. value(this).length = 0;
  4484. return this;
  4485. };
  4486. },{"../../object/valid-value":55}],20:[function(require,module,exports){
  4487. "use strict";
  4488. var numberIsNaN = require("../../number/is-nan")
  4489. , toPosInt = require("../../number/to-pos-integer")
  4490. , value = require("../../object/valid-value")
  4491. , indexOf = Array.prototype.indexOf
  4492. , objHasOwnProperty = Object.prototype.hasOwnProperty
  4493. , abs = Math.abs
  4494. , floor = Math.floor;
  4495. module.exports = function (searchElement /*, fromIndex*/) {
  4496. var i, length, fromIndex, val;
  4497. if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
  4498. length = toPosInt(value(this).length);
  4499. fromIndex = arguments[1];
  4500. if (isNaN(fromIndex)) fromIndex = 0;
  4501. else if (fromIndex >= 0) fromIndex = floor(fromIndex);
  4502. else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
  4503. for (i = fromIndex; i < length; ++i) {
  4504. if (objHasOwnProperty.call(this, i)) {
  4505. val = this[i];
  4506. if (numberIsNaN(val)) return i; // Jslint: ignore
  4507. }
  4508. }
  4509. return -1;
  4510. };
  4511. },{"../../number/is-nan":30,"../../number/to-pos-integer":34,"../../object/valid-value":55}],21:[function(require,module,exports){
  4512. "use strict";
  4513. module.exports = require("./is-implemented")()
  4514. ? Array.from
  4515. : require("./shim");
  4516. },{"./is-implemented":22,"./shim":23}],22:[function(require,module,exports){
  4517. "use strict";
  4518. module.exports = function () {
  4519. var from = Array.from, arr, result;
  4520. if (typeof from !== "function") return false;
  4521. arr = ["raz", "dwa"];
  4522. result = from(arr);
  4523. return Boolean(result && (result !== arr) && (result[1] === "dwa"));
  4524. };
  4525. },{}],23:[function(require,module,exports){
  4526. "use strict";
  4527. var iteratorSymbol = require("es6-symbol").iterator
  4528. , isArguments = require("../../function/is-arguments")
  4529. , isFunction = require("../../function/is-function")
  4530. , toPosInt = require("../../number/to-pos-integer")
  4531. , callable = require("../../object/valid-callable")
  4532. , validValue = require("../../object/valid-value")
  4533. , isValue = require("../../object/is-value")
  4534. , isString = require("../../string/is-string")
  4535. , isArray = Array.isArray
  4536. , call = Function.prototype.call
  4537. , desc = { configurable: true, enumerable: true, writable: true, value: null }
  4538. , defineProperty = Object.defineProperty;
  4539. // eslint-disable-next-line complexity, max-lines-per-function
  4540. module.exports = function (arrayLike /*, mapFn, thisArg*/) {
  4541. var mapFn = arguments[1]
  4542. , thisArg = arguments[2]
  4543. , Context
  4544. , i
  4545. , j
  4546. , arr
  4547. , length
  4548. , code
  4549. , iterator
  4550. , result
  4551. , getIterator
  4552. , value;
  4553. arrayLike = Object(validValue(arrayLike));
  4554. if (isValue(mapFn)) callable(mapFn);
  4555. if (!this || this === Array || !isFunction(this)) {
  4556. // Result: Plain array
  4557. if (!mapFn) {
  4558. if (isArguments(arrayLike)) {
  4559. // Source: Arguments
  4560. length = arrayLike.length;
  4561. if (length !== 1) return Array.apply(null, arrayLike);
  4562. arr = new Array(1);
  4563. arr[0] = arrayLike[0];
  4564. return arr;
  4565. }
  4566. if (isArray(arrayLike)) {
  4567. // Source: Array
  4568. arr = new Array(length = arrayLike.length);
  4569. for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
  4570. return arr;
  4571. }
  4572. }
  4573. arr = [];
  4574. } else {
  4575. // Result: Non plain array
  4576. Context = this;
  4577. }
  4578. if (!isArray(arrayLike)) {
  4579. if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
  4580. // Source: Iterator
  4581. iterator = callable(getIterator).call(arrayLike);
  4582. if (Context) arr = new Context();
  4583. result = iterator.next();
  4584. i = 0;
  4585. while (!result.done) {
  4586. value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
  4587. if (Context) {
  4588. desc.value = value;
  4589. defineProperty(arr, i, desc);
  4590. } else {
  4591. arr[i] = value;
  4592. }
  4593. result = iterator.next();
  4594. ++i;
  4595. }
  4596. length = i;
  4597. } else if (isString(arrayLike)) {
  4598. // Source: String
  4599. length = arrayLike.length;
  4600. if (Context) arr = new Context();
  4601. for (i = 0, j = 0; i < length; ++i) {
  4602. value = arrayLike[i];
  4603. if (i + 1 < length) {
  4604. code = value.charCodeAt(0);
  4605. // eslint-disable-next-line max-depth
  4606. if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
  4607. }
  4608. value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
  4609. if (Context) {
  4610. desc.value = value;
  4611. defineProperty(arr, j, desc);
  4612. } else {
  4613. arr[j] = value;
  4614. }
  4615. ++j;
  4616. }
  4617. length = j;
  4618. }
  4619. }
  4620. if (length === undefined) {
  4621. // Source: array or array-like
  4622. length = toPosInt(arrayLike.length);
  4623. if (Context) arr = new Context(length);
  4624. for (i = 0; i < length; ++i) {
  4625. value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
  4626. if (Context) {
  4627. desc.value = value;
  4628. defineProperty(arr, i, desc);
  4629. } else {
  4630. arr[i] = value;
  4631. }
  4632. }
  4633. }
  4634. if (Context) {
  4635. desc.value = null;
  4636. arr.length = length;
  4637. }
  4638. return arr;
  4639. };
  4640. },{"../../function/is-arguments":24,"../../function/is-function":25,"../../number/to-pos-integer":34,"../../object/is-value":44,"../../object/valid-callable":54,"../../object/valid-value":55,"../../string/is-string":59,"es6-symbol":73}],24:[function(require,module,exports){
  4641. "use strict";
  4642. var objToString = Object.prototype.toString
  4643. , id = objToString.call(
  4644. (function () {
  4645. return arguments;
  4646. })()
  4647. );
  4648. module.exports = function (value) {
  4649. return objToString.call(value) === id;
  4650. };
  4651. },{}],25:[function(require,module,exports){
  4652. "use strict";
  4653. var objToString = Object.prototype.toString, id = objToString.call(require("./noop"));
  4654. module.exports = function (value) {
  4655. return typeof value === "function" && objToString.call(value) === id;
  4656. };
  4657. },{"./noop":26}],26:[function(require,module,exports){
  4658. "use strict";
  4659. // eslint-disable-next-line no-empty-function
  4660. module.exports = function () {};
  4661. },{}],27:[function(require,module,exports){
  4662. "use strict";
  4663. module.exports = require("./is-implemented")()
  4664. ? Math.sign
  4665. : require("./shim");
  4666. },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){
  4667. "use strict";
  4668. module.exports = function () {
  4669. var sign = Math.sign;
  4670. if (typeof sign !== "function") return false;
  4671. return (sign(10) === 1) && (sign(-20) === -1);
  4672. };
  4673. },{}],29:[function(require,module,exports){
  4674. "use strict";
  4675. module.exports = function (value) {
  4676. value = Number(value);
  4677. if (isNaN(value) || (value === 0)) return value;
  4678. return value > 0 ? 1 : -1;
  4679. };
  4680. },{}],30:[function(require,module,exports){
  4681. "use strict";
  4682. module.exports = require("./is-implemented")()
  4683. ? Number.isNaN
  4684. : require("./shim");
  4685. },{"./is-implemented":31,"./shim":32}],31:[function(require,module,exports){
  4686. "use strict";
  4687. module.exports = function () {
  4688. var numberIsNaN = Number.isNaN;
  4689. if (typeof numberIsNaN !== "function") return false;
  4690. return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
  4691. };
  4692. },{}],32:[function(require,module,exports){
  4693. "use strict";
  4694. module.exports = function (value) {
  4695. // eslint-disable-next-line no-self-compare
  4696. return value !== value;
  4697. };
  4698. },{}],33:[function(require,module,exports){
  4699. "use strict";
  4700. var sign = require("../math/sign")
  4701. , abs = Math.abs, floor = Math.floor;
  4702. module.exports = function (value) {
  4703. if (isNaN(value)) return 0;
  4704. value = Number(value);
  4705. if ((value === 0) || !isFinite(value)) return value;
  4706. return sign(value) * floor(abs(value));
  4707. };
  4708. },{"../math/sign":27}],34:[function(require,module,exports){
  4709. "use strict";
  4710. var toInteger = require("./to-integer")
  4711. , max = Math.max;
  4712. module.exports = function (value) {
  4713. return max(0, toInteger(value));
  4714. };
  4715. },{"./to-integer":33}],35:[function(require,module,exports){
  4716. // Internal method, used by iteration functions.
  4717. // Calls a function for each key-value pair found in object
  4718. // Optionally takes compareFn to iterate object in specific order
  4719. "use strict";
  4720. var callable = require("./valid-callable")
  4721. , value = require("./valid-value")
  4722. , bind = Function.prototype.bind
  4723. , call = Function.prototype.call
  4724. , keys = Object.keys
  4725. , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
  4726. module.exports = function (method, defVal) {
  4727. return function (obj, cb /*, thisArg, compareFn*/) {
  4728. var list, thisArg = arguments[2], compareFn = arguments[3];
  4729. obj = Object(value(obj));
  4730. callable(cb);
  4731. list = keys(obj);
  4732. if (compareFn) {
  4733. list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
  4734. }
  4735. if (typeof method !== "function") method = list[method];
  4736. return call.call(method, list, function (key, index) {
  4737. if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
  4738. return call.call(cb, thisArg, obj[key], key, obj, index);
  4739. });
  4740. };
  4741. };
  4742. },{"./valid-callable":54,"./valid-value":55}],36:[function(require,module,exports){
  4743. "use strict";
  4744. module.exports = require("./is-implemented")()
  4745. ? Object.assign
  4746. : require("./shim");
  4747. },{"./is-implemented":37,"./shim":38}],37:[function(require,module,exports){
  4748. "use strict";
  4749. module.exports = function () {
  4750. var assign = Object.assign, obj;
  4751. if (typeof assign !== "function") return false;
  4752. obj = { foo: "raz" };
  4753. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  4754. return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
  4755. };
  4756. },{}],38:[function(require,module,exports){
  4757. "use strict";
  4758. var keys = require("../keys")
  4759. , value = require("../valid-value")
  4760. , max = Math.max;
  4761. module.exports = function (dest, src /*, …srcn*/) {
  4762. var error, i, length = max(arguments.length, 2), assign;
  4763. dest = Object(value(dest));
  4764. assign = function (key) {
  4765. try {
  4766. dest[key] = src[key];
  4767. } catch (e) {
  4768. if (!error) error = e;
  4769. }
  4770. };
  4771. for (i = 1; i < length; ++i) {
  4772. src = arguments[i];
  4773. keys(src).forEach(assign);
  4774. }
  4775. if (error !== undefined) throw error;
  4776. return dest;
  4777. };
  4778. },{"../keys":45,"../valid-value":55}],39:[function(require,module,exports){
  4779. "use strict";
  4780. var aFrom = require("../array/from")
  4781. , assign = require("./assign")
  4782. , value = require("./valid-value");
  4783. module.exports = function (obj/*, propertyNames, options*/) {
  4784. var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
  4785. if (copy !== obj && !propertyNames) return copy;
  4786. var result = {};
  4787. if (propertyNames) {
  4788. aFrom(propertyNames, function (propertyName) {
  4789. if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
  4790. });
  4791. } else {
  4792. assign(result, obj);
  4793. }
  4794. return result;
  4795. };
  4796. },{"../array/from":21,"./assign":36,"./valid-value":55}],40:[function(require,module,exports){
  4797. // Workaround for http://code.google.com/p/v8/issues/detail?id=2804
  4798. "use strict";
  4799. var create = Object.create, shim;
  4800. if (!require("./set-prototype-of/is-implemented")()) {
  4801. shim = require("./set-prototype-of/shim");
  4802. }
  4803. module.exports = (function () {
  4804. var nullObject, polyProps, desc;
  4805. if (!shim) return create;
  4806. if (shim.level !== 1) return create;
  4807. nullObject = {};
  4808. polyProps = {};
  4809. desc = {
  4810. configurable: false,
  4811. enumerable: false,
  4812. writable: true,
  4813. value: undefined
  4814. };
  4815. Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
  4816. if (name === "__proto__") {
  4817. polyProps[name] = {
  4818. configurable: true,
  4819. enumerable: false,
  4820. writable: true,
  4821. value: undefined
  4822. };
  4823. return;
  4824. }
  4825. polyProps[name] = desc;
  4826. });
  4827. Object.defineProperties(nullObject, polyProps);
  4828. Object.defineProperty(shim, "nullPolyfill", {
  4829. configurable: false,
  4830. enumerable: false,
  4831. writable: false,
  4832. value: nullObject
  4833. });
  4834. return function (prototype, props) {
  4835. return create(prototype === null ? nullObject : prototype, props);
  4836. };
  4837. }());
  4838. },{"./set-prototype-of/is-implemented":52,"./set-prototype-of/shim":53}],41:[function(require,module,exports){
  4839. "use strict";
  4840. module.exports = require("./_iterate")("forEach");
  4841. },{"./_iterate":35}],42:[function(require,module,exports){
  4842. // Deprecated
  4843. "use strict";
  4844. module.exports = function (obj) {
  4845. return typeof obj === "function";
  4846. };
  4847. },{}],43:[function(require,module,exports){
  4848. "use strict";
  4849. var isValue = require("./is-value");
  4850. var map = { function: true, object: true };
  4851. module.exports = function (value) {
  4852. return (isValue(value) && map[typeof value]) || false;
  4853. };
  4854. },{"./is-value":44}],44:[function(require,module,exports){
  4855. "use strict";
  4856. var _undefined = require("../function/noop")(); // Support ES3 engines
  4857. module.exports = function (val) {
  4858. return (val !== _undefined) && (val !== null);
  4859. };
  4860. },{"../function/noop":26}],45:[function(require,module,exports){
  4861. "use strict";
  4862. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  4863. },{"./is-implemented":46,"./shim":47}],46:[function(require,module,exports){
  4864. "use strict";
  4865. module.exports = function () {
  4866. try {
  4867. Object.keys("primitive");
  4868. return true;
  4869. } catch (e) {
  4870. return false;
  4871. }
  4872. };
  4873. },{}],47:[function(require,module,exports){
  4874. "use strict";
  4875. var isValue = require("../is-value");
  4876. var keys = Object.keys;
  4877. module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
  4878. },{"../is-value":44}],48:[function(require,module,exports){
  4879. "use strict";
  4880. var callable = require("./valid-callable")
  4881. , forEach = require("./for-each")
  4882. , call = Function.prototype.call;
  4883. module.exports = function (obj, cb /*, thisArg*/) {
  4884. var result = {}, thisArg = arguments[2];
  4885. callable(cb);
  4886. forEach(obj, function (value, key, targetObj, index) {
  4887. result[key] = call.call(cb, thisArg, value, key, targetObj, index);
  4888. });
  4889. return result;
  4890. };
  4891. },{"./for-each":41,"./valid-callable":54}],49:[function(require,module,exports){
  4892. "use strict";
  4893. var isValue = require("./is-value");
  4894. var forEach = Array.prototype.forEach, create = Object.create;
  4895. var process = function (src, obj) {
  4896. var key;
  4897. for (key in src) obj[key] = src[key];
  4898. };
  4899. // eslint-disable-next-line no-unused-vars
  4900. module.exports = function (opts1 /*, …options*/) {
  4901. var result = create(null);
  4902. forEach.call(arguments, function (options) {
  4903. if (!isValue(options)) return;
  4904. process(Object(options), result);
  4905. });
  4906. return result;
  4907. };
  4908. },{"./is-value":44}],50:[function(require,module,exports){
  4909. "use strict";
  4910. var forEach = Array.prototype.forEach, create = Object.create;
  4911. // eslint-disable-next-line no-unused-vars
  4912. module.exports = function (arg /*, …args*/) {
  4913. var set = create(null);
  4914. forEach.call(arguments, function (name) {
  4915. set[name] = true;
  4916. });
  4917. return set;
  4918. };
  4919. },{}],51:[function(require,module,exports){
  4920. "use strict";
  4921. module.exports = require("./is-implemented")()
  4922. ? Object.setPrototypeOf
  4923. : require("./shim");
  4924. },{"./is-implemented":52,"./shim":53}],52:[function(require,module,exports){
  4925. "use strict";
  4926. var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
  4927. module.exports = function (/* CustomCreate*/) {
  4928. var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
  4929. if (typeof setPrototypeOf !== "function") return false;
  4930. return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
  4931. };
  4932. },{}],53:[function(require,module,exports){
  4933. /* eslint no-proto: "off" */
  4934. // Big thanks to @WebReflection for sorting this out
  4935. // https://gist.github.com/WebReflection/5593554
  4936. "use strict";
  4937. var isObject = require("../is-object")
  4938. , value = require("../valid-value")
  4939. , objIsPrototypeOf = Object.prototype.isPrototypeOf
  4940. , defineProperty = Object.defineProperty
  4941. , nullDesc = {
  4942. configurable: true,
  4943. enumerable: false,
  4944. writable: true,
  4945. value: undefined
  4946. }
  4947. , validate;
  4948. validate = function (obj, prototype) {
  4949. value(obj);
  4950. if (prototype === null || isObject(prototype)) return obj;
  4951. throw new TypeError("Prototype must be null or an object");
  4952. };
  4953. module.exports = (function (status) {
  4954. var fn, set;
  4955. if (!status) return null;
  4956. if (status.level === 2) {
  4957. if (status.set) {
  4958. set = status.set;
  4959. fn = function (obj, prototype) {
  4960. set.call(validate(obj, prototype), prototype);
  4961. return obj;
  4962. };
  4963. } else {
  4964. fn = function (obj, prototype) {
  4965. validate(obj, prototype).__proto__ = prototype;
  4966. return obj;
  4967. };
  4968. }
  4969. } else {
  4970. fn = function self(obj, prototype) {
  4971. var isNullBase;
  4972. validate(obj, prototype);
  4973. isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
  4974. if (isNullBase) delete self.nullPolyfill.__proto__;
  4975. if (prototype === null) prototype = self.nullPolyfill;
  4976. obj.__proto__ = prototype;
  4977. if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
  4978. return obj;
  4979. };
  4980. }
  4981. return Object.defineProperty(fn, "level", {
  4982. configurable: false,
  4983. enumerable: false,
  4984. writable: false,
  4985. value: status.level
  4986. });
  4987. }(
  4988. (function () {
  4989. var tmpObj1 = Object.create(null)
  4990. , tmpObj2 = {}
  4991. , set
  4992. , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
  4993. if (desc) {
  4994. try {
  4995. set = desc.set; // Opera crashes at this point
  4996. set.call(tmpObj1, tmpObj2);
  4997. } catch (ignore) {}
  4998. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
  4999. }
  5000. tmpObj1.__proto__ = tmpObj2;
  5001. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
  5002. tmpObj1 = {};
  5003. tmpObj1.__proto__ = tmpObj2;
  5004. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
  5005. return false;
  5006. })()
  5007. ));
  5008. require("../create");
  5009. },{"../create":40,"../is-object":43,"../valid-value":55}],54:[function(require,module,exports){
  5010. "use strict";
  5011. module.exports = function (fn) {
  5012. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  5013. return fn;
  5014. };
  5015. },{}],55:[function(require,module,exports){
  5016. "use strict";
  5017. var isValue = require("./is-value");
  5018. module.exports = function (value) {
  5019. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  5020. return value;
  5021. };
  5022. },{"./is-value":44}],56:[function(require,module,exports){
  5023. "use strict";
  5024. module.exports = require("./is-implemented")()
  5025. ? String.prototype.contains
  5026. : require("./shim");
  5027. },{"./is-implemented":57,"./shim":58}],57:[function(require,module,exports){
  5028. "use strict";
  5029. var str = "razdwatrzy";
  5030. module.exports = function () {
  5031. if (typeof str.contains !== "function") return false;
  5032. return (str.contains("dwa") === true) && (str.contains("foo") === false);
  5033. };
  5034. },{}],58:[function(require,module,exports){
  5035. "use strict";
  5036. var indexOf = String.prototype.indexOf;
  5037. module.exports = function (searchString/*, position*/) {
  5038. return indexOf.call(this, searchString, arguments[1]) > -1;
  5039. };
  5040. },{}],59:[function(require,module,exports){
  5041. "use strict";
  5042. var objToString = Object.prototype.toString, id = objToString.call("");
  5043. module.exports = function (value) {
  5044. return (
  5045. typeof value === "string" ||
  5046. (value &&
  5047. typeof value === "object" &&
  5048. (value instanceof String || objToString.call(value) === id)) ||
  5049. false
  5050. );
  5051. };
  5052. },{}],60:[function(require,module,exports){
  5053. "use strict";
  5054. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5055. , contains = require("es5-ext/string/#/contains")
  5056. , d = require("d")
  5057. , Symbol = require("es6-symbol")
  5058. , Iterator = require("./");
  5059. var defineProperty = Object.defineProperty, ArrayIterator;
  5060. ArrayIterator = module.exports = function (arr, kind) {
  5061. if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
  5062. Iterator.call(this, arr);
  5063. if (!kind) kind = "value";
  5064. else if (contains.call(kind, "key+value")) kind = "key+value";
  5065. else if (contains.call(kind, "key")) kind = "key";
  5066. else kind = "value";
  5067. defineProperty(this, "__kind__", d("", kind));
  5068. };
  5069. if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
  5070. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5071. delete ArrayIterator.prototype.constructor;
  5072. ArrayIterator.prototype = Object.create(Iterator.prototype, {
  5073. _resolve: d(function (i) {
  5074. if (this.__kind__ === "value") return this.__list__[i];
  5075. if (this.__kind__ === "key+value") return [i, this.__list__[i]];
  5076. return i;
  5077. })
  5078. });
  5079. defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
  5080. },{"./":63,"d":16,"es5-ext/object/set-prototype-of":51,"es5-ext/string/#/contains":56,"es6-symbol":73}],61:[function(require,module,exports){
  5081. "use strict";
  5082. var isArguments = require("es5-ext/function/is-arguments")
  5083. , callable = require("es5-ext/object/valid-callable")
  5084. , isString = require("es5-ext/string/is-string")
  5085. , get = require("./get");
  5086. var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
  5087. module.exports = function (iterable, cb /*, thisArg*/) {
  5088. var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
  5089. if (isArray(iterable) || isArguments(iterable)) mode = "array";
  5090. else if (isString(iterable)) mode = "string";
  5091. else iterable = get(iterable);
  5092. callable(cb);
  5093. doBreak = function () {
  5094. broken = true;
  5095. };
  5096. if (mode === "array") {
  5097. some.call(iterable, function (value) {
  5098. call.call(cb, thisArg, value, doBreak);
  5099. return broken;
  5100. });
  5101. return;
  5102. }
  5103. if (mode === "string") {
  5104. length = iterable.length;
  5105. for (i = 0; i < length; ++i) {
  5106. char = iterable[i];
  5107. if (i + 1 < length) {
  5108. code = char.charCodeAt(0);
  5109. if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
  5110. }
  5111. call.call(cb, thisArg, char, doBreak);
  5112. if (broken) break;
  5113. }
  5114. return;
  5115. }
  5116. result = iterable.next();
  5117. while (!result.done) {
  5118. call.call(cb, thisArg, result.value, doBreak);
  5119. if (broken) return;
  5120. result = iterable.next();
  5121. }
  5122. };
  5123. },{"./get":62,"es5-ext/function/is-arguments":24,"es5-ext/object/valid-callable":54,"es5-ext/string/is-string":59}],62:[function(require,module,exports){
  5124. "use strict";
  5125. var isArguments = require("es5-ext/function/is-arguments")
  5126. , isString = require("es5-ext/string/is-string")
  5127. , ArrayIterator = require("./array")
  5128. , StringIterator = require("./string")
  5129. , iterable = require("./valid-iterable")
  5130. , iteratorSymbol = require("es6-symbol").iterator;
  5131. module.exports = function (obj) {
  5132. if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
  5133. if (isArguments(obj)) return new ArrayIterator(obj);
  5134. if (isString(obj)) return new StringIterator(obj);
  5135. return new ArrayIterator(obj);
  5136. };
  5137. },{"./array":60,"./string":65,"./valid-iterable":66,"es5-ext/function/is-arguments":24,"es5-ext/string/is-string":59,"es6-symbol":73}],63:[function(require,module,exports){
  5138. "use strict";
  5139. var clear = require("es5-ext/array/#/clear")
  5140. , assign = require("es5-ext/object/assign")
  5141. , callable = require("es5-ext/object/valid-callable")
  5142. , value = require("es5-ext/object/valid-value")
  5143. , d = require("d")
  5144. , autoBind = require("d/auto-bind")
  5145. , Symbol = require("es6-symbol");
  5146. var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
  5147. module.exports = Iterator = function (list, context) {
  5148. if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
  5149. defineProperties(this, {
  5150. __list__: d("w", value(list)),
  5151. __context__: d("w", context),
  5152. __nextIndex__: d("w", 0)
  5153. });
  5154. if (!context) return;
  5155. callable(context.on);
  5156. context.on("_add", this._onAdd);
  5157. context.on("_delete", this._onDelete);
  5158. context.on("_clear", this._onClear);
  5159. };
  5160. // Internal %IteratorPrototype% doesn't expose its constructor
  5161. delete Iterator.prototype.constructor;
  5162. defineProperties(
  5163. Iterator.prototype,
  5164. assign(
  5165. {
  5166. _next: d(function () {
  5167. var i;
  5168. if (!this.__list__) return undefined;
  5169. if (this.__redo__) {
  5170. i = this.__redo__.shift();
  5171. if (i !== undefined) return i;
  5172. }
  5173. if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
  5174. this._unBind();
  5175. return undefined;
  5176. }),
  5177. next: d(function () {
  5178. return this._createResult(this._next());
  5179. }),
  5180. _createResult: d(function (i) {
  5181. if (i === undefined) return { done: true, value: undefined };
  5182. return { done: false, value: this._resolve(i) };
  5183. }),
  5184. _resolve: d(function (i) {
  5185. return this.__list__[i];
  5186. }),
  5187. _unBind: d(function () {
  5188. this.__list__ = null;
  5189. delete this.__redo__;
  5190. if (!this.__context__) return;
  5191. this.__context__.off("_add", this._onAdd);
  5192. this.__context__.off("_delete", this._onDelete);
  5193. this.__context__.off("_clear", this._onClear);
  5194. this.__context__ = null;
  5195. }),
  5196. toString: d(function () {
  5197. return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
  5198. })
  5199. },
  5200. autoBind({
  5201. _onAdd: d(function (index) {
  5202. if (index >= this.__nextIndex__) return;
  5203. ++this.__nextIndex__;
  5204. if (!this.__redo__) {
  5205. defineProperty(this, "__redo__", d("c", [index]));
  5206. return;
  5207. }
  5208. this.__redo__.forEach(function (redo, i) {
  5209. if (redo >= index) this.__redo__[i] = ++redo;
  5210. }, this);
  5211. this.__redo__.push(index);
  5212. }),
  5213. _onDelete: d(function (index) {
  5214. var i;
  5215. if (index >= this.__nextIndex__) return;
  5216. --this.__nextIndex__;
  5217. if (!this.__redo__) return;
  5218. i = this.__redo__.indexOf(index);
  5219. if (i !== -1) this.__redo__.splice(i, 1);
  5220. this.__redo__.forEach(function (redo, j) {
  5221. if (redo > index) this.__redo__[j] = --redo;
  5222. }, this);
  5223. }),
  5224. _onClear: d(function () {
  5225. if (this.__redo__) clear.call(this.__redo__);
  5226. this.__nextIndex__ = 0;
  5227. })
  5228. })
  5229. )
  5230. );
  5231. defineProperty(
  5232. Iterator.prototype,
  5233. Symbol.iterator,
  5234. d(function () {
  5235. return this;
  5236. })
  5237. );
  5238. },{"d":16,"d/auto-bind":15,"es5-ext/array/#/clear":19,"es5-ext/object/assign":36,"es5-ext/object/valid-callable":54,"es5-ext/object/valid-value":55,"es6-symbol":73}],64:[function(require,module,exports){
  5239. "use strict";
  5240. var isArguments = require("es5-ext/function/is-arguments")
  5241. , isValue = require("es5-ext/object/is-value")
  5242. , isString = require("es5-ext/string/is-string");
  5243. var iteratorSymbol = require("es6-symbol").iterator
  5244. , isArray = Array.isArray;
  5245. module.exports = function (value) {
  5246. if (!isValue(value)) return false;
  5247. if (isArray(value)) return true;
  5248. if (isString(value)) return true;
  5249. if (isArguments(value)) return true;
  5250. return typeof value[iteratorSymbol] === "function";
  5251. };
  5252. },{"es5-ext/function/is-arguments":24,"es5-ext/object/is-value":44,"es5-ext/string/is-string":59,"es6-symbol":73}],65:[function(require,module,exports){
  5253. // Thanks @mathiasbynens
  5254. // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
  5255. "use strict";
  5256. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5257. , d = require("d")
  5258. , Symbol = require("es6-symbol")
  5259. , Iterator = require("./");
  5260. var defineProperty = Object.defineProperty, StringIterator;
  5261. StringIterator = module.exports = function (str) {
  5262. if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
  5263. str = String(str);
  5264. Iterator.call(this, str);
  5265. defineProperty(this, "__length__", d("", str.length));
  5266. };
  5267. if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
  5268. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5269. delete StringIterator.prototype.constructor;
  5270. StringIterator.prototype = Object.create(Iterator.prototype, {
  5271. _next: d(function () {
  5272. if (!this.__list__) return undefined;
  5273. if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
  5274. this._unBind();
  5275. return undefined;
  5276. }),
  5277. _resolve: d(function (i) {
  5278. var char = this.__list__[i], code;
  5279. if (this.__nextIndex__ === this.__length__) return char;
  5280. code = char.charCodeAt(0);
  5281. if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
  5282. return char;
  5283. })
  5284. });
  5285. defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
  5286. },{"./":63,"d":16,"es5-ext/object/set-prototype-of":51,"es6-symbol":73}],66:[function(require,module,exports){
  5287. "use strict";
  5288. var isIterable = require("./is-iterable");
  5289. module.exports = function (value) {
  5290. if (!isIterable(value)) throw new TypeError(value + " is not iterable");
  5291. return value;
  5292. };
  5293. },{"./is-iterable":64}],67:[function(require,module,exports){
  5294. 'use strict';
  5295. module.exports = require('./is-implemented')() ? Map : require('./polyfill');
  5296. },{"./is-implemented":68,"./polyfill":72}],68:[function(require,module,exports){
  5297. 'use strict';
  5298. module.exports = function () {
  5299. var map, iterator, result;
  5300. if (typeof Map !== 'function') return false;
  5301. try {
  5302. // WebKit doesn't support arguments and crashes
  5303. map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
  5304. } catch (e) {
  5305. return false;
  5306. }
  5307. if (String(map) !== '[object Map]') return false;
  5308. if (map.size !== 3) return false;
  5309. if (typeof map.clear !== 'function') return false;
  5310. if (typeof map.delete !== 'function') return false;
  5311. if (typeof map.entries !== 'function') return false;
  5312. if (typeof map.forEach !== 'function') return false;
  5313. if (typeof map.get !== 'function') return false;
  5314. if (typeof map.has !== 'function') return false;
  5315. if (typeof map.keys !== 'function') return false;
  5316. if (typeof map.set !== 'function') return false;
  5317. if (typeof map.values !== 'function') return false;
  5318. iterator = map.entries();
  5319. result = iterator.next();
  5320. if (result.done !== false) return false;
  5321. if (!result.value) return false;
  5322. if (result.value[0] !== 'raz') return false;
  5323. if (result.value[1] !== 'one') return false;
  5324. return true;
  5325. };
  5326. },{}],69:[function(require,module,exports){
  5327. // Exports true if environment provides native `Map` implementation,
  5328. // whatever that is.
  5329. 'use strict';
  5330. module.exports = (function () {
  5331. if (typeof Map === 'undefined') return false;
  5332. return (Object.prototype.toString.call(new Map()) === '[object Map]');
  5333. }());
  5334. },{}],70:[function(require,module,exports){
  5335. 'use strict';
  5336. module.exports = require('es5-ext/object/primitive-set')('key',
  5337. 'value', 'key+value');
  5338. },{"es5-ext/object/primitive-set":50}],71:[function(require,module,exports){
  5339. 'use strict';
  5340. var setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5341. , d = require('d')
  5342. , Iterator = require('es6-iterator')
  5343. , toStringTagSymbol = require('es6-symbol').toStringTag
  5344. , kinds = require('./iterator-kinds')
  5345. , defineProperties = Object.defineProperties
  5346. , unBind = Iterator.prototype._unBind
  5347. , MapIterator;
  5348. MapIterator = module.exports = function (map, kind) {
  5349. if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
  5350. Iterator.call(this, map.__mapKeysData__, map);
  5351. if (!kind || !kinds[kind]) kind = 'key+value';
  5352. defineProperties(this, {
  5353. __kind__: d('', kind),
  5354. __values__: d('w', map.__mapValuesData__)
  5355. });
  5356. };
  5357. if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
  5358. MapIterator.prototype = Object.create(Iterator.prototype, {
  5359. constructor: d(MapIterator),
  5360. _resolve: d(function (i) {
  5361. if (this.__kind__ === 'value') return this.__values__[i];
  5362. if (this.__kind__ === 'key') return this.__list__[i];
  5363. return [this.__list__[i], this.__values__[i]];
  5364. }),
  5365. _unBind: d(function () {
  5366. this.__values__ = null;
  5367. unBind.call(this);
  5368. }),
  5369. toString: d(function () { return '[object Map Iterator]'; })
  5370. });
  5371. Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
  5372. d('c', 'Map Iterator'));
  5373. },{"./iterator-kinds":70,"d":16,"es5-ext/object/set-prototype-of":51,"es6-iterator":63,"es6-symbol":73}],72:[function(require,module,exports){
  5374. 'use strict';
  5375. var clear = require('es5-ext/array/#/clear')
  5376. , eIndexOf = require('es5-ext/array/#/e-index-of')
  5377. , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5378. , callable = require('es5-ext/object/valid-callable')
  5379. , validValue = require('es5-ext/object/valid-value')
  5380. , d = require('d')
  5381. , ee = require('event-emitter')
  5382. , Symbol = require('es6-symbol')
  5383. , iterator = require('es6-iterator/valid-iterable')
  5384. , forOf = require('es6-iterator/for-of')
  5385. , Iterator = require('./lib/iterator')
  5386. , isNative = require('./is-native-implemented')
  5387. , call = Function.prototype.call
  5388. , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf
  5389. , MapPoly;
  5390. module.exports = MapPoly = function (/*iterable*/) {
  5391. var iterable = arguments[0], keys, values, self;
  5392. if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\'');
  5393. if (isNative && setPrototypeOf && (Map !== MapPoly)) {
  5394. self = setPrototypeOf(new Map(), getPrototypeOf(this));
  5395. } else {
  5396. self = this;
  5397. }
  5398. if (iterable != null) iterator(iterable);
  5399. defineProperties(self, {
  5400. __mapKeysData__: d('c', keys = []),
  5401. __mapValuesData__: d('c', values = [])
  5402. });
  5403. if (!iterable) return self;
  5404. forOf(iterable, function (value) {
  5405. var key = validValue(value)[0];
  5406. value = value[1];
  5407. if (eIndexOf.call(keys, key) !== -1) return;
  5408. keys.push(key);
  5409. values.push(value);
  5410. }, self);
  5411. return self;
  5412. };
  5413. if (isNative) {
  5414. if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
  5415. MapPoly.prototype = Object.create(Map.prototype, {
  5416. constructor: d(MapPoly)
  5417. });
  5418. }
  5419. ee(defineProperties(MapPoly.prototype, {
  5420. clear: d(function () {
  5421. if (!this.__mapKeysData__.length) return;
  5422. clear.call(this.__mapKeysData__);
  5423. clear.call(this.__mapValuesData__);
  5424. this.emit('_clear');
  5425. }),
  5426. delete: d(function (key) {
  5427. var index = eIndexOf.call(this.__mapKeysData__, key);
  5428. if (index === -1) return false;
  5429. this.__mapKeysData__.splice(index, 1);
  5430. this.__mapValuesData__.splice(index, 1);
  5431. this.emit('_delete', index, key);
  5432. return true;
  5433. }),
  5434. entries: d(function () { return new Iterator(this, 'key+value'); }),
  5435. forEach: d(function (cb/*, thisArg*/) {
  5436. var thisArg = arguments[1], iterator, result;
  5437. callable(cb);
  5438. iterator = this.entries();
  5439. result = iterator._next();
  5440. while (result !== undefined) {
  5441. call.call(cb, thisArg, this.__mapValuesData__[result],
  5442. this.__mapKeysData__[result], this);
  5443. result = iterator._next();
  5444. }
  5445. }),
  5446. get: d(function (key) {
  5447. var index = eIndexOf.call(this.__mapKeysData__, key);
  5448. if (index === -1) return;
  5449. return this.__mapValuesData__[index];
  5450. }),
  5451. has: d(function (key) {
  5452. return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
  5453. }),
  5454. keys: d(function () { return new Iterator(this, 'key'); }),
  5455. set: d(function (key, value) {
  5456. var index = eIndexOf.call(this.__mapKeysData__, key), emit;
  5457. if (index === -1) {
  5458. index = this.__mapKeysData__.push(key) - 1;
  5459. emit = true;
  5460. }
  5461. this.__mapValuesData__[index] = value;
  5462. if (emit) this.emit('_add', index, key);
  5463. return this;
  5464. }),
  5465. size: d.gs(function () { return this.__mapKeysData__.length; }),
  5466. values: d(function () { return new Iterator(this, 'value'); }),
  5467. toString: d(function () { return '[object Map]'; })
  5468. }));
  5469. Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
  5470. return this.entries();
  5471. }));
  5472. Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
  5473. },{"./is-native-implemented":69,"./lib/iterator":71,"d":16,"es5-ext/array/#/clear":19,"es5-ext/array/#/e-index-of":20,"es5-ext/object/set-prototype-of":51,"es5-ext/object/valid-callable":54,"es5-ext/object/valid-value":55,"es6-iterator/for-of":61,"es6-iterator/valid-iterable":66,"es6-symbol":73,"event-emitter":78}],73:[function(require,module,exports){
  5474. 'use strict';
  5475. module.exports = require('./is-implemented')() ? Symbol : require('./polyfill');
  5476. },{"./is-implemented":74,"./polyfill":76}],74:[function(require,module,exports){
  5477. 'use strict';
  5478. var validTypes = { object: true, symbol: true };
  5479. module.exports = function () {
  5480. var symbol;
  5481. if (typeof Symbol !== 'function') return false;
  5482. symbol = Symbol('test symbol');
  5483. try { String(symbol); } catch (e) { return false; }
  5484. // Return 'true' also for polyfills
  5485. if (!validTypes[typeof Symbol.iterator]) return false;
  5486. if (!validTypes[typeof Symbol.toPrimitive]) return false;
  5487. if (!validTypes[typeof Symbol.toStringTag]) return false;
  5488. return true;
  5489. };
  5490. },{}],75:[function(require,module,exports){
  5491. 'use strict';
  5492. module.exports = function (x) {
  5493. if (!x) return false;
  5494. if (typeof x === 'symbol') return true;
  5495. if (!x.constructor) return false;
  5496. if (x.constructor.name !== 'Symbol') return false;
  5497. return (x[x.constructor.toStringTag] === 'Symbol');
  5498. };
  5499. },{}],76:[function(require,module,exports){
  5500. // ES2015 Symbol polyfill for environments that do not (or partially) support it
  5501. 'use strict';
  5502. var d = require('d')
  5503. , validateSymbol = require('./validate-symbol')
  5504. , create = Object.create, defineProperties = Object.defineProperties
  5505. , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  5506. , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null)
  5507. , isNativeSafe;
  5508. if (typeof Symbol === 'function') {
  5509. NativeSymbol = Symbol;
  5510. try {
  5511. String(NativeSymbol());
  5512. isNativeSafe = true;
  5513. } catch (ignore) {}
  5514. }
  5515. var generateName = (function () {
  5516. var created = create(null);
  5517. return function (desc) {
  5518. var postfix = 0, name, ie11BugWorkaround;
  5519. while (created[desc + (postfix || '')]) ++postfix;
  5520. desc += (postfix || '');
  5521. created[desc] = true;
  5522. name = '@@' + desc;
  5523. defineProperty(objPrototype, name, d.gs(null, function (value) {
  5524. // For IE11 issue see:
  5525. // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
  5526. // ie11-broken-getters-on-dom-objects
  5527. // https://github.com/medikoo/es6-symbol/issues/12
  5528. if (ie11BugWorkaround) return;
  5529. ie11BugWorkaround = true;
  5530. defineProperty(this, name, d(value));
  5531. ie11BugWorkaround = false;
  5532. }));
  5533. return name;
  5534. };
  5535. }());
  5536. // Internal constructor (not one exposed) for creating Symbol instances.
  5537. // This one is used to ensure that `someSymbol instanceof Symbol` always return false
  5538. HiddenSymbol = function Symbol(description) {
  5539. if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor');
  5540. return SymbolPolyfill(description);
  5541. };
  5542. // Exposed `Symbol` constructor
  5543. // (returns instances of HiddenSymbol)
  5544. module.exports = SymbolPolyfill = function Symbol(description) {
  5545. var symbol;
  5546. if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor');
  5547. if (isNativeSafe) return NativeSymbol(description);
  5548. symbol = create(HiddenSymbol.prototype);
  5549. description = (description === undefined ? '' : String(description));
  5550. return defineProperties(symbol, {
  5551. __description__: d('', description),
  5552. __name__: d('', generateName(description))
  5553. });
  5554. };
  5555. defineProperties(SymbolPolyfill, {
  5556. for: d(function (key) {
  5557. if (globalSymbols[key]) return globalSymbols[key];
  5558. return (globalSymbols[key] = SymbolPolyfill(String(key)));
  5559. }),
  5560. keyFor: d(function (s) {
  5561. var key;
  5562. validateSymbol(s);
  5563. for (key in globalSymbols) if (globalSymbols[key] === s) return key;
  5564. }),
  5565. // To ensure proper interoperability with other native functions (e.g. Array.from)
  5566. // fallback to eventual native implementation of given symbol
  5567. hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
  5568. isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
  5569. SymbolPolyfill('isConcatSpreadable')),
  5570. iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
  5571. match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
  5572. replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
  5573. search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
  5574. species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
  5575. split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
  5576. toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
  5577. toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
  5578. unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
  5579. });
  5580. // Internal tweaks for real symbol producer
  5581. defineProperties(HiddenSymbol.prototype, {
  5582. constructor: d(SymbolPolyfill),
  5583. toString: d('', function () { return this.__name__; })
  5584. });
  5585. // Proper implementation of methods exposed on Symbol.prototype
  5586. // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
  5587. defineProperties(SymbolPolyfill.prototype, {
  5588. toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
  5589. valueOf: d(function () { return validateSymbol(this); })
  5590. });
  5591. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () {
  5592. var symbol = validateSymbol(this);
  5593. if (typeof symbol === 'symbol') return symbol;
  5594. return symbol.toString();
  5595. }));
  5596. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));
  5597. // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
  5598. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
  5599. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
  5600. // Note: It's important to define `toPrimitive` as last one, as some implementations
  5601. // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
  5602. // And that may invoke error in definition flow:
  5603. // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
  5604. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
  5605. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
  5606. },{"./validate-symbol":77,"d":16}],77:[function(require,module,exports){
  5607. 'use strict';
  5608. var isSymbol = require('./is-symbol');
  5609. module.exports = function (value) {
  5610. if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
  5611. return value;
  5612. };
  5613. },{"./is-symbol":75}],78:[function(require,module,exports){
  5614. 'use strict';
  5615. var d = require('d')
  5616. , callable = require('es5-ext/object/valid-callable')
  5617. , apply = Function.prototype.apply, call = Function.prototype.call
  5618. , create = Object.create, defineProperty = Object.defineProperty
  5619. , defineProperties = Object.defineProperties
  5620. , hasOwnProperty = Object.prototype.hasOwnProperty
  5621. , descriptor = { configurable: true, enumerable: false, writable: true }
  5622. , on, once, off, emit, methods, descriptors, base;
  5623. on = function (type, listener) {
  5624. var data;
  5625. callable(listener);
  5626. if (!hasOwnProperty.call(this, '__ee__')) {
  5627. data = descriptor.value = create(null);
  5628. defineProperty(this, '__ee__', descriptor);
  5629. descriptor.value = null;
  5630. } else {
  5631. data = this.__ee__;
  5632. }
  5633. if (!data[type]) data[type] = listener;
  5634. else if (typeof data[type] === 'object') data[type].push(listener);
  5635. else data[type] = [data[type], listener];
  5636. return this;
  5637. };
  5638. once = function (type, listener) {
  5639. var once, self;
  5640. callable(listener);
  5641. self = this;
  5642. on.call(this, type, once = function () {
  5643. off.call(self, type, once);
  5644. apply.call(listener, this, arguments);
  5645. });
  5646. once.__eeOnceListener__ = listener;
  5647. return this;
  5648. };
  5649. off = function (type, listener) {
  5650. var data, listeners, candidate, i;
  5651. callable(listener);
  5652. if (!hasOwnProperty.call(this, '__ee__')) return this;
  5653. data = this.__ee__;
  5654. if (!data[type]) return this;
  5655. listeners = data[type];
  5656. if (typeof listeners === 'object') {
  5657. for (i = 0; (candidate = listeners[i]); ++i) {
  5658. if ((candidate === listener) ||
  5659. (candidate.__eeOnceListener__ === listener)) {
  5660. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  5661. else listeners.splice(i, 1);
  5662. }
  5663. }
  5664. } else {
  5665. if ((listeners === listener) ||
  5666. (listeners.__eeOnceListener__ === listener)) {
  5667. delete data[type];
  5668. }
  5669. }
  5670. return this;
  5671. };
  5672. emit = function (type) {
  5673. var i, l, listener, listeners, args;
  5674. if (!hasOwnProperty.call(this, '__ee__')) return;
  5675. listeners = this.__ee__[type];
  5676. if (!listeners) return;
  5677. if (typeof listeners === 'object') {
  5678. l = arguments.length;
  5679. args = new Array(l - 1);
  5680. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  5681. listeners = listeners.slice();
  5682. for (i = 0; (listener = listeners[i]); ++i) {
  5683. apply.call(listener, this, args);
  5684. }
  5685. } else {
  5686. switch (arguments.length) {
  5687. case 1:
  5688. call.call(listeners, this);
  5689. break;
  5690. case 2:
  5691. call.call(listeners, this, arguments[1]);
  5692. break;
  5693. case 3:
  5694. call.call(listeners, this, arguments[1], arguments[2]);
  5695. break;
  5696. default:
  5697. l = arguments.length;
  5698. args = new Array(l - 1);
  5699. for (i = 1; i < l; ++i) {
  5700. args[i - 1] = arguments[i];
  5701. }
  5702. apply.call(listeners, this, args);
  5703. }
  5704. }
  5705. };
  5706. methods = {
  5707. on: on,
  5708. once: once,
  5709. off: off,
  5710. emit: emit
  5711. };
  5712. descriptors = {
  5713. on: d(on),
  5714. once: d(once),
  5715. off: d(off),
  5716. emit: d(emit)
  5717. };
  5718. base = defineProperties({}, descriptors);
  5719. module.exports = exports = function (o) {
  5720. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  5721. };
  5722. exports.methods = methods;
  5723. },{"d":16,"es5-ext/object/valid-callable":54}],79:[function(require,module,exports){
  5724. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5725. var e, m
  5726. var eLen = (nBytes * 8) - mLen - 1
  5727. var eMax = (1 << eLen) - 1
  5728. var eBias = eMax >> 1
  5729. var nBits = -7
  5730. var i = isLE ? (nBytes - 1) : 0
  5731. var d = isLE ? -1 : 1
  5732. var s = buffer[offset + i]
  5733. i += d
  5734. e = s & ((1 << (-nBits)) - 1)
  5735. s >>= (-nBits)
  5736. nBits += eLen
  5737. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5738. m = e & ((1 << (-nBits)) - 1)
  5739. e >>= (-nBits)
  5740. nBits += mLen
  5741. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5742. if (e === 0) {
  5743. e = 1 - eBias
  5744. } else if (e === eMax) {
  5745. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5746. } else {
  5747. m = m + Math.pow(2, mLen)
  5748. e = e - eBias
  5749. }
  5750. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5751. }
  5752. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5753. var e, m, c
  5754. var eLen = (nBytes * 8) - mLen - 1
  5755. var eMax = (1 << eLen) - 1
  5756. var eBias = eMax >> 1
  5757. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5758. var i = isLE ? 0 : (nBytes - 1)
  5759. var d = isLE ? 1 : -1
  5760. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5761. value = Math.abs(value)
  5762. if (isNaN(value) || value === Infinity) {
  5763. m = isNaN(value) ? 1 : 0
  5764. e = eMax
  5765. } else {
  5766. e = Math.floor(Math.log(value) / Math.LN2)
  5767. if (value * (c = Math.pow(2, -e)) < 1) {
  5768. e--
  5769. c *= 2
  5770. }
  5771. if (e + eBias >= 1) {
  5772. value += rt / c
  5773. } else {
  5774. value += rt * Math.pow(2, 1 - eBias)
  5775. }
  5776. if (value * c >= 2) {
  5777. e++
  5778. c /= 2
  5779. }
  5780. if (e + eBias >= eMax) {
  5781. m = 0
  5782. e = eMax
  5783. } else if (e + eBias >= 1) {
  5784. m = ((value * c) - 1) * Math.pow(2, mLen)
  5785. e = e + eBias
  5786. } else {
  5787. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5788. e = 0
  5789. }
  5790. }
  5791. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5792. e = (e << mLen) | m
  5793. eLen += mLen
  5794. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5795. buffer[offset + i - d] |= s * 128
  5796. }
  5797. },{}],80:[function(require,module,exports){
  5798. if (typeof Object.create === 'function') {
  5799. // implementation from standard node.js 'util' module
  5800. module.exports = function inherits(ctor, superCtor) {
  5801. ctor.super_ = superCtor
  5802. ctor.prototype = Object.create(superCtor.prototype, {
  5803. constructor: {
  5804. value: ctor,
  5805. enumerable: false,
  5806. writable: true,
  5807. configurable: true
  5808. }
  5809. });
  5810. };
  5811. } else {
  5812. // old school shim for old browsers
  5813. module.exports = function inherits(ctor, superCtor) {
  5814. ctor.super_ = superCtor
  5815. var TempCtor = function () {}
  5816. TempCtor.prototype = superCtor.prototype
  5817. ctor.prototype = new TempCtor()
  5818. ctor.prototype.constructor = ctor
  5819. }
  5820. }
  5821. },{}],81:[function(require,module,exports){
  5822. /*!
  5823. * Determine if an object is a Buffer
  5824. *
  5825. * @author Feross Aboukhadijeh <https://feross.org>
  5826. * @license MIT
  5827. */
  5828. // The _isBuffer check is for Safari 5-7 support, because it's missing
  5829. // Object.prototype.constructor. Remove this eventually
  5830. module.exports = function (obj) {
  5831. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  5832. }
  5833. function isBuffer (obj) {
  5834. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  5835. }
  5836. // For Node v0.10 support. Remove this eventually.
  5837. function isSlowBuffer (obj) {
  5838. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  5839. }
  5840. },{}],82:[function(require,module,exports){
  5841. 'use strict'
  5842. var Buffer = require('safe-buffer').Buffer
  5843. /* Protocol - protocol constants */
  5844. var protocol = module.exports
  5845. /* Command code => mnemonic */
  5846. protocol.types = {
  5847. 0: 'reserved',
  5848. 1: 'connect',
  5849. 2: 'connack',
  5850. 3: 'publish',
  5851. 4: 'puback',
  5852. 5: 'pubrec',
  5853. 6: 'pubrel',
  5854. 7: 'pubcomp',
  5855. 8: 'subscribe',
  5856. 9: 'suback',
  5857. 10: 'unsubscribe',
  5858. 11: 'unsuback',
  5859. 12: 'pingreq',
  5860. 13: 'pingresp',
  5861. 14: 'disconnect',
  5862. 15: 'auth'
  5863. }
  5864. /* Mnemonic => Command code */
  5865. protocol.codes = {}
  5866. for (var k in protocol.types) {
  5867. var v = protocol.types[k]
  5868. protocol.codes[v] = k
  5869. }
  5870. /* Header */
  5871. protocol.CMD_SHIFT = 4
  5872. protocol.CMD_MASK = 0xF0
  5873. protocol.DUP_MASK = 0x08
  5874. protocol.QOS_MASK = 0x03
  5875. protocol.QOS_SHIFT = 1
  5876. protocol.RETAIN_MASK = 0x01
  5877. /* Length */
  5878. protocol.LENGTH_MASK = 0x7F
  5879. protocol.LENGTH_FIN_MASK = 0x80
  5880. /* Connack */
  5881. protocol.SESSIONPRESENT_MASK = 0x01
  5882. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  5883. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  5884. /* Connect */
  5885. protocol.USERNAME_MASK = 0x80
  5886. protocol.PASSWORD_MASK = 0x40
  5887. protocol.WILL_RETAIN_MASK = 0x20
  5888. protocol.WILL_QOS_MASK = 0x18
  5889. protocol.WILL_QOS_SHIFT = 3
  5890. protocol.WILL_FLAG_MASK = 0x04
  5891. protocol.CLEAN_SESSION_MASK = 0x02
  5892. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  5893. /* Properties */
  5894. protocol.properties = {
  5895. sessionExpiryInterval: 17,
  5896. willDelayInterval: 24,
  5897. receiveMaximum: 33,
  5898. maximumPacketSize: 39,
  5899. topicAliasMaximum: 34,
  5900. requestResponseInformation: 25,
  5901. requestProblemInformation: 23,
  5902. userProperties: 38,
  5903. authenticationMethod: 21,
  5904. authenticationData: 22,
  5905. payloadFormatIndicator: 1,
  5906. messageExpiryInterval: 2,
  5907. contentType: 3,
  5908. responseTopic: 8,
  5909. correlationData: 9,
  5910. maximumQoS: 36,
  5911. retainAvailable: 37,
  5912. assignedClientIdentifier: 18,
  5913. reasonString: 31,
  5914. wildcardSubscriptionAvailable: 40,
  5915. subscriptionIdentifiersAvailable: 41,
  5916. sharedSubscriptionAvailable: 42,
  5917. serverKeepAlive: 19,
  5918. responseInformation: 26,
  5919. serverReference: 28,
  5920. topicAlias: 35,
  5921. subscriptionIdentifier: 11
  5922. }
  5923. protocol.propertiesCodes = {}
  5924. for (var prop in protocol.properties) {
  5925. var id = protocol.properties[prop]
  5926. protocol.propertiesCodes[id] = prop
  5927. }
  5928. protocol.propertiesTypes = {
  5929. sessionExpiryInterval: 'int32',
  5930. willDelayInterval: 'int32',
  5931. receiveMaximum: 'int16',
  5932. maximumPacketSize: 'int32',
  5933. topicAliasMaximum: 'int16',
  5934. requestResponseInformation: 'byte',
  5935. requestProblemInformation: 'byte',
  5936. userProperties: 'pair',
  5937. authenticationMethod: 'string',
  5938. authenticationData: 'binary',
  5939. payloadFormatIndicator: 'byte',
  5940. messageExpiryInterval: 'int32',
  5941. contentType: 'string',
  5942. responseTopic: 'string',
  5943. correlationData: 'binary',
  5944. maximumQoS: 'int8',
  5945. retainAvailable: 'byte',
  5946. assignedClientIdentifier: 'string',
  5947. reasonString: 'string',
  5948. wildcardSubscriptionAvailable: 'byte',
  5949. subscriptionIdentifiersAvailable: 'byte',
  5950. sharedSubscriptionAvailable: 'byte',
  5951. serverKeepAlive: 'int32',
  5952. responseInformation: 'string',
  5953. serverReference: 'string',
  5954. topicAlias: 'int16',
  5955. subscriptionIdentifier: 'var'
  5956. }
  5957. function genHeader (type) {
  5958. return [0, 1, 2].map(function (qos) {
  5959. return [0, 1].map(function (dup) {
  5960. return [0, 1].map(function (retain) {
  5961. var buf = new Buffer(1)
  5962. buf.writeUInt8(
  5963. protocol.codes[type] << protocol.CMD_SHIFT |
  5964. (dup ? protocol.DUP_MASK : 0) |
  5965. qos << protocol.QOS_SHIFT | retain, 0, true)
  5966. return buf
  5967. })
  5968. })
  5969. })
  5970. }
  5971. /* Publish */
  5972. protocol.PUBLISH_HEADER = genHeader('publish')
  5973. /* Subscribe */
  5974. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  5975. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  5976. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  5977. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  5978. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  5979. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  5980. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  5981. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  5982. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  5983. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  5984. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  5985. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  5986. /* Unsubscribe */
  5987. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  5988. /* Confirmations */
  5989. protocol.ACKS = {
  5990. unsuback: genHeader('unsuback'),
  5991. puback: genHeader('puback'),
  5992. pubcomp: genHeader('pubcomp'),
  5993. pubrel: genHeader('pubrel'),
  5994. pubrec: genHeader('pubrec')
  5995. }
  5996. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  5997. /* Protocol versions */
  5998. protocol.VERSION3 = Buffer.from([3])
  5999. protocol.VERSION4 = Buffer.from([4])
  6000. protocol.VERSION5 = Buffer.from([5])
  6001. /* QoS */
  6002. protocol.QOS = [0, 1, 2].map(function (qos) {
  6003. return Buffer.from([qos])
  6004. })
  6005. /* Empty packets */
  6006. protocol.EMPTY = {
  6007. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  6008. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  6009. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  6010. }
  6011. },{"safe-buffer":110}],83:[function(require,module,exports){
  6012. 'use strict'
  6013. var Buffer = require('safe-buffer').Buffer
  6014. var writeToStream = require('./writeToStream')
  6015. var EE = require('events').EventEmitter
  6016. var inherits = require('inherits')
  6017. function generate (packet, opts) {
  6018. var stream = new Accumulator()
  6019. writeToStream(packet, stream, opts)
  6020. return stream.concat()
  6021. }
  6022. function Accumulator () {
  6023. this._array = new Array(20)
  6024. this._i = 0
  6025. }
  6026. inherits(Accumulator, EE)
  6027. Accumulator.prototype.write = function (chunk) {
  6028. this._array[this._i++] = chunk
  6029. return true
  6030. }
  6031. Accumulator.prototype.concat = function () {
  6032. var length = 0
  6033. var lengths = new Array(this._array.length)
  6034. var list = this._array
  6035. var pos = 0
  6036. var i
  6037. var result
  6038. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6039. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  6040. else lengths[i] = Buffer.byteLength(list[i])
  6041. length += lengths[i]
  6042. }
  6043. result = Buffer.allocUnsafe(length)
  6044. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6045. if (typeof list[i] !== 'string') {
  6046. list[i].copy(result, pos)
  6047. pos += lengths[i]
  6048. } else {
  6049. result.write(list[i], pos)
  6050. pos += lengths[i]
  6051. }
  6052. }
  6053. return result
  6054. }
  6055. module.exports = generate
  6056. },{"./writeToStream":89,"events":13,"inherits":80,"safe-buffer":110}],84:[function(require,module,exports){
  6057. 'use strict'
  6058. exports.parser = require('./parser')
  6059. exports.generate = require('./generate')
  6060. exports.writeToStream = require('./writeToStream')
  6061. },{"./generate":83,"./parser":88,"./writeToStream":89}],85:[function(require,module,exports){
  6062. var DuplexStream = require('readable-stream/duplex')
  6063. , util = require('util')
  6064. , Buffer = require('safe-buffer').Buffer
  6065. function BufferList (callback) {
  6066. if (!(this instanceof BufferList))
  6067. return new BufferList(callback)
  6068. this._bufs = []
  6069. this.length = 0
  6070. if (typeof callback == 'function') {
  6071. this._callback = callback
  6072. var piper = function piper (err) {
  6073. if (this._callback) {
  6074. this._callback(err)
  6075. this._callback = null
  6076. }
  6077. }.bind(this)
  6078. this.on('pipe', function onPipe (src) {
  6079. src.on('error', piper)
  6080. })
  6081. this.on('unpipe', function onUnpipe (src) {
  6082. src.removeListener('error', piper)
  6083. })
  6084. } else {
  6085. this.append(callback)
  6086. }
  6087. DuplexStream.call(this)
  6088. }
  6089. util.inherits(BufferList, DuplexStream)
  6090. BufferList.prototype._offset = function _offset (offset) {
  6091. var tot = 0, i = 0, _t
  6092. if (offset === 0) return [ 0, 0 ]
  6093. for (; i < this._bufs.length; i++) {
  6094. _t = tot + this._bufs[i].length
  6095. if (offset < _t || i == this._bufs.length - 1)
  6096. return [ i, offset - tot ]
  6097. tot = _t
  6098. }
  6099. }
  6100. BufferList.prototype.append = function append (buf) {
  6101. var i = 0
  6102. if (Buffer.isBuffer(buf)) {
  6103. this._appendBuffer(buf);
  6104. } else if (Array.isArray(buf)) {
  6105. for (; i < buf.length; i++)
  6106. this.append(buf[i])
  6107. } else if (buf instanceof BufferList) {
  6108. // unwrap argument into individual BufferLists
  6109. for (; i < buf._bufs.length; i++)
  6110. this.append(buf._bufs[i])
  6111. } else if (buf != null) {
  6112. // coerce number arguments to strings, since Buffer(number) does
  6113. // uninitialized memory allocation
  6114. if (typeof buf == 'number')
  6115. buf = buf.toString()
  6116. this._appendBuffer(Buffer.from(buf));
  6117. }
  6118. return this
  6119. }
  6120. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  6121. this._bufs.push(buf)
  6122. this.length += buf.length
  6123. }
  6124. BufferList.prototype._write = function _write (buf, encoding, callback) {
  6125. this._appendBuffer(buf)
  6126. if (typeof callback == 'function')
  6127. callback()
  6128. }
  6129. BufferList.prototype._read = function _read (size) {
  6130. if (!this.length)
  6131. return this.push(null)
  6132. size = Math.min(size, this.length)
  6133. this.push(this.slice(0, size))
  6134. this.consume(size)
  6135. }
  6136. BufferList.prototype.end = function end (chunk) {
  6137. DuplexStream.prototype.end.call(this, chunk)
  6138. if (this._callback) {
  6139. this._callback(null, this.slice())
  6140. this._callback = null
  6141. }
  6142. }
  6143. BufferList.prototype.get = function get (index) {
  6144. return this.slice(index, index + 1)[0]
  6145. }
  6146. BufferList.prototype.slice = function slice (start, end) {
  6147. if (typeof start == 'number' && start < 0)
  6148. start += this.length
  6149. if (typeof end == 'number' && end < 0)
  6150. end += this.length
  6151. return this.copy(null, 0, start, end)
  6152. }
  6153. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  6154. if (typeof srcStart != 'number' || srcStart < 0)
  6155. srcStart = 0
  6156. if (typeof srcEnd != 'number' || srcEnd > this.length)
  6157. srcEnd = this.length
  6158. if (srcStart >= this.length)
  6159. return dst || Buffer.alloc(0)
  6160. if (srcEnd <= 0)
  6161. return dst || Buffer.alloc(0)
  6162. var copy = !!dst
  6163. , off = this._offset(srcStart)
  6164. , len = srcEnd - srcStart
  6165. , bytes = len
  6166. , bufoff = (copy && dstStart) || 0
  6167. , start = off[1]
  6168. , l
  6169. , i
  6170. // copy/slice everything
  6171. if (srcStart === 0 && srcEnd == this.length) {
  6172. if (!copy) { // slice, but full concat if multiple buffers
  6173. return this._bufs.length === 1
  6174. ? this._bufs[0]
  6175. : Buffer.concat(this._bufs, this.length)
  6176. }
  6177. // copy, need to copy individual buffers
  6178. for (i = 0; i < this._bufs.length; i++) {
  6179. this._bufs[i].copy(dst, bufoff)
  6180. bufoff += this._bufs[i].length
  6181. }
  6182. return dst
  6183. }
  6184. // easy, cheap case where it's a subset of one of the buffers
  6185. if (bytes <= this._bufs[off[0]].length - start) {
  6186. return copy
  6187. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  6188. : this._bufs[off[0]].slice(start, start + bytes)
  6189. }
  6190. if (!copy) // a slice, we need something to copy in to
  6191. dst = Buffer.allocUnsafe(len)
  6192. for (i = off[0]; i < this._bufs.length; i++) {
  6193. l = this._bufs[i].length - start
  6194. if (bytes > l) {
  6195. this._bufs[i].copy(dst, bufoff, start)
  6196. } else {
  6197. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  6198. break
  6199. }
  6200. bufoff += l
  6201. bytes -= l
  6202. if (start)
  6203. start = 0
  6204. }
  6205. return dst
  6206. }
  6207. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  6208. start = start || 0
  6209. end = end || this.length
  6210. if (start < 0)
  6211. start += this.length
  6212. if (end < 0)
  6213. end += this.length
  6214. var startOffset = this._offset(start)
  6215. , endOffset = this._offset(end)
  6216. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  6217. if (endOffset[1] == 0)
  6218. buffers.pop()
  6219. else
  6220. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  6221. if (startOffset[1] != 0)
  6222. buffers[0] = buffers[0].slice(startOffset[1])
  6223. return new BufferList(buffers)
  6224. }
  6225. BufferList.prototype.toString = function toString (encoding, start, end) {
  6226. return this.slice(start, end).toString(encoding)
  6227. }
  6228. BufferList.prototype.consume = function consume (bytes) {
  6229. while (this._bufs.length) {
  6230. if (bytes >= this._bufs[0].length) {
  6231. bytes -= this._bufs[0].length
  6232. this.length -= this._bufs[0].length
  6233. this._bufs.shift()
  6234. } else {
  6235. this._bufs[0] = this._bufs[0].slice(bytes)
  6236. this.length -= bytes
  6237. break
  6238. }
  6239. }
  6240. return this
  6241. }
  6242. BufferList.prototype.duplicate = function duplicate () {
  6243. var i = 0
  6244. , copy = new BufferList()
  6245. for (; i < this._bufs.length; i++)
  6246. copy.append(this._bufs[i])
  6247. return copy
  6248. }
  6249. BufferList.prototype.destroy = function destroy () {
  6250. this._bufs.length = 0
  6251. this.length = 0
  6252. this.push(null)
  6253. }
  6254. ;(function () {
  6255. var methods = {
  6256. 'readDoubleBE' : 8
  6257. , 'readDoubleLE' : 8
  6258. , 'readFloatBE' : 4
  6259. , 'readFloatLE' : 4
  6260. , 'readInt32BE' : 4
  6261. , 'readInt32LE' : 4
  6262. , 'readUInt32BE' : 4
  6263. , 'readUInt32LE' : 4
  6264. , 'readInt16BE' : 2
  6265. , 'readInt16LE' : 2
  6266. , 'readUInt16BE' : 2
  6267. , 'readUInt16LE' : 2
  6268. , 'readInt8' : 1
  6269. , 'readUInt8' : 1
  6270. }
  6271. for (var m in methods) {
  6272. (function (m) {
  6273. BufferList.prototype[m] = function (offset) {
  6274. return this.slice(offset, offset + methods[m])[m](0)
  6275. }
  6276. }(m))
  6277. }
  6278. }())
  6279. module.exports = BufferList
  6280. },{"readable-stream/duplex":97,"safe-buffer":110,"util":117}],86:[function(require,module,exports){
  6281. 'use strict'
  6282. var Buffer = require('safe-buffer').Buffer
  6283. var max = 65536
  6284. var cache = {}
  6285. function generateBuffer (i) {
  6286. var buffer = Buffer.allocUnsafe(2)
  6287. buffer.writeUInt8(i >> 8, 0)
  6288. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  6289. return buffer
  6290. }
  6291. function generateCache () {
  6292. for (var i = 0; i < max; i++) {
  6293. cache[i] = generateBuffer(i)
  6294. }
  6295. }
  6296. /**
  6297. * calcVariableByteIntLength - calculate the variable byte integer
  6298. * length field
  6299. *
  6300. * @api private
  6301. */
  6302. function calcVariableByteIntLength (length) {
  6303. if (length >= 0 && length < 128) return 1
  6304. else if (length >= 128 && length < 16384) return 2
  6305. else if (length >= 16384 && length < 2097152) return 3
  6306. else if (length >= 2097152 && length < 268435456) return 4
  6307. else return 0
  6308. }
  6309. function genBufVariableByteInt (num) {
  6310. var digit = 0
  6311. var pos = 0
  6312. var length = calcVariableByteIntLength(num)
  6313. var buffer = Buffer.allocUnsafe(length)
  6314. do {
  6315. digit = num % 128 | 0
  6316. num = num / 128 | 0
  6317. if (num > 0) digit = digit | 0x80
  6318. buffer.writeUInt8(digit, pos++)
  6319. } while (num > 0)
  6320. return {
  6321. data: buffer,
  6322. length: length
  6323. }
  6324. }
  6325. function generate4ByteBuffer (num) {
  6326. var buffer = Buffer.allocUnsafe(4)
  6327. buffer.writeUInt32BE(num, 0)
  6328. return buffer
  6329. }
  6330. module.exports = {
  6331. cache: cache,
  6332. generateCache: generateCache,
  6333. generateNumber: generateBuffer,
  6334. genBufVariableByteInt: genBufVariableByteInt,
  6335. generate4ByteBuffer: generate4ByteBuffer
  6336. }
  6337. },{"safe-buffer":110}],87:[function(require,module,exports){
  6338. function Packet () {
  6339. this.cmd = null
  6340. this.retain = false
  6341. this.qos = 0
  6342. this.dup = false
  6343. this.length = -1
  6344. this.topic = null
  6345. this.payload = null
  6346. }
  6347. module.exports = Packet
  6348. },{}],88:[function(require,module,exports){
  6349. 'use strict'
  6350. var bl = require('bl')
  6351. var inherits = require('inherits')
  6352. var EE = require('events').EventEmitter
  6353. var Packet = require('./packet')
  6354. var constants = require('./constants')
  6355. function Parser (opt) {
  6356. if (!(this instanceof Parser)) return new Parser(opt)
  6357. this.settings = opt || {}
  6358. this._states = [
  6359. '_parseHeader',
  6360. '_parseLength',
  6361. '_parsePayload',
  6362. '_newPacket'
  6363. ]
  6364. this._resetState()
  6365. }
  6366. inherits(Parser, EE)
  6367. Parser.prototype._resetState = function () {
  6368. this.packet = new Packet()
  6369. this.error = null
  6370. this._list = bl()
  6371. this._stateCounter = 0
  6372. }
  6373. Parser.prototype.parse = function (buf) {
  6374. if (this.error) this._resetState()
  6375. this._list.append(buf)
  6376. while ((this.packet.length !== -1 || this._list.length > 0) &&
  6377. this[this._states[this._stateCounter]]() &&
  6378. !this.error) {
  6379. this._stateCounter++
  6380. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  6381. }
  6382. return this._list.length
  6383. }
  6384. Parser.prototype._parseHeader = function () {
  6385. // There is at least one byte in the buffer
  6386. var zero = this._list.readUInt8(0)
  6387. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  6388. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  6389. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  6390. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  6391. this._list.consume(1)
  6392. return true
  6393. }
  6394. Parser.prototype._parseLength = function () {
  6395. // There is at least one byte in the list
  6396. var result = this._parseVarByteNum(true)
  6397. if (result) {
  6398. this.packet.length = result.value
  6399. this._list.consume(result.bytes)
  6400. }
  6401. return !!result
  6402. }
  6403. Parser.prototype._parsePayload = function () {
  6404. var result = false
  6405. // Do we have a payload? Do we have enough data to complete the payload?
  6406. // PINGs have no payload
  6407. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  6408. this._pos = 0
  6409. switch (this.packet.cmd) {
  6410. case 'connect':
  6411. this._parseConnect()
  6412. break
  6413. case 'connack':
  6414. this._parseConnack()
  6415. break
  6416. case 'publish':
  6417. this._parsePublish()
  6418. break
  6419. case 'puback':
  6420. case 'pubrec':
  6421. case 'pubrel':
  6422. case 'pubcomp':
  6423. this._parseConfirmation()
  6424. break
  6425. case 'subscribe':
  6426. this._parseSubscribe()
  6427. break
  6428. case 'suback':
  6429. this._parseSuback()
  6430. break
  6431. case 'unsubscribe':
  6432. this._parseUnsubscribe()
  6433. break
  6434. case 'unsuback':
  6435. this._parseUnsuback()
  6436. break
  6437. case 'pingreq':
  6438. case 'pingresp':
  6439. // These are empty, nothing to do
  6440. break
  6441. case 'disconnect':
  6442. this._parseDisconnect()
  6443. break
  6444. case 'auth':
  6445. this._parseAuth()
  6446. break
  6447. default:
  6448. this._emitError(new Error('Not supported'))
  6449. }
  6450. result = true
  6451. }
  6452. return result
  6453. }
  6454. Parser.prototype._parseConnect = function () {
  6455. var protocolId // Protocol ID
  6456. var clientId // Client ID
  6457. var topic // Will topic
  6458. var payload // Will payload
  6459. var password // Password
  6460. var username // Username
  6461. var flags = {}
  6462. var packet = this.packet
  6463. // Parse protocolId
  6464. protocolId = this._parseString()
  6465. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  6466. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  6467. return this._emitError(new Error('Invalid protocolId'))
  6468. }
  6469. packet.protocolId = protocolId
  6470. // Parse constants version number
  6471. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  6472. packet.protocolVersion = this._list.readUInt8(this._pos)
  6473. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  6474. return this._emitError(new Error('Invalid protocol version'))
  6475. }
  6476. this._pos++
  6477. if (this._pos >= this._list.length) {
  6478. return this._emitError(new Error('Packet too short'))
  6479. }
  6480. // Parse connect flags
  6481. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  6482. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  6483. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  6484. if (flags.will) {
  6485. packet.will = {}
  6486. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  6487. packet.will.qos = (this._list.readUInt8(this._pos) &
  6488. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  6489. }
  6490. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  6491. this._pos++
  6492. // Parse keepalive
  6493. packet.keepalive = this._parseNum()
  6494. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  6495. // parse properties
  6496. if (packet.protocolVersion === 5) {
  6497. var properties = this._parseProperties()
  6498. if (Object.getOwnPropertyNames(properties).length) {
  6499. packet.properties = properties
  6500. }
  6501. }
  6502. // Parse clientId
  6503. clientId = this._parseString()
  6504. if (clientId === null) return this._emitError(new Error('Packet too short'))
  6505. packet.clientId = clientId
  6506. if (flags.will) {
  6507. if (packet.protocolVersion === 5) {
  6508. var willProperties = this._parseProperties()
  6509. if (Object.getOwnPropertyNames(willProperties).length) {
  6510. packet.will.properties = willProperties
  6511. }
  6512. }
  6513. // Parse will topic
  6514. topic = this._parseString()
  6515. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  6516. packet.will.topic = topic
  6517. // Parse will payload
  6518. payload = this._parseBuffer()
  6519. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  6520. packet.will.payload = payload
  6521. }
  6522. // Parse username
  6523. if (flags.username) {
  6524. username = this._parseString()
  6525. if (username === null) return this._emitError(new Error('Cannot parse username'))
  6526. packet.username = username
  6527. }
  6528. // Parse password
  6529. if (flags.password) {
  6530. password = this._parseBuffer()
  6531. if (password === null) return this._emitError(new Error('Cannot parse password'))
  6532. packet.password = password
  6533. }
  6534. // need for right parse auth packet and self set up
  6535. this.settings = packet
  6536. return packet
  6537. }
  6538. Parser.prototype._parseConnack = function () {
  6539. var packet = this.packet
  6540. if (this._list.length < 2) return null
  6541. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  6542. if (this.settings.protocolVersion === 5) {
  6543. packet.reasonCode = this._list.readUInt8(this._pos++)
  6544. } else {
  6545. packet.returnCode = this._list.readUInt8(this._pos++)
  6546. }
  6547. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  6548. // mqtt 5 properties
  6549. if (this.settings.protocolVersion === 5) {
  6550. var properties = this._parseProperties()
  6551. if (Object.getOwnPropertyNames(properties).length) {
  6552. packet.properties = properties
  6553. }
  6554. }
  6555. }
  6556. Parser.prototype._parsePublish = function () {
  6557. var packet = this.packet
  6558. packet.topic = this._parseString()
  6559. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  6560. // Parse messageId
  6561. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  6562. // Properties mqtt 5
  6563. if (this.settings.protocolVersion === 5) {
  6564. var properties = this._parseProperties()
  6565. if (Object.getOwnPropertyNames(properties).length) {
  6566. packet.properties = properties
  6567. }
  6568. }
  6569. packet.payload = this._list.slice(this._pos, packet.length)
  6570. }
  6571. Parser.prototype._parseSubscribe = function () {
  6572. var packet = this.packet
  6573. var topic
  6574. var options
  6575. var qos
  6576. var rh
  6577. var rap
  6578. var nl
  6579. var subscription
  6580. if (packet.qos !== 1) {
  6581. return this._emitError(new Error('Wrong subscribe header'))
  6582. }
  6583. packet.subscriptions = []
  6584. if (!this._parseMessageId()) { return }
  6585. // Properties mqtt 5
  6586. if (this.settings.protocolVersion === 5) {
  6587. var properties = this._parseProperties()
  6588. if (Object.getOwnPropertyNames(properties).length) {
  6589. packet.properties = properties
  6590. }
  6591. }
  6592. while (this._pos < packet.length) {
  6593. // Parse topic
  6594. topic = this._parseString()
  6595. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  6596. options = this._parseByte()
  6597. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  6598. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  6599. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  6600. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  6601. subscription = { topic: topic, qos: qos }
  6602. // mqtt 5 options
  6603. if (this.settings.protocolVersion === 5) {
  6604. subscription.nl = nl
  6605. subscription.rap = rap
  6606. subscription.rh = rh
  6607. }
  6608. // Push pair to subscriptions
  6609. packet.subscriptions.push(subscription)
  6610. }
  6611. }
  6612. Parser.prototype._parseSuback = function () {
  6613. var packet = this.packet
  6614. this.packet.granted = []
  6615. if (!this._parseMessageId()) { return }
  6616. // Properties mqtt 5
  6617. if (this.settings.protocolVersion === 5) {
  6618. var properties = this._parseProperties()
  6619. if (Object.getOwnPropertyNames(properties).length) {
  6620. packet.properties = properties
  6621. }
  6622. }
  6623. // Parse granted QoSes
  6624. while (this._pos < this.packet.length) {
  6625. this.packet.granted.push(this._list.readUInt8(this._pos++))
  6626. }
  6627. }
  6628. Parser.prototype._parseUnsubscribe = function () {
  6629. var packet = this.packet
  6630. packet.unsubscriptions = []
  6631. // Parse messageId
  6632. if (!this._parseMessageId()) { return }
  6633. // Properties mqtt 5
  6634. if (this.settings.protocolVersion === 5) {
  6635. var properties = this._parseProperties()
  6636. if (Object.getOwnPropertyNames(properties).length) {
  6637. packet.properties = properties
  6638. }
  6639. }
  6640. while (this._pos < packet.length) {
  6641. var topic
  6642. // Parse topic
  6643. topic = this._parseString()
  6644. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  6645. // Push topic to unsubscriptions
  6646. packet.unsubscriptions.push(topic)
  6647. }
  6648. }
  6649. Parser.prototype._parseUnsuback = function () {
  6650. var packet = this.packet
  6651. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  6652. // Properties mqtt 5
  6653. if (this.settings.protocolVersion === 5) {
  6654. var properties = this._parseProperties()
  6655. if (Object.getOwnPropertyNames(properties).length) {
  6656. packet.properties = properties
  6657. }
  6658. // Parse granted QoSes
  6659. packet.granted = []
  6660. while (this._pos < this.packet.length) {
  6661. this.packet.granted.push(this._list.readUInt8(this._pos++))
  6662. }
  6663. }
  6664. }
  6665. // parse packets like puback, pubrec, pubrel, pubcomp
  6666. Parser.prototype._parseConfirmation = function () {
  6667. var packet = this.packet
  6668. this._parseMessageId()
  6669. if (this.settings.protocolVersion === 5) {
  6670. if (packet.length > 2) {
  6671. // response code
  6672. packet.reasonCode = this._parseByte()
  6673. // properies mqtt 5
  6674. var properties = this._parseProperties()
  6675. if (Object.getOwnPropertyNames(properties).length) {
  6676. packet.properties = properties
  6677. }
  6678. }
  6679. }
  6680. return true
  6681. }
  6682. // parse disconnect packet
  6683. Parser.prototype._parseDisconnect = function () {
  6684. var packet = this.packet
  6685. if (this.settings.protocolVersion === 5) {
  6686. // response code
  6687. packet.reasonCode = this._parseByte()
  6688. // properies mqtt 5
  6689. var properties = this._parseProperties()
  6690. if (Object.getOwnPropertyNames(properties).length) {
  6691. packet.properties = properties
  6692. }
  6693. }
  6694. return true
  6695. }
  6696. // parse auth packet
  6697. Parser.prototype._parseAuth = function () {
  6698. var packet = this.packet
  6699. if (this.settings.protocolVersion !== 5) {
  6700. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  6701. }
  6702. // response code
  6703. packet.reasonCode = this._parseByte()
  6704. // properies mqtt 5
  6705. var properties = this._parseProperties()
  6706. if (Object.getOwnPropertyNames(properties).length) {
  6707. packet.properties = properties
  6708. }
  6709. return true
  6710. }
  6711. Parser.prototype._parseMessageId = function () {
  6712. var packet = this.packet
  6713. packet.messageId = this._parseNum()
  6714. if (packet.messageId === null) {
  6715. this._emitError(new Error('Cannot parse messageId'))
  6716. return false
  6717. }
  6718. return true
  6719. }
  6720. Parser.prototype._parseString = function (maybeBuffer) {
  6721. var length = this._parseNum()
  6722. var result
  6723. var end = length + this._pos
  6724. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  6725. result = this._list.toString('utf8', this._pos, end)
  6726. this._pos += length
  6727. return result
  6728. }
  6729. Parser.prototype._parseStringPair = function () {
  6730. return {
  6731. name: this._parseString(),
  6732. value: this._parseString()
  6733. }
  6734. }
  6735. Parser.prototype._parseBuffer = function () {
  6736. var length = this._parseNum()
  6737. var result
  6738. var end = length + this._pos
  6739. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  6740. result = this._list.slice(this._pos, end)
  6741. this._pos += length
  6742. return result
  6743. }
  6744. Parser.prototype._parseNum = function () {
  6745. if (this._list.length - this._pos < 2) return -1
  6746. var result = this._list.readUInt16BE(this._pos)
  6747. this._pos += 2
  6748. return result
  6749. }
  6750. Parser.prototype._parse4ByteNum = function () {
  6751. if (this._list.length - this._pos < 4) return -1
  6752. var result = this._list.readUInt32BE(this._pos)
  6753. this._pos += 4
  6754. return result
  6755. }
  6756. Parser.prototype._parseVarByteNum = function (fullInfoFlag) {
  6757. var bytes = 0
  6758. var mul = 1
  6759. var length = 0
  6760. var result = true
  6761. var current
  6762. var padding = this._pos ? this._pos : 0
  6763. while (bytes < 5) {
  6764. current = this._list.readUInt8(padding + bytes++)
  6765. length += mul * (current & constants.LENGTH_MASK)
  6766. mul *= 0x80
  6767. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  6768. if (this._list.length <= bytes) {
  6769. result = false
  6770. break
  6771. }
  6772. }
  6773. if (padding) {
  6774. this._pos += bytes
  6775. }
  6776. result = result
  6777. ? fullInfoFlag ? {
  6778. bytes: bytes,
  6779. value: length
  6780. } : length
  6781. : false
  6782. return result
  6783. }
  6784. Parser.prototype._parseByte = function () {
  6785. var result = this._list.readUInt8(this._pos)
  6786. this._pos++
  6787. return result
  6788. }
  6789. Parser.prototype._parseByType = function (type) {
  6790. switch (type) {
  6791. case 'byte': {
  6792. return this._parseByte() !== 0
  6793. }
  6794. case 'int8': {
  6795. return this._parseByte()
  6796. }
  6797. case 'int16': {
  6798. return this._parseNum()
  6799. }
  6800. case 'int32': {
  6801. return this._parse4ByteNum()
  6802. }
  6803. case 'var': {
  6804. return this._parseVarByteNum()
  6805. }
  6806. case 'string': {
  6807. return this._parseString()
  6808. }
  6809. case 'pair': {
  6810. return this._parseStringPair()
  6811. }
  6812. case 'binary': {
  6813. return this._parseBuffer()
  6814. }
  6815. }
  6816. }
  6817. Parser.prototype._parseProperties = function () {
  6818. var length = this._parseVarByteNum()
  6819. var start = this._pos
  6820. var end = start + length
  6821. var result = {}
  6822. while (this._pos < end) {
  6823. var type = this._parseByte()
  6824. var name = constants.propertiesCodes[type]
  6825. if (!name) {
  6826. this._emitError(new Error('Unknown property'))
  6827. return false
  6828. }
  6829. // user properties process
  6830. if (name === 'userProperties') {
  6831. if (!result[name]) {
  6832. result[name] = {}
  6833. }
  6834. var currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  6835. result[name][currentUserProperty.name] = currentUserProperty.value
  6836. continue
  6837. }
  6838. result[name] = this._parseByType(constants.propertiesTypes[name])
  6839. }
  6840. return result
  6841. }
  6842. Parser.prototype._newPacket = function () {
  6843. if (this.packet) {
  6844. this._list.consume(this.packet.length)
  6845. this.emit('packet', this.packet)
  6846. }
  6847. this.packet = new Packet()
  6848. this._pos = 0
  6849. return true
  6850. }
  6851. Parser.prototype._emitError = function (err) {
  6852. this.error = err
  6853. this.emit('error', err)
  6854. }
  6855. module.exports = Parser
  6856. },{"./constants":82,"./packet":87,"bl":85,"events":13,"inherits":80}],89:[function(require,module,exports){
  6857. 'use strict'
  6858. var protocol = require('./constants')
  6859. var Buffer = require('safe-buffer').Buffer
  6860. var empty = Buffer.allocUnsafe(0)
  6861. var zeroBuf = Buffer.from([0])
  6862. var numbers = require('./numbers')
  6863. var nextTick = require('process-nextick-args').nextTick
  6864. var numCache = numbers.cache
  6865. var generateNumber = numbers.generateNumber
  6866. var generateCache = numbers.generateCache
  6867. var genBufVariableByteInt = numbers.genBufVariableByteInt
  6868. var generate4ByteBuffer = numbers.generate4ByteBuffer
  6869. var writeNumber = writeNumberCached
  6870. var toGenerate = true
  6871. function generate (packet, stream, opts) {
  6872. if (stream.cork) {
  6873. stream.cork()
  6874. nextTick(uncork, stream)
  6875. }
  6876. if (toGenerate) {
  6877. toGenerate = false
  6878. generateCache()
  6879. }
  6880. switch (packet.cmd) {
  6881. case 'connect':
  6882. return connect(packet, stream, opts)
  6883. case 'connack':
  6884. return connack(packet, stream, opts)
  6885. case 'publish':
  6886. return publish(packet, stream, opts)
  6887. case 'puback':
  6888. case 'pubrec':
  6889. case 'pubrel':
  6890. case 'pubcomp':
  6891. return confirmation(packet, stream, opts)
  6892. case 'subscribe':
  6893. return subscribe(packet, stream, opts)
  6894. case 'suback':
  6895. return suback(packet, stream, opts)
  6896. case 'unsubscribe':
  6897. return unsubscribe(packet, stream, opts)
  6898. case 'unsuback':
  6899. return unsuback(packet, stream, opts)
  6900. case 'pingreq':
  6901. case 'pingresp':
  6902. return emptyPacket(packet, stream, opts)
  6903. case 'disconnect':
  6904. return disconnect(packet, stream, opts)
  6905. case 'auth':
  6906. return auth(packet, stream, opts)
  6907. default:
  6908. stream.emit('error', new Error('Unknown command'))
  6909. return false
  6910. }
  6911. }
  6912. /**
  6913. * Controls numbers cache.
  6914. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  6915. */
  6916. Object.defineProperty(generate, 'cacheNumbers', {
  6917. get: function () {
  6918. return writeNumber === writeNumberCached
  6919. },
  6920. set: function (value) {
  6921. if (value) {
  6922. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  6923. writeNumber = writeNumberCached
  6924. } else {
  6925. toGenerate = false
  6926. writeNumber = writeNumberGenerated
  6927. }
  6928. }
  6929. })
  6930. function uncork (stream) {
  6931. stream.uncork()
  6932. }
  6933. function connect (packet, stream, opts) {
  6934. var settings = packet || {}
  6935. var protocolId = settings.protocolId || 'MQTT'
  6936. var protocolVersion = settings.protocolVersion || 4
  6937. var will = settings.will
  6938. var clean = settings.clean
  6939. var keepalive = settings.keepalive || 0
  6940. var clientId = settings.clientId || ''
  6941. var username = settings.username
  6942. var password = settings.password
  6943. /* mqtt5 new oprions */
  6944. var properties = settings.properties
  6945. if (clean === undefined) clean = true
  6946. var length = 0
  6947. // Must be a string and non-falsy
  6948. if (!protocolId ||
  6949. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  6950. stream.emit('error', new Error('Invalid protocolId'))
  6951. return false
  6952. } else length += protocolId.length + 2
  6953. // Must be 3 or 4 or 5
  6954. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  6955. stream.emit('error', new Error('Invalid protocol version'))
  6956. return false
  6957. } else length += 1
  6958. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  6959. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  6960. (clientId || protocolVersion === 4) && (clientId || clean)) {
  6961. length += clientId.length + 2
  6962. } else {
  6963. if (protocolVersion < 4) {
  6964. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  6965. return false
  6966. }
  6967. if ((clean * 1) === 0) {
  6968. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  6969. return false
  6970. }
  6971. }
  6972. // Must be a two byte number
  6973. if (typeof keepalive !== 'number' ||
  6974. keepalive < 0 ||
  6975. keepalive > 65535 ||
  6976. keepalive % 1 !== 0) {
  6977. stream.emit('error', new Error('Invalid keepalive'))
  6978. return false
  6979. } else length += 2
  6980. // Connect flags
  6981. length += 1
  6982. // Properties
  6983. if (protocolVersion === 5) {
  6984. var propertiesData = getProperties(stream, properties)
  6985. length += propertiesData.length
  6986. }
  6987. // If will exists...
  6988. if (will) {
  6989. // It must be an object
  6990. if (typeof will !== 'object') {
  6991. stream.emit('error', new Error('Invalid will'))
  6992. return false
  6993. }
  6994. // It must have topic typeof string
  6995. if (!will.topic || typeof will.topic !== 'string') {
  6996. stream.emit('error', new Error('Invalid will topic'))
  6997. return false
  6998. } else {
  6999. length += Buffer.byteLength(will.topic) + 2
  7000. }
  7001. // Payload
  7002. if (will.payload) {
  7003. if (will.payload.length >= 0) {
  7004. if (typeof will.payload === 'string') {
  7005. length += Buffer.byteLength(will.payload) + 2
  7006. } else {
  7007. length += will.payload.length + 2
  7008. }
  7009. } else {
  7010. stream.emit('error', new Error('Invalid will payload'))
  7011. return false
  7012. }
  7013. // will properties
  7014. var willProperties = {}
  7015. if (protocolVersion === 5) {
  7016. willProperties = getProperties(stream, will.properties)
  7017. length += willProperties.length
  7018. }
  7019. }
  7020. }
  7021. // Username
  7022. var providedUsername = false
  7023. if (username != null) {
  7024. if (isStringOrBuffer(username)) {
  7025. providedUsername = true
  7026. length += Buffer.byteLength(username) + 2
  7027. } else {
  7028. stream.emit('error', new Error('Invalid username'))
  7029. return false
  7030. }
  7031. }
  7032. // Password
  7033. if (password != null) {
  7034. if (!providedUsername) {
  7035. stream.emit('error', new Error('Username is required to use password'))
  7036. return false
  7037. }
  7038. if (isStringOrBuffer(password)) {
  7039. length += byteLength(password) + 2
  7040. } else {
  7041. stream.emit('error', new Error('Invalid password'))
  7042. return false
  7043. }
  7044. }
  7045. // Generate header
  7046. stream.write(protocol.CONNECT_HEADER)
  7047. // Generate length
  7048. writeVarByteInt(stream, length)
  7049. // Generate protocol ID
  7050. writeStringOrBuffer(stream, protocolId)
  7051. stream.write(
  7052. protocolVersion === 4
  7053. ? protocol.VERSION4
  7054. : protocolVersion === 5
  7055. ? protocol.VERSION5
  7056. : protocol.VERSION3
  7057. )
  7058. // Connect flags
  7059. var flags = 0
  7060. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  7061. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  7062. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  7063. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  7064. flags |= will ? protocol.WILL_FLAG_MASK : 0
  7065. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  7066. stream.write(Buffer.from([flags]))
  7067. // Keepalive
  7068. writeNumber(stream, keepalive)
  7069. // Properties
  7070. if (protocolVersion === 5) {
  7071. propertiesData.write()
  7072. }
  7073. // Client ID
  7074. writeStringOrBuffer(stream, clientId)
  7075. // Will
  7076. if (will) {
  7077. if (protocolVersion === 5) {
  7078. willProperties.write()
  7079. }
  7080. writeString(stream, will.topic)
  7081. writeStringOrBuffer(stream, will.payload)
  7082. }
  7083. // Username and password
  7084. if (username != null) {
  7085. writeStringOrBuffer(stream, username)
  7086. }
  7087. if (password != null) {
  7088. writeStringOrBuffer(stream, password)
  7089. }
  7090. // This is a small packet that happens only once on a stream
  7091. // We assume the stream is always free to receive more data after this
  7092. return true
  7093. }
  7094. function connack (packet, stream, opts) {
  7095. var version = opts ? opts.protocolVersion : 4
  7096. var settings = packet || {}
  7097. var rc = version === 5 ? settings.reasonCode : settings.returnCode
  7098. var properties = settings.properties
  7099. var length = 2 // length of rc and sessionHeader
  7100. // Check return code
  7101. if (typeof rc !== 'number') {
  7102. stream.emit('error', new Error('Invalid return code'))
  7103. return false
  7104. }
  7105. // mqtt5 properties
  7106. var propertiesData = null
  7107. if (version === 5) {
  7108. propertiesData = getProperties(stream, properties)
  7109. length += propertiesData.length
  7110. }
  7111. stream.write(protocol.CONNACK_HEADER)
  7112. // length
  7113. writeVarByteInt(stream, length)
  7114. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  7115. stream.write(Buffer.from([rc]))
  7116. if (propertiesData != null) {
  7117. propertiesData.write()
  7118. }
  7119. return true
  7120. }
  7121. function publish (packet, stream, opts) {
  7122. var version = opts ? opts.protocolVersion : 4
  7123. var settings = packet || {}
  7124. var qos = settings.qos || 0
  7125. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  7126. var topic = settings.topic
  7127. var payload = settings.payload || empty
  7128. var id = settings.messageId
  7129. var properties = settings.properties
  7130. var length = 0
  7131. // Topic must be a non-empty string or Buffer
  7132. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  7133. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  7134. else {
  7135. stream.emit('error', new Error('Invalid topic'))
  7136. return false
  7137. }
  7138. // Get the payload length
  7139. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  7140. else length += payload.length
  7141. // Message ID must a number if qos > 0
  7142. if (qos && typeof id !== 'number') {
  7143. stream.emit('error', new Error('Invalid messageId'))
  7144. return false
  7145. } else if (qos) length += 2
  7146. // mqtt5 properties
  7147. var propertiesData = null
  7148. if (version === 5) {
  7149. propertiesData = getProperties(stream, properties)
  7150. length += propertiesData.length
  7151. }
  7152. // Header
  7153. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  7154. // Remaining length
  7155. writeVarByteInt(stream, length)
  7156. // Topic
  7157. writeNumber(stream, byteLength(topic))
  7158. stream.write(topic)
  7159. // Message ID
  7160. if (qos > 0) writeNumber(stream, id)
  7161. // Properties
  7162. if (propertiesData != null) {
  7163. propertiesData.write()
  7164. }
  7165. // Payload
  7166. return stream.write(payload)
  7167. }
  7168. /* Puback, pubrec, pubrel and pubcomp */
  7169. function confirmation (packet, stream, opts) {
  7170. var version = opts ? opts.protocolVersion : 4
  7171. var settings = packet || {}
  7172. var type = settings.cmd || 'puback'
  7173. var id = settings.messageId
  7174. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  7175. var qos = 0
  7176. var reasonCode = settings.reasonCode
  7177. var properties = settings.properties
  7178. var length = version === 5 ? 3 : 2
  7179. if (type === 'pubrel') qos = 1
  7180. // Check message ID
  7181. if (typeof id !== 'number') {
  7182. stream.emit('error', new Error('Invalid messageId'))
  7183. return false
  7184. }
  7185. // properies mqtt 5
  7186. var propertiesData = null
  7187. if (version === 5) {
  7188. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7189. if (!propertiesData) { return false }
  7190. length += propertiesData.length
  7191. }
  7192. // Header
  7193. stream.write(protocol.ACKS[type][qos][dup][0])
  7194. // Length
  7195. writeVarByteInt(stream, length)
  7196. // Message ID
  7197. writeNumber(stream, id)
  7198. // reason code in header
  7199. if (version === 5) {
  7200. stream.write(Buffer.from([reasonCode]))
  7201. }
  7202. // properies mqtt 5
  7203. if (propertiesData !== null) {
  7204. propertiesData.write()
  7205. }
  7206. return true
  7207. }
  7208. function subscribe (packet, stream, opts) {
  7209. var version = opts ? opts.protocolVersion : 4
  7210. var settings = packet || {}
  7211. var dup = settings.dup ? protocol.DUP_MASK : 0
  7212. var id = settings.messageId
  7213. var subs = settings.subscriptions
  7214. var properties = settings.properties
  7215. var length = 0
  7216. // Check message ID
  7217. if (typeof id !== 'number') {
  7218. stream.emit('error', new Error('Invalid messageId'))
  7219. return false
  7220. } else length += 2
  7221. // properies mqtt 5
  7222. var propertiesData = null
  7223. if (version === 5) {
  7224. propertiesData = getProperties(stream, properties)
  7225. length += propertiesData.length
  7226. }
  7227. // Check subscriptions
  7228. if (typeof subs === 'object' && subs.length) {
  7229. for (var i = 0; i < subs.length; i += 1) {
  7230. var itopic = subs[i].topic
  7231. var iqos = subs[i].qos
  7232. if (typeof itopic !== 'string') {
  7233. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  7234. return false
  7235. }
  7236. if (typeof iqos !== 'number') {
  7237. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  7238. return false
  7239. }
  7240. if (version === 5) {
  7241. var nl = subs[i].nl || false
  7242. if (typeof nl !== 'boolean') {
  7243. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  7244. return false
  7245. }
  7246. var rap = subs[i].rap || false
  7247. if (typeof rap !== 'boolean') {
  7248. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  7249. return false
  7250. }
  7251. var rh = subs[i].rh || 0
  7252. if (typeof rh !== 'number' || rh > 2) {
  7253. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  7254. return false
  7255. }
  7256. }
  7257. length += Buffer.byteLength(itopic) + 2 + 1
  7258. }
  7259. } else {
  7260. stream.emit('error', new Error('Invalid subscriptions'))
  7261. return false
  7262. }
  7263. // Generate header
  7264. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  7265. // Generate length
  7266. writeVarByteInt(stream, length)
  7267. // Generate message ID
  7268. writeNumber(stream, id)
  7269. // properies mqtt 5
  7270. if (propertiesData !== null) {
  7271. propertiesData.write()
  7272. }
  7273. var result = true
  7274. // Generate subs
  7275. for (var j = 0; j < subs.length; j++) {
  7276. var sub = subs[j]
  7277. var jtopic = sub.topic
  7278. var jqos = sub.qos
  7279. var jnl = +sub.nl
  7280. var jrap = +sub.rap
  7281. var jrh = sub.rh
  7282. var joptions
  7283. // Write topic string
  7284. writeString(stream, jtopic)
  7285. // options process
  7286. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  7287. if (version === 5) {
  7288. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  7289. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  7290. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  7291. }
  7292. // Write options
  7293. result = stream.write(Buffer.from([joptions]))
  7294. }
  7295. return result
  7296. }
  7297. function suback (packet, stream, opts) {
  7298. var version = opts ? opts.protocolVersion : 4
  7299. var settings = packet || {}
  7300. var id = settings.messageId
  7301. var granted = settings.granted
  7302. var properties = settings.properties
  7303. var length = 0
  7304. // Check message ID
  7305. if (typeof id !== 'number') {
  7306. stream.emit('error', new Error('Invalid messageId'))
  7307. return false
  7308. } else length += 2
  7309. // Check granted qos vector
  7310. if (typeof granted === 'object' && granted.length) {
  7311. for (var i = 0; i < granted.length; i += 1) {
  7312. if (typeof granted[i] !== 'number') {
  7313. stream.emit('error', new Error('Invalid qos vector'))
  7314. return false
  7315. }
  7316. length += 1
  7317. }
  7318. } else {
  7319. stream.emit('error', new Error('Invalid qos vector'))
  7320. return false
  7321. }
  7322. // properies mqtt 5
  7323. var propertiesData = null
  7324. if (version === 5) {
  7325. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7326. if (!propertiesData) { return false }
  7327. length += propertiesData.length
  7328. }
  7329. // header
  7330. stream.write(protocol.SUBACK_HEADER)
  7331. // Length
  7332. writeVarByteInt(stream, length)
  7333. // Message ID
  7334. writeNumber(stream, id)
  7335. // properies mqtt 5
  7336. if (propertiesData !== null) {
  7337. propertiesData.write()
  7338. }
  7339. return stream.write(Buffer.from(granted))
  7340. }
  7341. function unsubscribe (packet, stream, opts) {
  7342. var version = opts ? opts.protocolVersion : 4
  7343. var settings = packet || {}
  7344. var id = settings.messageId
  7345. var dup = settings.dup ? protocol.DUP_MASK : 0
  7346. var unsubs = settings.unsubscriptions
  7347. var properties = settings.properties
  7348. var length = 0
  7349. // Check message ID
  7350. if (typeof id !== 'number') {
  7351. stream.emit('error', new Error('Invalid messageId'))
  7352. return false
  7353. } else {
  7354. length += 2
  7355. }
  7356. // Check unsubs
  7357. if (typeof unsubs === 'object' && unsubs.length) {
  7358. for (var i = 0; i < unsubs.length; i += 1) {
  7359. if (typeof unsubs[i] !== 'string') {
  7360. stream.emit('error', new Error('Invalid unsubscriptions'))
  7361. return false
  7362. }
  7363. length += Buffer.byteLength(unsubs[i]) + 2
  7364. }
  7365. } else {
  7366. stream.emit('error', new Error('Invalid unsubscriptions'))
  7367. return false
  7368. }
  7369. // properies mqtt 5
  7370. var propertiesData = null
  7371. if (version === 5) {
  7372. propertiesData = getProperties(stream, properties)
  7373. length += propertiesData.length
  7374. }
  7375. // Header
  7376. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  7377. // Length
  7378. writeVarByteInt(stream, length)
  7379. // Message ID
  7380. writeNumber(stream, id)
  7381. // properies mqtt 5
  7382. if (propertiesData !== null) {
  7383. propertiesData.write()
  7384. }
  7385. // Unsubs
  7386. var result = true
  7387. for (var j = 0; j < unsubs.length; j++) {
  7388. result = writeString(stream, unsubs[j])
  7389. }
  7390. return result
  7391. }
  7392. function unsuback (packet, stream, opts) {
  7393. var version = opts ? opts.protocolVersion : 4
  7394. var settings = packet || {}
  7395. var id = settings.messageId
  7396. var dup = settings.dup ? protocol.DUP_MASK : 0
  7397. var granted = settings.granted
  7398. var properties = settings.properties
  7399. var type = settings.cmd
  7400. var qos = 0
  7401. var length = 2
  7402. // Check message ID
  7403. if (typeof id !== 'number') {
  7404. stream.emit('error', new Error('Invalid messageId'))
  7405. return false
  7406. }
  7407. // Check granted
  7408. if (version === 5) {
  7409. if (typeof granted === 'object' && granted.length) {
  7410. for (var i = 0; i < granted.length; i += 1) {
  7411. if (typeof granted[i] !== 'number') {
  7412. stream.emit('error', new Error('Invalid qos vector'))
  7413. return false
  7414. }
  7415. length += 1
  7416. }
  7417. } else {
  7418. stream.emit('error', new Error('Invalid qos vector'))
  7419. return false
  7420. }
  7421. }
  7422. // properies mqtt 5
  7423. var propertiesData = null
  7424. if (version === 5) {
  7425. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7426. if (!propertiesData) { return false }
  7427. length += propertiesData.length
  7428. }
  7429. // Header
  7430. stream.write(protocol.ACKS[type][qos][dup][0])
  7431. // Length
  7432. writeVarByteInt(stream, length)
  7433. // Message ID
  7434. writeNumber(stream, id)
  7435. // properies mqtt 5
  7436. if (propertiesData !== null) {
  7437. propertiesData.write()
  7438. }
  7439. // payload
  7440. if (version === 5) {
  7441. stream.write(Buffer.from(granted))
  7442. }
  7443. return true
  7444. }
  7445. function emptyPacket (packet, stream, opts) {
  7446. return stream.write(protocol.EMPTY[packet.cmd])
  7447. }
  7448. function disconnect (packet, stream, opts) {
  7449. var version = opts ? opts.protocolVersion : 4
  7450. var settings = packet || {}
  7451. var reasonCode = settings.reasonCode
  7452. var properties = settings.properties
  7453. var length = version === 5 ? 1 : 0
  7454. // properies mqtt 5
  7455. var propertiesData = null
  7456. if (version === 5) {
  7457. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7458. if (!propertiesData) { return false }
  7459. length += propertiesData.length
  7460. }
  7461. // Header
  7462. stream.write(Buffer.from([protocol.codes['disconnect'] << 4]))
  7463. // Length
  7464. writeVarByteInt(stream, length)
  7465. // reason code in header
  7466. if (version === 5) {
  7467. stream.write(Buffer.from([reasonCode]))
  7468. }
  7469. // properies mqtt 5
  7470. if (propertiesData !== null) {
  7471. propertiesData.write()
  7472. }
  7473. return true
  7474. }
  7475. function auth (packet, stream, opts) {
  7476. var version = opts ? opts.protocolVersion : 4
  7477. var settings = packet || {}
  7478. var reasonCode = settings.reasonCode
  7479. var properties = settings.properties
  7480. var length = version === 5 ? 1 : 0
  7481. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  7482. // properies mqtt 5
  7483. var propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7484. if (!propertiesData) { return false }
  7485. length += propertiesData.length
  7486. // Header
  7487. stream.write(Buffer.from([protocol.codes['auth'] << 4]))
  7488. // Length
  7489. writeVarByteInt(stream, length)
  7490. // reason code in header
  7491. stream.write(Buffer.from([reasonCode]))
  7492. // properies mqtt 5
  7493. if (propertiesData !== null) {
  7494. propertiesData.write()
  7495. }
  7496. return true
  7497. }
  7498. /**
  7499. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  7500. *
  7501. * @param <Buffer> buffer - destination
  7502. * @param <Number> pos - offset
  7503. * @param <Number> length - length (>0)
  7504. * @returns <Number> number of bytes written
  7505. *
  7506. * @api private
  7507. */
  7508. var varByteIntCache = {}
  7509. function writeVarByteInt (stream, num) {
  7510. var buffer = varByteIntCache[num]
  7511. if (!buffer) {
  7512. buffer = genBufVariableByteInt(num).data
  7513. if (num < 16384) varByteIntCache[num] = buffer
  7514. }
  7515. stream.write(buffer)
  7516. }
  7517. /**
  7518. * writeString - write a utf8 string to the buffer
  7519. *
  7520. * @param <Buffer> buffer - destination
  7521. * @param <Number> pos - offset
  7522. * @param <String> string - string to write
  7523. * @return <Number> number of bytes written
  7524. *
  7525. * @api private
  7526. */
  7527. function writeString (stream, string) {
  7528. var strlen = Buffer.byteLength(string)
  7529. writeNumber(stream, strlen)
  7530. stream.write(string, 'utf8')
  7531. }
  7532. /**
  7533. * writeStringPair - write a utf8 string pairs to the buffer
  7534. *
  7535. * @param <Buffer> buffer - destination
  7536. * @param <String> name - string name to write
  7537. * @param <String> value - string value to write
  7538. * @return <Number> number of bytes written
  7539. *
  7540. * @api private
  7541. */
  7542. function writeStringPair (stream, name, value) {
  7543. writeString(stream, name)
  7544. writeString(stream, value)
  7545. }
  7546. /**
  7547. * writeNumber - write a two byte number to the buffer
  7548. *
  7549. * @param <Buffer> buffer - destination
  7550. * @param <Number> pos - offset
  7551. * @param <String> number - number to write
  7552. * @return <Number> number of bytes written
  7553. *
  7554. * @api private
  7555. */
  7556. function writeNumberCached (stream, number) {
  7557. return stream.write(numCache[number])
  7558. }
  7559. function writeNumberGenerated (stream, number) {
  7560. return stream.write(generateNumber(number))
  7561. }
  7562. function write4ByteNumber (stream, number) {
  7563. return stream.write(generate4ByteBuffer(number))
  7564. }
  7565. /**
  7566. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  7567. *
  7568. * @param <Buffer> buffer - destination
  7569. * @param <Number> pos - offset
  7570. * @param <String> toWrite - String or Buffer
  7571. * @return <Number> number of bytes written
  7572. */
  7573. function writeStringOrBuffer (stream, toWrite) {
  7574. if (typeof toWrite === 'string') {
  7575. writeString(stream, toWrite)
  7576. } else if (toWrite) {
  7577. writeNumber(stream, toWrite.length)
  7578. stream.write(toWrite)
  7579. } else writeNumber(stream, 0)
  7580. }
  7581. function getProperties (stream, properties) {
  7582. /* connect properties */
  7583. if (typeof properties !== 'object' || properties.length != null) {
  7584. return {
  7585. length: 1,
  7586. write: function () {
  7587. writeProperties(stream, {}, 0)
  7588. }
  7589. }
  7590. }
  7591. var propertiesLength = 0
  7592. function getLengthProperty (name) {
  7593. var type = protocol.propertiesTypes[name]
  7594. var value = properties[name]
  7595. var length = 0
  7596. switch (type) {
  7597. case 'byte': {
  7598. if (typeof value !== 'boolean') {
  7599. stream.emit('error', new Error('Invalid ' + name))
  7600. return false
  7601. }
  7602. length += 1 + 1
  7603. break
  7604. }
  7605. case 'int8': {
  7606. if (typeof value !== 'number') {
  7607. stream.emit('error', new Error('Invalid ' + name))
  7608. return false
  7609. }
  7610. length += 1 + 1
  7611. break
  7612. }
  7613. case 'binary': {
  7614. if (value && value === null) {
  7615. stream.emit('error', new Error('Invalid ' + name))
  7616. return false
  7617. }
  7618. length += 1 + Buffer.byteLength(value) + 2
  7619. break
  7620. }
  7621. case 'int16': {
  7622. if (typeof value !== 'number') {
  7623. stream.emit('error', new Error('Invalid ' + name))
  7624. return false
  7625. }
  7626. length += 1 + 2
  7627. break
  7628. }
  7629. case 'int32': {
  7630. if (typeof value !== 'number') {
  7631. stream.emit('error', new Error('Invalid ' + name))
  7632. return false
  7633. }
  7634. length += 1 + 4
  7635. break
  7636. }
  7637. case 'var': {
  7638. if (typeof value !== 'number') {
  7639. stream.emit('error', new Error('Invalid ' + name))
  7640. return false
  7641. }
  7642. length += 1 + genBufVariableByteInt(value).length
  7643. break
  7644. }
  7645. case 'string': {
  7646. if (typeof value !== 'string') {
  7647. stream.emit('error', new Error('Invalid ' + name))
  7648. return false
  7649. }
  7650. length += 1 + 2 + Buffer.byteLength(value.toString())
  7651. break
  7652. }
  7653. case 'pair': {
  7654. if (typeof value !== 'object') {
  7655. stream.emit('error', new Error('Invalid ' + name))
  7656. return false
  7657. }
  7658. length += Object.getOwnPropertyNames(value).reduce(function (result, name) {
  7659. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  7660. return result
  7661. }, 0)
  7662. break
  7663. }
  7664. default: {
  7665. stream.emit('error', new Error('Invalid property ' + name))
  7666. return false
  7667. }
  7668. }
  7669. return length
  7670. }
  7671. if (properties) {
  7672. for (var propName in properties) {
  7673. var propLength = getLengthProperty(propName)
  7674. if (!propLength) return false
  7675. propertiesLength += propLength
  7676. }
  7677. }
  7678. var propertiesLengthLength = genBufVariableByteInt(propertiesLength).length
  7679. return {
  7680. length: propertiesLengthLength + propertiesLength,
  7681. write: function () {
  7682. writeProperties(stream, properties, propertiesLength)
  7683. }
  7684. }
  7685. }
  7686. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  7687. var mayEmptyProps = ['reasonString', 'userProperties']
  7688. var maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  7689. var propertiesData = getProperties(stream, properties)
  7690. if (maximumPacketSize) {
  7691. while (length + propertiesData.length > maximumPacketSize) {
  7692. var currentMayEmptyProp = mayEmptyProps.shift()
  7693. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  7694. delete properties[currentMayEmptyProp]
  7695. propertiesData = getProperties(stream, properties)
  7696. } else {
  7697. return false
  7698. }
  7699. }
  7700. }
  7701. return propertiesData
  7702. }
  7703. function writeProperties (stream, properties, propertiesLength) {
  7704. /* write properties to stream */
  7705. writeVarByteInt(stream, propertiesLength)
  7706. for (var propName in properties) {
  7707. if (properties.hasOwnProperty(propName) && properties[propName] !== null) {
  7708. var value = properties[propName]
  7709. var type = protocol.propertiesTypes[propName]
  7710. switch (type) {
  7711. case 'byte': {
  7712. stream.write(Buffer.from([protocol.properties[propName]]))
  7713. stream.write(Buffer.from([+value]))
  7714. break
  7715. }
  7716. case 'int8': {
  7717. stream.write(Buffer.from([protocol.properties[propName]]))
  7718. stream.write(Buffer.from([value]))
  7719. break
  7720. }
  7721. case 'binary': {
  7722. stream.write(Buffer.from([protocol.properties[propName]]))
  7723. writeStringOrBuffer(stream, value)
  7724. break
  7725. }
  7726. case 'int16': {
  7727. stream.write(Buffer.from([protocol.properties[propName]]))
  7728. writeNumber(stream, value)
  7729. break
  7730. }
  7731. case 'int32': {
  7732. stream.write(Buffer.from([protocol.properties[propName]]))
  7733. write4ByteNumber(stream, value)
  7734. break
  7735. }
  7736. case 'var': {
  7737. stream.write(Buffer.from([protocol.properties[propName]]))
  7738. writeVarByteInt(stream, value)
  7739. break
  7740. }
  7741. case 'string': {
  7742. stream.write(Buffer.from([protocol.properties[propName]]))
  7743. writeString(stream, value)
  7744. break
  7745. }
  7746. case 'pair': {
  7747. Object.getOwnPropertyNames(value).forEach(function (name) {
  7748. stream.write(Buffer.from([protocol.properties[propName]]))
  7749. writeStringPair(stream, name.toString(), value[name].toString())
  7750. })
  7751. break
  7752. }
  7753. default: {
  7754. stream.emit('error', new Error('Invalid property ' + propName))
  7755. return false
  7756. }
  7757. }
  7758. }
  7759. }
  7760. }
  7761. function byteLength (bufOrString) {
  7762. if (!bufOrString) return 0
  7763. else if (bufOrString instanceof Buffer) return bufOrString.length
  7764. else return Buffer.byteLength(bufOrString)
  7765. }
  7766. function isStringOrBuffer (field) {
  7767. return typeof field === 'string' || field instanceof Buffer
  7768. }
  7769. module.exports = generate
  7770. },{"./constants":82,"./numbers":86,"process-nextick-args":91,"safe-buffer":110}],90:[function(require,module,exports){
  7771. var wrappy = require('wrappy')
  7772. module.exports = wrappy(once)
  7773. module.exports.strict = wrappy(onceStrict)
  7774. once.proto = once(function () {
  7775. Object.defineProperty(Function.prototype, 'once', {
  7776. value: function () {
  7777. return once(this)
  7778. },
  7779. configurable: true
  7780. })
  7781. Object.defineProperty(Function.prototype, 'onceStrict', {
  7782. value: function () {
  7783. return onceStrict(this)
  7784. },
  7785. configurable: true
  7786. })
  7787. })
  7788. function once (fn) {
  7789. var f = function () {
  7790. if (f.called) return f.value
  7791. f.called = true
  7792. return f.value = fn.apply(this, arguments)
  7793. }
  7794. f.called = false
  7795. return f
  7796. }
  7797. function onceStrict (fn) {
  7798. var f = function () {
  7799. if (f.called)
  7800. throw new Error(f.onceError)
  7801. f.called = true
  7802. return f.value = fn.apply(this, arguments)
  7803. }
  7804. var name = fn.name || 'Function wrapped with `once`'
  7805. f.onceError = name + " shouldn't be called more than once"
  7806. f.called = false
  7807. return f
  7808. }
  7809. },{"wrappy":120}],91:[function(require,module,exports){
  7810. (function (process){
  7811. 'use strict';
  7812. if (!process.version ||
  7813. process.version.indexOf('v0.') === 0 ||
  7814. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  7815. module.exports = { nextTick: nextTick };
  7816. } else {
  7817. module.exports = process
  7818. }
  7819. function nextTick(fn, arg1, arg2, arg3) {
  7820. if (typeof fn !== 'function') {
  7821. throw new TypeError('"callback" argument must be a function');
  7822. }
  7823. var len = arguments.length;
  7824. var args, i;
  7825. switch (len) {
  7826. case 0:
  7827. case 1:
  7828. return process.nextTick(fn);
  7829. case 2:
  7830. return process.nextTick(function afterTickOne() {
  7831. fn.call(null, arg1);
  7832. });
  7833. case 3:
  7834. return process.nextTick(function afterTickTwo() {
  7835. fn.call(null, arg1, arg2);
  7836. });
  7837. case 4:
  7838. return process.nextTick(function afterTickThree() {
  7839. fn.call(null, arg1, arg2, arg3);
  7840. });
  7841. default:
  7842. args = new Array(len - 1);
  7843. i = 0;
  7844. while (i < args.length) {
  7845. args[i++] = arguments[i];
  7846. }
  7847. return process.nextTick(function afterTick() {
  7848. fn.apply(null, args);
  7849. });
  7850. }
  7851. }
  7852. }).call(this,require('_process'))
  7853. },{"_process":92}],92:[function(require,module,exports){
  7854. // shim for using process in browser
  7855. var process = module.exports = {};
  7856. // cached from whatever global is present so that test runners that stub it
  7857. // don't break things. But we need to wrap it in a try catch in case it is
  7858. // wrapped in strict mode code which doesn't define any globals. It's inside a
  7859. // function because try/catches deoptimize in certain engines.
  7860. var cachedSetTimeout;
  7861. var cachedClearTimeout;
  7862. function defaultSetTimout() {
  7863. throw new Error('setTimeout has not been defined');
  7864. }
  7865. function defaultClearTimeout () {
  7866. throw new Error('clearTimeout has not been defined');
  7867. }
  7868. (function () {
  7869. try {
  7870. if (typeof setTimeout === 'function') {
  7871. cachedSetTimeout = setTimeout;
  7872. } else {
  7873. cachedSetTimeout = defaultSetTimout;
  7874. }
  7875. } catch (e) {
  7876. cachedSetTimeout = defaultSetTimout;
  7877. }
  7878. try {
  7879. if (typeof clearTimeout === 'function') {
  7880. cachedClearTimeout = clearTimeout;
  7881. } else {
  7882. cachedClearTimeout = defaultClearTimeout;
  7883. }
  7884. } catch (e) {
  7885. cachedClearTimeout = defaultClearTimeout;
  7886. }
  7887. } ())
  7888. function runTimeout(fun) {
  7889. if (cachedSetTimeout === setTimeout) {
  7890. //normal enviroments in sane situations
  7891. return setTimeout(fun, 0);
  7892. }
  7893. // if setTimeout wasn't available but was latter defined
  7894. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  7895. cachedSetTimeout = setTimeout;
  7896. return setTimeout(fun, 0);
  7897. }
  7898. try {
  7899. // when when somebody has screwed with setTimeout but no I.E. maddness
  7900. return cachedSetTimeout(fun, 0);
  7901. } catch(e){
  7902. try {
  7903. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7904. return cachedSetTimeout.call(null, fun, 0);
  7905. } catch(e){
  7906. // 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
  7907. return cachedSetTimeout.call(this, fun, 0);
  7908. }
  7909. }
  7910. }
  7911. function runClearTimeout(marker) {
  7912. if (cachedClearTimeout === clearTimeout) {
  7913. //normal enviroments in sane situations
  7914. return clearTimeout(marker);
  7915. }
  7916. // if clearTimeout wasn't available but was latter defined
  7917. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  7918. cachedClearTimeout = clearTimeout;
  7919. return clearTimeout(marker);
  7920. }
  7921. try {
  7922. // when when somebody has screwed with setTimeout but no I.E. maddness
  7923. return cachedClearTimeout(marker);
  7924. } catch (e){
  7925. try {
  7926. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7927. return cachedClearTimeout.call(null, marker);
  7928. } catch (e){
  7929. // 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.
  7930. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  7931. return cachedClearTimeout.call(this, marker);
  7932. }
  7933. }
  7934. }
  7935. var queue = [];
  7936. var draining = false;
  7937. var currentQueue;
  7938. var queueIndex = -1;
  7939. function cleanUpNextTick() {
  7940. if (!draining || !currentQueue) {
  7941. return;
  7942. }
  7943. draining = false;
  7944. if (currentQueue.length) {
  7945. queue = currentQueue.concat(queue);
  7946. } else {
  7947. queueIndex = -1;
  7948. }
  7949. if (queue.length) {
  7950. drainQueue();
  7951. }
  7952. }
  7953. function drainQueue() {
  7954. if (draining) {
  7955. return;
  7956. }
  7957. var timeout = runTimeout(cleanUpNextTick);
  7958. draining = true;
  7959. var len = queue.length;
  7960. while(len) {
  7961. currentQueue = queue;
  7962. queue = [];
  7963. while (++queueIndex < len) {
  7964. if (currentQueue) {
  7965. currentQueue[queueIndex].run();
  7966. }
  7967. }
  7968. queueIndex = -1;
  7969. len = queue.length;
  7970. }
  7971. currentQueue = null;
  7972. draining = false;
  7973. runClearTimeout(timeout);
  7974. }
  7975. process.nextTick = function (fun) {
  7976. var args = new Array(arguments.length - 1);
  7977. if (arguments.length > 1) {
  7978. for (var i = 1; i < arguments.length; i++) {
  7979. args[i - 1] = arguments[i];
  7980. }
  7981. }
  7982. queue.push(new Item(fun, args));
  7983. if (queue.length === 1 && !draining) {
  7984. runTimeout(drainQueue);
  7985. }
  7986. };
  7987. // v8 likes predictible objects
  7988. function Item(fun, array) {
  7989. this.fun = fun;
  7990. this.array = array;
  7991. }
  7992. Item.prototype.run = function () {
  7993. this.fun.apply(null, this.array);
  7994. };
  7995. process.title = 'browser';
  7996. process.browser = true;
  7997. process.env = {};
  7998. process.argv = [];
  7999. process.version = ''; // empty string to avoid regexp issues
  8000. process.versions = {};
  8001. function noop() {}
  8002. process.on = noop;
  8003. process.addListener = noop;
  8004. process.once = noop;
  8005. process.off = noop;
  8006. process.removeListener = noop;
  8007. process.removeAllListeners = noop;
  8008. process.emit = noop;
  8009. process.prependListener = noop;
  8010. process.prependOnceListener = noop;
  8011. process.listeners = function (name) { return [] }
  8012. process.binding = function (name) {
  8013. throw new Error('process.binding is not supported');
  8014. };
  8015. process.cwd = function () { return '/' };
  8016. process.chdir = function (dir) {
  8017. throw new Error('process.chdir is not supported');
  8018. };
  8019. process.umask = function() { return 0; };
  8020. },{}],93:[function(require,module,exports){
  8021. (function (global){
  8022. /*! https://mths.be/punycode v1.4.1 by @mathias */
  8023. ;(function(root) {
  8024. /** Detect free variables */
  8025. var freeExports = typeof exports == 'object' && exports &&
  8026. !exports.nodeType && exports;
  8027. var freeModule = typeof module == 'object' && module &&
  8028. !module.nodeType && module;
  8029. var freeGlobal = typeof global == 'object' && global;
  8030. if (
  8031. freeGlobal.global === freeGlobal ||
  8032. freeGlobal.window === freeGlobal ||
  8033. freeGlobal.self === freeGlobal
  8034. ) {
  8035. root = freeGlobal;
  8036. }
  8037. /**
  8038. * The `punycode` object.
  8039. * @name punycode
  8040. * @type Object
  8041. */
  8042. var punycode,
  8043. /** Highest positive signed 32-bit float value */
  8044. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  8045. /** Bootstring parameters */
  8046. base = 36,
  8047. tMin = 1,
  8048. tMax = 26,
  8049. skew = 38,
  8050. damp = 700,
  8051. initialBias = 72,
  8052. initialN = 128, // 0x80
  8053. delimiter = '-', // '\x2D'
  8054. /** Regular expressions */
  8055. regexPunycode = /^xn--/,
  8056. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  8057. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  8058. /** Error messages */
  8059. errors = {
  8060. 'overflow': 'Overflow: input needs wider integers to process',
  8061. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  8062. 'invalid-input': 'Invalid input'
  8063. },
  8064. /** Convenience shortcuts */
  8065. baseMinusTMin = base - tMin,
  8066. floor = Math.floor,
  8067. stringFromCharCode = String.fromCharCode,
  8068. /** Temporary variable */
  8069. key;
  8070. /*--------------------------------------------------------------------------*/
  8071. /**
  8072. * A generic error utility function.
  8073. * @private
  8074. * @param {String} type The error type.
  8075. * @returns {Error} Throws a `RangeError` with the applicable error message.
  8076. */
  8077. function error(type) {
  8078. throw new RangeError(errors[type]);
  8079. }
  8080. /**
  8081. * A generic `Array#map` utility function.
  8082. * @private
  8083. * @param {Array} array The array to iterate over.
  8084. * @param {Function} callback The function that gets called for every array
  8085. * item.
  8086. * @returns {Array} A new array of values returned by the callback function.
  8087. */
  8088. function map(array, fn) {
  8089. var length = array.length;
  8090. var result = [];
  8091. while (length--) {
  8092. result[length] = fn(array[length]);
  8093. }
  8094. return result;
  8095. }
  8096. /**
  8097. * A simple `Array#map`-like wrapper to work with domain name strings or email
  8098. * addresses.
  8099. * @private
  8100. * @param {String} domain The domain name or email address.
  8101. * @param {Function} callback The function that gets called for every
  8102. * character.
  8103. * @returns {Array} A new string of characters returned by the callback
  8104. * function.
  8105. */
  8106. function mapDomain(string, fn) {
  8107. var parts = string.split('@');
  8108. var result = '';
  8109. if (parts.length > 1) {
  8110. // In email addresses, only the domain name should be punycoded. Leave
  8111. // the local part (i.e. everything up to `@`) intact.
  8112. result = parts[0] + '@';
  8113. string = parts[1];
  8114. }
  8115. // Avoid `split(regex)` for IE8 compatibility. See #17.
  8116. string = string.replace(regexSeparators, '\x2E');
  8117. var labels = string.split('.');
  8118. var encoded = map(labels, fn).join('.');
  8119. return result + encoded;
  8120. }
  8121. /**
  8122. * Creates an array containing the numeric code points of each Unicode
  8123. * character in the string. While JavaScript uses UCS-2 internally,
  8124. * this function will convert a pair of surrogate halves (each of which
  8125. * UCS-2 exposes as separate characters) into a single code point,
  8126. * matching UTF-16.
  8127. * @see `punycode.ucs2.encode`
  8128. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8129. * @memberOf punycode.ucs2
  8130. * @name decode
  8131. * @param {String} string The Unicode input string (UCS-2).
  8132. * @returns {Array} The new array of code points.
  8133. */
  8134. function ucs2decode(string) {
  8135. var output = [],
  8136. counter = 0,
  8137. length = string.length,
  8138. value,
  8139. extra;
  8140. while (counter < length) {
  8141. value = string.charCodeAt(counter++);
  8142. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  8143. // high surrogate, and there is a next character
  8144. extra = string.charCodeAt(counter++);
  8145. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  8146. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  8147. } else {
  8148. // unmatched surrogate; only append this code unit, in case the next
  8149. // code unit is the high surrogate of a surrogate pair
  8150. output.push(value);
  8151. counter--;
  8152. }
  8153. } else {
  8154. output.push(value);
  8155. }
  8156. }
  8157. return output;
  8158. }
  8159. /**
  8160. * Creates a string based on an array of numeric code points.
  8161. * @see `punycode.ucs2.decode`
  8162. * @memberOf punycode.ucs2
  8163. * @name encode
  8164. * @param {Array} codePoints The array of numeric code points.
  8165. * @returns {String} The new Unicode string (UCS-2).
  8166. */
  8167. function ucs2encode(array) {
  8168. return map(array, function(value) {
  8169. var output = '';
  8170. if (value > 0xFFFF) {
  8171. value -= 0x10000;
  8172. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  8173. value = 0xDC00 | value & 0x3FF;
  8174. }
  8175. output += stringFromCharCode(value);
  8176. return output;
  8177. }).join('');
  8178. }
  8179. /**
  8180. * Converts a basic code point into a digit/integer.
  8181. * @see `digitToBasic()`
  8182. * @private
  8183. * @param {Number} codePoint The basic numeric code point value.
  8184. * @returns {Number} The numeric value of a basic code point (for use in
  8185. * representing integers) in the range `0` to `base - 1`, or `base` if
  8186. * the code point does not represent a value.
  8187. */
  8188. function basicToDigit(codePoint) {
  8189. if (codePoint - 48 < 10) {
  8190. return codePoint - 22;
  8191. }
  8192. if (codePoint - 65 < 26) {
  8193. return codePoint - 65;
  8194. }
  8195. if (codePoint - 97 < 26) {
  8196. return codePoint - 97;
  8197. }
  8198. return base;
  8199. }
  8200. /**
  8201. * Converts a digit/integer into a basic code point.
  8202. * @see `basicToDigit()`
  8203. * @private
  8204. * @param {Number} digit The numeric value of a basic code point.
  8205. * @returns {Number} The basic code point whose value (when used for
  8206. * representing integers) is `digit`, which needs to be in the range
  8207. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  8208. * used; else, the lowercase form is used. The behavior is undefined
  8209. * if `flag` is non-zero and `digit` has no uppercase form.
  8210. */
  8211. function digitToBasic(digit, flag) {
  8212. // 0..25 map to ASCII a..z or A..Z
  8213. // 26..35 map to ASCII 0..9
  8214. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  8215. }
  8216. /**
  8217. * Bias adaptation function as per section 3.4 of RFC 3492.
  8218. * https://tools.ietf.org/html/rfc3492#section-3.4
  8219. * @private
  8220. */
  8221. function adapt(delta, numPoints, firstTime) {
  8222. var k = 0;
  8223. delta = firstTime ? floor(delta / damp) : delta >> 1;
  8224. delta += floor(delta / numPoints);
  8225. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  8226. delta = floor(delta / baseMinusTMin);
  8227. }
  8228. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  8229. }
  8230. /**
  8231. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  8232. * symbols.
  8233. * @memberOf punycode
  8234. * @param {String} input The Punycode string of ASCII-only symbols.
  8235. * @returns {String} The resulting string of Unicode symbols.
  8236. */
  8237. function decode(input) {
  8238. // Don't use UCS-2
  8239. var output = [],
  8240. inputLength = input.length,
  8241. out,
  8242. i = 0,
  8243. n = initialN,
  8244. bias = initialBias,
  8245. basic,
  8246. j,
  8247. index,
  8248. oldi,
  8249. w,
  8250. k,
  8251. digit,
  8252. t,
  8253. /** Cached calculation results */
  8254. baseMinusT;
  8255. // Handle the basic code points: let `basic` be the number of input code
  8256. // points before the last delimiter, or `0` if there is none, then copy
  8257. // the first basic code points to the output.
  8258. basic = input.lastIndexOf(delimiter);
  8259. if (basic < 0) {
  8260. basic = 0;
  8261. }
  8262. for (j = 0; j < basic; ++j) {
  8263. // if it's not a basic code point
  8264. if (input.charCodeAt(j) >= 0x80) {
  8265. error('not-basic');
  8266. }
  8267. output.push(input.charCodeAt(j));
  8268. }
  8269. // Main decoding loop: start just after the last delimiter if any basic code
  8270. // points were copied; start at the beginning otherwise.
  8271. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  8272. // `index` is the index of the next character to be consumed.
  8273. // Decode a generalized variable-length integer into `delta`,
  8274. // which gets added to `i`. The overflow checking is easier
  8275. // if we increase `i` as we go, then subtract off its starting
  8276. // value at the end to obtain `delta`.
  8277. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  8278. if (index >= inputLength) {
  8279. error('invalid-input');
  8280. }
  8281. digit = basicToDigit(input.charCodeAt(index++));
  8282. if (digit >= base || digit > floor((maxInt - i) / w)) {
  8283. error('overflow');
  8284. }
  8285. i += digit * w;
  8286. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  8287. if (digit < t) {
  8288. break;
  8289. }
  8290. baseMinusT = base - t;
  8291. if (w > floor(maxInt / baseMinusT)) {
  8292. error('overflow');
  8293. }
  8294. w *= baseMinusT;
  8295. }
  8296. out = output.length + 1;
  8297. bias = adapt(i - oldi, out, oldi == 0);
  8298. // `i` was supposed to wrap around from `out` to `0`,
  8299. // incrementing `n` each time, so we'll fix that now:
  8300. if (floor(i / out) > maxInt - n) {
  8301. error('overflow');
  8302. }
  8303. n += floor(i / out);
  8304. i %= out;
  8305. // Insert `n` at position `i` of the output
  8306. output.splice(i++, 0, n);
  8307. }
  8308. return ucs2encode(output);
  8309. }
  8310. /**
  8311. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  8312. * Punycode string of ASCII-only symbols.
  8313. * @memberOf punycode
  8314. * @param {String} input The string of Unicode symbols.
  8315. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  8316. */
  8317. function encode(input) {
  8318. var n,
  8319. delta,
  8320. handledCPCount,
  8321. basicLength,
  8322. bias,
  8323. j,
  8324. m,
  8325. q,
  8326. k,
  8327. t,
  8328. currentValue,
  8329. output = [],
  8330. /** `inputLength` will hold the number of code points in `input`. */
  8331. inputLength,
  8332. /** Cached calculation results */
  8333. handledCPCountPlusOne,
  8334. baseMinusT,
  8335. qMinusT;
  8336. // Convert the input in UCS-2 to Unicode
  8337. input = ucs2decode(input);
  8338. // Cache the length
  8339. inputLength = input.length;
  8340. // Initialize the state
  8341. n = initialN;
  8342. delta = 0;
  8343. bias = initialBias;
  8344. // Handle the basic code points
  8345. for (j = 0; j < inputLength; ++j) {
  8346. currentValue = input[j];
  8347. if (currentValue < 0x80) {
  8348. output.push(stringFromCharCode(currentValue));
  8349. }
  8350. }
  8351. handledCPCount = basicLength = output.length;
  8352. // `handledCPCount` is the number of code points that have been handled;
  8353. // `basicLength` is the number of basic code points.
  8354. // Finish the basic string - if it is not empty - with a delimiter
  8355. if (basicLength) {
  8356. output.push(delimiter);
  8357. }
  8358. // Main encoding loop:
  8359. while (handledCPCount < inputLength) {
  8360. // All non-basic code points < n have been handled already. Find the next
  8361. // larger one:
  8362. for (m = maxInt, j = 0; j < inputLength; ++j) {
  8363. currentValue = input[j];
  8364. if (currentValue >= n && currentValue < m) {
  8365. m = currentValue;
  8366. }
  8367. }
  8368. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  8369. // but guard against overflow
  8370. handledCPCountPlusOne = handledCPCount + 1;
  8371. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  8372. error('overflow');
  8373. }
  8374. delta += (m - n) * handledCPCountPlusOne;
  8375. n = m;
  8376. for (j = 0; j < inputLength; ++j) {
  8377. currentValue = input[j];
  8378. if (currentValue < n && ++delta > maxInt) {
  8379. error('overflow');
  8380. }
  8381. if (currentValue == n) {
  8382. // Represent delta as a generalized variable-length integer
  8383. for (q = delta, k = base; /* no condition */; k += base) {
  8384. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  8385. if (q < t) {
  8386. break;
  8387. }
  8388. qMinusT = q - t;
  8389. baseMinusT = base - t;
  8390. output.push(
  8391. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  8392. );
  8393. q = floor(qMinusT / baseMinusT);
  8394. }
  8395. output.push(stringFromCharCode(digitToBasic(q, 0)));
  8396. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  8397. delta = 0;
  8398. ++handledCPCount;
  8399. }
  8400. }
  8401. ++delta;
  8402. ++n;
  8403. }
  8404. return output.join('');
  8405. }
  8406. /**
  8407. * Converts a Punycode string representing a domain name or an email address
  8408. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  8409. * it doesn't matter if you call it on a string that has already been
  8410. * converted to Unicode.
  8411. * @memberOf punycode
  8412. * @param {String} input The Punycoded domain name or email address to
  8413. * convert to Unicode.
  8414. * @returns {String} The Unicode representation of the given Punycode
  8415. * string.
  8416. */
  8417. function toUnicode(input) {
  8418. return mapDomain(input, function(string) {
  8419. return regexPunycode.test(string)
  8420. ? decode(string.slice(4).toLowerCase())
  8421. : string;
  8422. });
  8423. }
  8424. /**
  8425. * Converts a Unicode string representing a domain name or an email address to
  8426. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  8427. * i.e. it doesn't matter if you call it with a domain that's already in
  8428. * ASCII.
  8429. * @memberOf punycode
  8430. * @param {String} input The domain name or email address to convert, as a
  8431. * Unicode string.
  8432. * @returns {String} The Punycode representation of the given domain name or
  8433. * email address.
  8434. */
  8435. function toASCII(input) {
  8436. return mapDomain(input, function(string) {
  8437. return regexNonASCII.test(string)
  8438. ? 'xn--' + encode(string)
  8439. : string;
  8440. });
  8441. }
  8442. /*--------------------------------------------------------------------------*/
  8443. /** Define the public API */
  8444. punycode = {
  8445. /**
  8446. * A string representing the current Punycode.js version number.
  8447. * @memberOf punycode
  8448. * @type String
  8449. */
  8450. 'version': '1.4.1',
  8451. /**
  8452. * An object of methods to convert from JavaScript's internal character
  8453. * representation (UCS-2) to Unicode code points, and back.
  8454. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8455. * @memberOf punycode
  8456. * @type Object
  8457. */
  8458. 'ucs2': {
  8459. 'decode': ucs2decode,
  8460. 'encode': ucs2encode
  8461. },
  8462. 'decode': decode,
  8463. 'encode': encode,
  8464. 'toASCII': toASCII,
  8465. 'toUnicode': toUnicode
  8466. };
  8467. /** Expose `punycode` */
  8468. // Some AMD build optimizers, like r.js, check for specific condition patterns
  8469. // like the following:
  8470. if (
  8471. typeof define == 'function' &&
  8472. typeof define.amd == 'object' &&
  8473. define.amd
  8474. ) {
  8475. define('punycode', function() {
  8476. return punycode;
  8477. });
  8478. } else if (freeExports && freeModule) {
  8479. if (module.exports == freeExports) {
  8480. // in Node.js, io.js, or RingoJS v0.8.0+
  8481. freeModule.exports = punycode;
  8482. } else {
  8483. // in Narwhal or RingoJS v0.7.0-
  8484. for (key in punycode) {
  8485. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  8486. }
  8487. }
  8488. } else {
  8489. // in Rhino or a web browser
  8490. root.punycode = punycode;
  8491. }
  8492. }(this));
  8493. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8494. },{}],94:[function(require,module,exports){
  8495. // Copyright Joyent, Inc. and other Node contributors.
  8496. //
  8497. // Permission is hereby granted, free of charge, to any person obtaining a
  8498. // copy of this software and associated documentation files (the
  8499. // "Software"), to deal in the Software without restriction, including
  8500. // without limitation the rights to use, copy, modify, merge, publish,
  8501. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8502. // persons to whom the Software is furnished to do so, subject to the
  8503. // following conditions:
  8504. //
  8505. // The above copyright notice and this permission notice shall be included
  8506. // in all copies or substantial portions of the Software.
  8507. //
  8508. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8509. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8510. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8511. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8512. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8513. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8514. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8515. 'use strict';
  8516. // If obj.hasOwnProperty has been overridden, then calling
  8517. // obj.hasOwnProperty(prop) will break.
  8518. // See: https://github.com/joyent/node/issues/1707
  8519. function hasOwnProperty(obj, prop) {
  8520. return Object.prototype.hasOwnProperty.call(obj, prop);
  8521. }
  8522. module.exports = function(qs, sep, eq, options) {
  8523. sep = sep || '&';
  8524. eq = eq || '=';
  8525. var obj = {};
  8526. if (typeof qs !== 'string' || qs.length === 0) {
  8527. return obj;
  8528. }
  8529. var regexp = /\+/g;
  8530. qs = qs.split(sep);
  8531. var maxKeys = 1000;
  8532. if (options && typeof options.maxKeys === 'number') {
  8533. maxKeys = options.maxKeys;
  8534. }
  8535. var len = qs.length;
  8536. // maxKeys <= 0 means that we should not limit keys count
  8537. if (maxKeys > 0 && len > maxKeys) {
  8538. len = maxKeys;
  8539. }
  8540. for (var i = 0; i < len; ++i) {
  8541. var x = qs[i].replace(regexp, '%20'),
  8542. idx = x.indexOf(eq),
  8543. kstr, vstr, k, v;
  8544. if (idx >= 0) {
  8545. kstr = x.substr(0, idx);
  8546. vstr = x.substr(idx + 1);
  8547. } else {
  8548. kstr = x;
  8549. vstr = '';
  8550. }
  8551. k = decodeURIComponent(kstr);
  8552. v = decodeURIComponent(vstr);
  8553. if (!hasOwnProperty(obj, k)) {
  8554. obj[k] = v;
  8555. } else if (isArray(obj[k])) {
  8556. obj[k].push(v);
  8557. } else {
  8558. obj[k] = [obj[k], v];
  8559. }
  8560. }
  8561. return obj;
  8562. };
  8563. var isArray = Array.isArray || function (xs) {
  8564. return Object.prototype.toString.call(xs) === '[object Array]';
  8565. };
  8566. },{}],95:[function(require,module,exports){
  8567. // Copyright Joyent, Inc. and other Node contributors.
  8568. //
  8569. // Permission is hereby granted, free of charge, to any person obtaining a
  8570. // copy of this software and associated documentation files (the
  8571. // "Software"), to deal in the Software without restriction, including
  8572. // without limitation the rights to use, copy, modify, merge, publish,
  8573. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8574. // persons to whom the Software is furnished to do so, subject to the
  8575. // following conditions:
  8576. //
  8577. // The above copyright notice and this permission notice shall be included
  8578. // in all copies or substantial portions of the Software.
  8579. //
  8580. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8581. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8582. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8583. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8584. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8585. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8586. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8587. 'use strict';
  8588. var stringifyPrimitive = function(v) {
  8589. switch (typeof v) {
  8590. case 'string':
  8591. return v;
  8592. case 'boolean':
  8593. return v ? 'true' : 'false';
  8594. case 'number':
  8595. return isFinite(v) ? v : '';
  8596. default:
  8597. return '';
  8598. }
  8599. };
  8600. module.exports = function(obj, sep, eq, name) {
  8601. sep = sep || '&';
  8602. eq = eq || '=';
  8603. if (obj === null) {
  8604. obj = undefined;
  8605. }
  8606. if (typeof obj === 'object') {
  8607. return map(objectKeys(obj), function(k) {
  8608. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  8609. if (isArray(obj[k])) {
  8610. return map(obj[k], function(v) {
  8611. return ks + encodeURIComponent(stringifyPrimitive(v));
  8612. }).join(sep);
  8613. } else {
  8614. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  8615. }
  8616. }).join(sep);
  8617. }
  8618. if (!name) return '';
  8619. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  8620. encodeURIComponent(stringifyPrimitive(obj));
  8621. };
  8622. var isArray = Array.isArray || function (xs) {
  8623. return Object.prototype.toString.call(xs) === '[object Array]';
  8624. };
  8625. function map (xs, f) {
  8626. if (xs.map) return xs.map(f);
  8627. var res = [];
  8628. for (var i = 0; i < xs.length; i++) {
  8629. res.push(f(xs[i], i));
  8630. }
  8631. return res;
  8632. }
  8633. var objectKeys = Object.keys || function (obj) {
  8634. var res = [];
  8635. for (var key in obj) {
  8636. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  8637. }
  8638. return res;
  8639. };
  8640. },{}],96:[function(require,module,exports){
  8641. 'use strict';
  8642. exports.decode = exports.parse = require('./decode');
  8643. exports.encode = exports.stringify = require('./encode');
  8644. },{"./decode":94,"./encode":95}],97:[function(require,module,exports){
  8645. module.exports = require('./lib/_stream_duplex.js');
  8646. },{"./lib/_stream_duplex.js":98}],98:[function(require,module,exports){
  8647. // Copyright Joyent, Inc. and other Node contributors.
  8648. //
  8649. // Permission is hereby granted, free of charge, to any person obtaining a
  8650. // copy of this software and associated documentation files (the
  8651. // "Software"), to deal in the Software without restriction, including
  8652. // without limitation the rights to use, copy, modify, merge, publish,
  8653. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8654. // persons to whom the Software is furnished to do so, subject to the
  8655. // following conditions:
  8656. //
  8657. // The above copyright notice and this permission notice shall be included
  8658. // in all copies or substantial portions of the Software.
  8659. //
  8660. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8661. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8662. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8663. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8664. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8665. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8666. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8667. // a duplex stream is just a stream that is both readable and writable.
  8668. // Since JS doesn't have multiple prototypal inheritance, this class
  8669. // prototypally inherits from Readable, and then parasitically from
  8670. // Writable.
  8671. 'use strict';
  8672. /*<replacement>*/
  8673. var pna = require('process-nextick-args');
  8674. /*</replacement>*/
  8675. /*<replacement>*/
  8676. var objectKeys = Object.keys || function (obj) {
  8677. var keys = [];
  8678. for (var key in obj) {
  8679. keys.push(key);
  8680. }return keys;
  8681. };
  8682. /*</replacement>*/
  8683. module.exports = Duplex;
  8684. /*<replacement>*/
  8685. var util = require('core-util-is');
  8686. util.inherits = require('inherits');
  8687. /*</replacement>*/
  8688. var Readable = require('./_stream_readable');
  8689. var Writable = require('./_stream_writable');
  8690. util.inherits(Duplex, Readable);
  8691. {
  8692. // avoid scope creep, the keys array can then be collected
  8693. var keys = objectKeys(Writable.prototype);
  8694. for (var v = 0; v < keys.length; v++) {
  8695. var method = keys[v];
  8696. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  8697. }
  8698. }
  8699. function Duplex(options) {
  8700. if (!(this instanceof Duplex)) return new Duplex(options);
  8701. Readable.call(this, options);
  8702. Writable.call(this, options);
  8703. if (options && options.readable === false) this.readable = false;
  8704. if (options && options.writable === false) this.writable = false;
  8705. this.allowHalfOpen = true;
  8706. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  8707. this.once('end', onend);
  8708. }
  8709. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  8710. // making it explicit this property is not enumerable
  8711. // because otherwise some prototype manipulation in
  8712. // userland will fail
  8713. enumerable: false,
  8714. get: function () {
  8715. return this._writableState.highWaterMark;
  8716. }
  8717. });
  8718. // the no-half-open enforcer
  8719. function onend() {
  8720. // if we allow half-open state, or if the writable side ended,
  8721. // then we're ok.
  8722. if (this.allowHalfOpen || this._writableState.ended) return;
  8723. // no more data can be written.
  8724. // But allow more writes to happen in this tick.
  8725. pna.nextTick(onEndNT, this);
  8726. }
  8727. function onEndNT(self) {
  8728. self.end();
  8729. }
  8730. Object.defineProperty(Duplex.prototype, 'destroyed', {
  8731. get: function () {
  8732. if (this._readableState === undefined || this._writableState === undefined) {
  8733. return false;
  8734. }
  8735. return this._readableState.destroyed && this._writableState.destroyed;
  8736. },
  8737. set: function (value) {
  8738. // we ignore the value if the stream
  8739. // has not been initialized yet
  8740. if (this._readableState === undefined || this._writableState === undefined) {
  8741. return;
  8742. }
  8743. // backward compatibility, the user is explicitly
  8744. // managing destroyed
  8745. this._readableState.destroyed = value;
  8746. this._writableState.destroyed = value;
  8747. }
  8748. });
  8749. Duplex.prototype._destroy = function (err, cb) {
  8750. this.push(null);
  8751. this.end();
  8752. pna.nextTick(cb, err);
  8753. };
  8754. },{"./_stream_readable":100,"./_stream_writable":102,"core-util-is":14,"inherits":80,"process-nextick-args":91}],99:[function(require,module,exports){
  8755. // Copyright Joyent, Inc. and other Node contributors.
  8756. //
  8757. // Permission is hereby granted, free of charge, to any person obtaining a
  8758. // copy of this software and associated documentation files (the
  8759. // "Software"), to deal in the Software without restriction, including
  8760. // without limitation the rights to use, copy, modify, merge, publish,
  8761. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8762. // persons to whom the Software is furnished to do so, subject to the
  8763. // following conditions:
  8764. //
  8765. // The above copyright notice and this permission notice shall be included
  8766. // in all copies or substantial portions of the Software.
  8767. //
  8768. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8769. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8770. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8771. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8772. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8773. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8774. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8775. // a passthrough stream.
  8776. // basically just the most minimal sort of Transform stream.
  8777. // Every written chunk gets output as-is.
  8778. 'use strict';
  8779. module.exports = PassThrough;
  8780. var Transform = require('./_stream_transform');
  8781. /*<replacement>*/
  8782. var util = require('core-util-is');
  8783. util.inherits = require('inherits');
  8784. /*</replacement>*/
  8785. util.inherits(PassThrough, Transform);
  8786. function PassThrough(options) {
  8787. if (!(this instanceof PassThrough)) return new PassThrough(options);
  8788. Transform.call(this, options);
  8789. }
  8790. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  8791. cb(null, chunk);
  8792. };
  8793. },{"./_stream_transform":101,"core-util-is":14,"inherits":80}],100:[function(require,module,exports){
  8794. (function (process,global){
  8795. // Copyright Joyent, Inc. and other Node contributors.
  8796. //
  8797. // Permission is hereby granted, free of charge, to any person obtaining a
  8798. // copy of this software and associated documentation files (the
  8799. // "Software"), to deal in the Software without restriction, including
  8800. // without limitation the rights to use, copy, modify, merge, publish,
  8801. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8802. // persons to whom the Software is furnished to do so, subject to the
  8803. // following conditions:
  8804. //
  8805. // The above copyright notice and this permission notice shall be included
  8806. // in all copies or substantial portions of the Software.
  8807. //
  8808. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8809. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8810. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8811. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8812. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8813. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8814. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8815. 'use strict';
  8816. /*<replacement>*/
  8817. var pna = require('process-nextick-args');
  8818. /*</replacement>*/
  8819. module.exports = Readable;
  8820. /*<replacement>*/
  8821. var isArray = require('isarray');
  8822. /*</replacement>*/
  8823. /*<replacement>*/
  8824. var Duplex;
  8825. /*</replacement>*/
  8826. Readable.ReadableState = ReadableState;
  8827. /*<replacement>*/
  8828. var EE = require('events').EventEmitter;
  8829. var EElistenerCount = function (emitter, type) {
  8830. return emitter.listeners(type).length;
  8831. };
  8832. /*</replacement>*/
  8833. /*<replacement>*/
  8834. var Stream = require('./internal/streams/stream');
  8835. /*</replacement>*/
  8836. /*<replacement>*/
  8837. var Buffer = require('safe-buffer').Buffer;
  8838. var OurUint8Array = global.Uint8Array || function () {};
  8839. function _uint8ArrayToBuffer(chunk) {
  8840. return Buffer.from(chunk);
  8841. }
  8842. function _isUint8Array(obj) {
  8843. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  8844. }
  8845. /*</replacement>*/
  8846. /*<replacement>*/
  8847. var util = require('core-util-is');
  8848. util.inherits = require('inherits');
  8849. /*</replacement>*/
  8850. /*<replacement>*/
  8851. var debugUtil = require('util');
  8852. var debug = void 0;
  8853. if (debugUtil && debugUtil.debuglog) {
  8854. debug = debugUtil.debuglog('stream');
  8855. } else {
  8856. debug = function () {};
  8857. }
  8858. /*</replacement>*/
  8859. var BufferList = require('./internal/streams/BufferList');
  8860. var destroyImpl = require('./internal/streams/destroy');
  8861. var StringDecoder;
  8862. util.inherits(Readable, Stream);
  8863. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  8864. function prependListener(emitter, event, fn) {
  8865. // Sadly this is not cacheable as some libraries bundle their own
  8866. // event emitter implementation with them.
  8867. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  8868. // This is a hack to make sure that our error handler is attached before any
  8869. // userland ones. NEVER DO THIS. This is here only because this code needs
  8870. // to continue to work with older versions of Node.js that do not include
  8871. // the prependListener() method. The goal is to eventually remove this hack.
  8872. 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]];
  8873. }
  8874. function ReadableState(options, stream) {
  8875. Duplex = Duplex || require('./_stream_duplex');
  8876. options = options || {};
  8877. // Duplex streams are both readable and writable, but share
  8878. // the same options object.
  8879. // However, some cases require setting options to different
  8880. // values for the readable and the writable sides of the duplex stream.
  8881. // These options can be provided separately as readableXXX and writableXXX.
  8882. var isDuplex = stream instanceof Duplex;
  8883. // object stream flag. Used to make read(n) ignore n and to
  8884. // make all the buffer merging and length checks go away
  8885. this.objectMode = !!options.objectMode;
  8886. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  8887. // the point at which it stops calling _read() to fill the buffer
  8888. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  8889. var hwm = options.highWaterMark;
  8890. var readableHwm = options.readableHighWaterMark;
  8891. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  8892. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  8893. // cast to ints.
  8894. this.highWaterMark = Math.floor(this.highWaterMark);
  8895. // A linked list is used to store data chunks instead of an array because the
  8896. // linked list can remove elements from the beginning faster than
  8897. // array.shift()
  8898. this.buffer = new BufferList();
  8899. this.length = 0;
  8900. this.pipes = null;
  8901. this.pipesCount = 0;
  8902. this.flowing = null;
  8903. this.ended = false;
  8904. this.endEmitted = false;
  8905. this.reading = false;
  8906. // a flag to be able to tell if the event 'readable'/'data' is emitted
  8907. // immediately, or on a later tick. We set this to true at first, because
  8908. // any actions that shouldn't happen until "later" should generally also
  8909. // not happen before the first read call.
  8910. this.sync = true;
  8911. // whenever we return null, then we set a flag to say
  8912. // that we're awaiting a 'readable' event emission.
  8913. this.needReadable = false;
  8914. this.emittedReadable = false;
  8915. this.readableListening = false;
  8916. this.resumeScheduled = false;
  8917. // has it been destroyed
  8918. this.destroyed = false;
  8919. // Crypto is kind of old and crusty. Historically, its default string
  8920. // encoding is 'binary' so we have to make this configurable.
  8921. // Everything else in the universe uses 'utf8', though.
  8922. this.defaultEncoding = options.defaultEncoding || 'utf8';
  8923. // the number of writers that are awaiting a drain event in .pipe()s
  8924. this.awaitDrain = 0;
  8925. // if true, a maybeReadMore has been scheduled
  8926. this.readingMore = false;
  8927. this.decoder = null;
  8928. this.encoding = null;
  8929. if (options.encoding) {
  8930. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  8931. this.decoder = new StringDecoder(options.encoding);
  8932. this.encoding = options.encoding;
  8933. }
  8934. }
  8935. function Readable(options) {
  8936. Duplex = Duplex || require('./_stream_duplex');
  8937. if (!(this instanceof Readable)) return new Readable(options);
  8938. this._readableState = new ReadableState(options, this);
  8939. // legacy
  8940. this.readable = true;
  8941. if (options) {
  8942. if (typeof options.read === 'function') this._read = options.read;
  8943. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  8944. }
  8945. Stream.call(this);
  8946. }
  8947. Object.defineProperty(Readable.prototype, 'destroyed', {
  8948. get: function () {
  8949. if (this._readableState === undefined) {
  8950. return false;
  8951. }
  8952. return this._readableState.destroyed;
  8953. },
  8954. set: function (value) {
  8955. // we ignore the value if the stream
  8956. // has not been initialized yet
  8957. if (!this._readableState) {
  8958. return;
  8959. }
  8960. // backward compatibility, the user is explicitly
  8961. // managing destroyed
  8962. this._readableState.destroyed = value;
  8963. }
  8964. });
  8965. Readable.prototype.destroy = destroyImpl.destroy;
  8966. Readable.prototype._undestroy = destroyImpl.undestroy;
  8967. Readable.prototype._destroy = function (err, cb) {
  8968. this.push(null);
  8969. cb(err);
  8970. };
  8971. // Manually shove something into the read() buffer.
  8972. // This returns true if the highWaterMark has not been hit yet,
  8973. // similar to how Writable.write() returns true if you should
  8974. // write() some more.
  8975. Readable.prototype.push = function (chunk, encoding) {
  8976. var state = this._readableState;
  8977. var skipChunkCheck;
  8978. if (!state.objectMode) {
  8979. if (typeof chunk === 'string') {
  8980. encoding = encoding || state.defaultEncoding;
  8981. if (encoding !== state.encoding) {
  8982. chunk = Buffer.from(chunk, encoding);
  8983. encoding = '';
  8984. }
  8985. skipChunkCheck = true;
  8986. }
  8987. } else {
  8988. skipChunkCheck = true;
  8989. }
  8990. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  8991. };
  8992. // Unshift should *always* be something directly out of read()
  8993. Readable.prototype.unshift = function (chunk) {
  8994. return readableAddChunk(this, chunk, null, true, false);
  8995. };
  8996. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  8997. var state = stream._readableState;
  8998. if (chunk === null) {
  8999. state.reading = false;
  9000. onEofChunk(stream, state);
  9001. } else {
  9002. var er;
  9003. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  9004. if (er) {
  9005. stream.emit('error', er);
  9006. } else if (state.objectMode || chunk && chunk.length > 0) {
  9007. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  9008. chunk = _uint8ArrayToBuffer(chunk);
  9009. }
  9010. if (addToFront) {
  9011. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  9012. } else if (state.ended) {
  9013. stream.emit('error', new Error('stream.push() after EOF'));
  9014. } else {
  9015. state.reading = false;
  9016. if (state.decoder && !encoding) {
  9017. chunk = state.decoder.write(chunk);
  9018. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  9019. } else {
  9020. addChunk(stream, state, chunk, false);
  9021. }
  9022. }
  9023. } else if (!addToFront) {
  9024. state.reading = false;
  9025. }
  9026. }
  9027. return needMoreData(state);
  9028. }
  9029. function addChunk(stream, state, chunk, addToFront) {
  9030. if (state.flowing && state.length === 0 && !state.sync) {
  9031. stream.emit('data', chunk);
  9032. stream.read(0);
  9033. } else {
  9034. // update the buffer info.
  9035. state.length += state.objectMode ? 1 : chunk.length;
  9036. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  9037. if (state.needReadable) emitReadable(stream);
  9038. }
  9039. maybeReadMore(stream, state);
  9040. }
  9041. function chunkInvalid(state, chunk) {
  9042. var er;
  9043. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  9044. er = new TypeError('Invalid non-string/buffer chunk');
  9045. }
  9046. return er;
  9047. }
  9048. // if it's past the high water mark, we can push in some more.
  9049. // Also, if we have no data yet, we can stand some
  9050. // more bytes. This is to work around cases where hwm=0,
  9051. // such as the repl. Also, if the push() triggered a
  9052. // readable event, and the user called read(largeNumber) such that
  9053. // needReadable was set, then we ought to push more, so that another
  9054. // 'readable' event will be triggered.
  9055. function needMoreData(state) {
  9056. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  9057. }
  9058. Readable.prototype.isPaused = function () {
  9059. return this._readableState.flowing === false;
  9060. };
  9061. // backwards compatibility.
  9062. Readable.prototype.setEncoding = function (enc) {
  9063. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9064. this._readableState.decoder = new StringDecoder(enc);
  9065. this._readableState.encoding = enc;
  9066. return this;
  9067. };
  9068. // Don't raise the hwm > 8MB
  9069. var MAX_HWM = 0x800000;
  9070. function computeNewHighWaterMark(n) {
  9071. if (n >= MAX_HWM) {
  9072. n = MAX_HWM;
  9073. } else {
  9074. // Get the next highest power of 2 to prevent increasing hwm excessively in
  9075. // tiny amounts
  9076. n--;
  9077. n |= n >>> 1;
  9078. n |= n >>> 2;
  9079. n |= n >>> 4;
  9080. n |= n >>> 8;
  9081. n |= n >>> 16;
  9082. n++;
  9083. }
  9084. return n;
  9085. }
  9086. // This function is designed to be inlinable, so please take care when making
  9087. // changes to the function body.
  9088. function howMuchToRead(n, state) {
  9089. if (n <= 0 || state.length === 0 && state.ended) return 0;
  9090. if (state.objectMode) return 1;
  9091. if (n !== n) {
  9092. // Only flow one buffer at a time
  9093. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  9094. }
  9095. // If we're asking for more than the current hwm, then raise the hwm.
  9096. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  9097. if (n <= state.length) return n;
  9098. // Don't have enough
  9099. if (!state.ended) {
  9100. state.needReadable = true;
  9101. return 0;
  9102. }
  9103. return state.length;
  9104. }
  9105. // you can override either this method, or the async _read(n) below.
  9106. Readable.prototype.read = function (n) {
  9107. debug('read', n);
  9108. n = parseInt(n, 10);
  9109. var state = this._readableState;
  9110. var nOrig = n;
  9111. if (n !== 0) state.emittedReadable = false;
  9112. // if we're doing read(0) to trigger a readable event, but we
  9113. // already have a bunch of data in the buffer, then just trigger
  9114. // the 'readable' event and move on.
  9115. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  9116. debug('read: emitReadable', state.length, state.ended);
  9117. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  9118. return null;
  9119. }
  9120. n = howMuchToRead(n, state);
  9121. // if we've ended, and we're now clear, then finish it up.
  9122. if (n === 0 && state.ended) {
  9123. if (state.length === 0) endReadable(this);
  9124. return null;
  9125. }
  9126. // All the actual chunk generation logic needs to be
  9127. // *below* the call to _read. The reason is that in certain
  9128. // synthetic stream cases, such as passthrough streams, _read
  9129. // may be a completely synchronous operation which may change
  9130. // the state of the read buffer, providing enough data when
  9131. // before there was *not* enough.
  9132. //
  9133. // So, the steps are:
  9134. // 1. Figure out what the state of things will be after we do
  9135. // a read from the buffer.
  9136. //
  9137. // 2. If that resulting state will trigger a _read, then call _read.
  9138. // Note that this may be asynchronous, or synchronous. Yes, it is
  9139. // deeply ugly to write APIs this way, but that still doesn't mean
  9140. // that the Readable class should behave improperly, as streams are
  9141. // designed to be sync/async agnostic.
  9142. // Take note if the _read call is sync or async (ie, if the read call
  9143. // has returned yet), so that we know whether or not it's safe to emit
  9144. // 'readable' etc.
  9145. //
  9146. // 3. Actually pull the requested chunks out of the buffer and return.
  9147. // if we need a readable event, then we need to do some reading.
  9148. var doRead = state.needReadable;
  9149. debug('need readable', doRead);
  9150. // if we currently have less than the highWaterMark, then also read some
  9151. if (state.length === 0 || state.length - n < state.highWaterMark) {
  9152. doRead = true;
  9153. debug('length less than watermark', doRead);
  9154. }
  9155. // however, if we've ended, then there's no point, and if we're already
  9156. // reading, then it's unnecessary.
  9157. if (state.ended || state.reading) {
  9158. doRead = false;
  9159. debug('reading or ended', doRead);
  9160. } else if (doRead) {
  9161. debug('do read');
  9162. state.reading = true;
  9163. state.sync = true;
  9164. // if the length is currently zero, then we *need* a readable event.
  9165. if (state.length === 0) state.needReadable = true;
  9166. // call internal read method
  9167. this._read(state.highWaterMark);
  9168. state.sync = false;
  9169. // If _read pushed data synchronously, then `reading` will be false,
  9170. // and we need to re-evaluate how much data we can return to the user.
  9171. if (!state.reading) n = howMuchToRead(nOrig, state);
  9172. }
  9173. var ret;
  9174. if (n > 0) ret = fromList(n, state);else ret = null;
  9175. if (ret === null) {
  9176. state.needReadable = true;
  9177. n = 0;
  9178. } else {
  9179. state.length -= n;
  9180. }
  9181. if (state.length === 0) {
  9182. // If we have nothing in the buffer, then we want to know
  9183. // as soon as we *do* get something into the buffer.
  9184. if (!state.ended) state.needReadable = true;
  9185. // If we tried to read() past the EOF, then emit end on the next tick.
  9186. if (nOrig !== n && state.ended) endReadable(this);
  9187. }
  9188. if (ret !== null) this.emit('data', ret);
  9189. return ret;
  9190. };
  9191. function onEofChunk(stream, state) {
  9192. if (state.ended) return;
  9193. if (state.decoder) {
  9194. var chunk = state.decoder.end();
  9195. if (chunk && chunk.length) {
  9196. state.buffer.push(chunk);
  9197. state.length += state.objectMode ? 1 : chunk.length;
  9198. }
  9199. }
  9200. state.ended = true;
  9201. // emit 'readable' now to make sure it gets picked up.
  9202. emitReadable(stream);
  9203. }
  9204. // Don't emit readable right away in sync mode, because this can trigger
  9205. // another read() call => stack overflow. This way, it might trigger
  9206. // a nextTick recursion warning, but that's not so bad.
  9207. function emitReadable(stream) {
  9208. var state = stream._readableState;
  9209. state.needReadable = false;
  9210. if (!state.emittedReadable) {
  9211. debug('emitReadable', state.flowing);
  9212. state.emittedReadable = true;
  9213. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  9214. }
  9215. }
  9216. function emitReadable_(stream) {
  9217. debug('emit readable');
  9218. stream.emit('readable');
  9219. flow(stream);
  9220. }
  9221. // at this point, the user has presumably seen the 'readable' event,
  9222. // and called read() to consume some data. that may have triggered
  9223. // in turn another _read(n) call, in which case reading = true if
  9224. // it's in progress.
  9225. // However, if we're not ended, or reading, and the length < hwm,
  9226. // then go ahead and try to read some more preemptively.
  9227. function maybeReadMore(stream, state) {
  9228. if (!state.readingMore) {
  9229. state.readingMore = true;
  9230. pna.nextTick(maybeReadMore_, stream, state);
  9231. }
  9232. }
  9233. function maybeReadMore_(stream, state) {
  9234. var len = state.length;
  9235. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  9236. debug('maybeReadMore read 0');
  9237. stream.read(0);
  9238. if (len === state.length)
  9239. // didn't get any data, stop spinning.
  9240. break;else len = state.length;
  9241. }
  9242. state.readingMore = false;
  9243. }
  9244. // abstract method. to be overridden in specific implementation classes.
  9245. // call cb(er, data) where data is <= n in length.
  9246. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  9247. // arbitrary, and perhaps not very meaningful.
  9248. Readable.prototype._read = function (n) {
  9249. this.emit('error', new Error('_read() is not implemented'));
  9250. };
  9251. Readable.prototype.pipe = function (dest, pipeOpts) {
  9252. var src = this;
  9253. var state = this._readableState;
  9254. switch (state.pipesCount) {
  9255. case 0:
  9256. state.pipes = dest;
  9257. break;
  9258. case 1:
  9259. state.pipes = [state.pipes, dest];
  9260. break;
  9261. default:
  9262. state.pipes.push(dest);
  9263. break;
  9264. }
  9265. state.pipesCount += 1;
  9266. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  9267. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  9268. var endFn = doEnd ? onend : unpipe;
  9269. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  9270. dest.on('unpipe', onunpipe);
  9271. function onunpipe(readable, unpipeInfo) {
  9272. debug('onunpipe');
  9273. if (readable === src) {
  9274. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  9275. unpipeInfo.hasUnpiped = true;
  9276. cleanup();
  9277. }
  9278. }
  9279. }
  9280. function onend() {
  9281. debug('onend');
  9282. dest.end();
  9283. }
  9284. // when the dest drains, it reduces the awaitDrain counter
  9285. // on the source. This would be more elegant with a .once()
  9286. // handler in flow(), but adding and removing repeatedly is
  9287. // too slow.
  9288. var ondrain = pipeOnDrain(src);
  9289. dest.on('drain', ondrain);
  9290. var cleanedUp = false;
  9291. function cleanup() {
  9292. debug('cleanup');
  9293. // cleanup event handlers once the pipe is broken
  9294. dest.removeListener('close', onclose);
  9295. dest.removeListener('finish', onfinish);
  9296. dest.removeListener('drain', ondrain);
  9297. dest.removeListener('error', onerror);
  9298. dest.removeListener('unpipe', onunpipe);
  9299. src.removeListener('end', onend);
  9300. src.removeListener('end', unpipe);
  9301. src.removeListener('data', ondata);
  9302. cleanedUp = true;
  9303. // if the reader is waiting for a drain event from this
  9304. // specific writer, then it would cause it to never start
  9305. // flowing again.
  9306. // So, if this is awaiting a drain, then we just call it now.
  9307. // If we don't know, then assume that we are waiting for one.
  9308. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  9309. }
  9310. // If the user pushes more data while we're writing to dest then we'll end up
  9311. // in ondata again. However, we only want to increase awaitDrain once because
  9312. // dest will only emit one 'drain' event for the multiple writes.
  9313. // => Introduce a guard on increasing awaitDrain.
  9314. var increasedAwaitDrain = false;
  9315. src.on('data', ondata);
  9316. function ondata(chunk) {
  9317. debug('ondata');
  9318. increasedAwaitDrain = false;
  9319. var ret = dest.write(chunk);
  9320. if (false === ret && !increasedAwaitDrain) {
  9321. // If the user unpiped during `dest.write()`, it is possible
  9322. // to get stuck in a permanently paused state if that write
  9323. // also returned false.
  9324. // => Check whether `dest` is still a piping destination.
  9325. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  9326. debug('false write response, pause', src._readableState.awaitDrain);
  9327. src._readableState.awaitDrain++;
  9328. increasedAwaitDrain = true;
  9329. }
  9330. src.pause();
  9331. }
  9332. }
  9333. // if the dest has an error, then stop piping into it.
  9334. // however, don't suppress the throwing behavior for this.
  9335. function onerror(er) {
  9336. debug('onerror', er);
  9337. unpipe();
  9338. dest.removeListener('error', onerror);
  9339. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  9340. }
  9341. // Make sure our error handler is attached before userland ones.
  9342. prependListener(dest, 'error', onerror);
  9343. // Both close and finish should trigger unpipe, but only once.
  9344. function onclose() {
  9345. dest.removeListener('finish', onfinish);
  9346. unpipe();
  9347. }
  9348. dest.once('close', onclose);
  9349. function onfinish() {
  9350. debug('onfinish');
  9351. dest.removeListener('close', onclose);
  9352. unpipe();
  9353. }
  9354. dest.once('finish', onfinish);
  9355. function unpipe() {
  9356. debug('unpipe');
  9357. src.unpipe(dest);
  9358. }
  9359. // tell the dest that it's being piped to
  9360. dest.emit('pipe', src);
  9361. // start the flow if it hasn't been started already.
  9362. if (!state.flowing) {
  9363. debug('pipe resume');
  9364. src.resume();
  9365. }
  9366. return dest;
  9367. };
  9368. function pipeOnDrain(src) {
  9369. return function () {
  9370. var state = src._readableState;
  9371. debug('pipeOnDrain', state.awaitDrain);
  9372. if (state.awaitDrain) state.awaitDrain--;
  9373. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  9374. state.flowing = true;
  9375. flow(src);
  9376. }
  9377. };
  9378. }
  9379. Readable.prototype.unpipe = function (dest) {
  9380. var state = this._readableState;
  9381. var unpipeInfo = { hasUnpiped: false };
  9382. // if we're not piping anywhere, then do nothing.
  9383. if (state.pipesCount === 0) return this;
  9384. // just one destination. most common case.
  9385. if (state.pipesCount === 1) {
  9386. // passed in one, but it's not the right one.
  9387. if (dest && dest !== state.pipes) return this;
  9388. if (!dest) dest = state.pipes;
  9389. // got a match.
  9390. state.pipes = null;
  9391. state.pipesCount = 0;
  9392. state.flowing = false;
  9393. if (dest) dest.emit('unpipe', this, unpipeInfo);
  9394. return this;
  9395. }
  9396. // slow case. multiple pipe destinations.
  9397. if (!dest) {
  9398. // remove all.
  9399. var dests = state.pipes;
  9400. var len = state.pipesCount;
  9401. state.pipes = null;
  9402. state.pipesCount = 0;
  9403. state.flowing = false;
  9404. for (var i = 0; i < len; i++) {
  9405. dests[i].emit('unpipe', this, unpipeInfo);
  9406. }return this;
  9407. }
  9408. // try to find the right one.
  9409. var index = indexOf(state.pipes, dest);
  9410. if (index === -1) return this;
  9411. state.pipes.splice(index, 1);
  9412. state.pipesCount -= 1;
  9413. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  9414. dest.emit('unpipe', this, unpipeInfo);
  9415. return this;
  9416. };
  9417. // set up data events if they are asked for
  9418. // Ensure readable listeners eventually get something
  9419. Readable.prototype.on = function (ev, fn) {
  9420. var res = Stream.prototype.on.call(this, ev, fn);
  9421. if (ev === 'data') {
  9422. // Start flowing on next tick if stream isn't explicitly paused
  9423. if (this._readableState.flowing !== false) this.resume();
  9424. } else if (ev === 'readable') {
  9425. var state = this._readableState;
  9426. if (!state.endEmitted && !state.readableListening) {
  9427. state.readableListening = state.needReadable = true;
  9428. state.emittedReadable = false;
  9429. if (!state.reading) {
  9430. pna.nextTick(nReadingNextTick, this);
  9431. } else if (state.length) {
  9432. emitReadable(this);
  9433. }
  9434. }
  9435. }
  9436. return res;
  9437. };
  9438. Readable.prototype.addListener = Readable.prototype.on;
  9439. function nReadingNextTick(self) {
  9440. debug('readable nexttick read 0');
  9441. self.read(0);
  9442. }
  9443. // pause() and resume() are remnants of the legacy readable stream API
  9444. // If the user uses them, then switch into old mode.
  9445. Readable.prototype.resume = function () {
  9446. var state = this._readableState;
  9447. if (!state.flowing) {
  9448. debug('resume');
  9449. state.flowing = true;
  9450. resume(this, state);
  9451. }
  9452. return this;
  9453. };
  9454. function resume(stream, state) {
  9455. if (!state.resumeScheduled) {
  9456. state.resumeScheduled = true;
  9457. pna.nextTick(resume_, stream, state);
  9458. }
  9459. }
  9460. function resume_(stream, state) {
  9461. if (!state.reading) {
  9462. debug('resume read 0');
  9463. stream.read(0);
  9464. }
  9465. state.resumeScheduled = false;
  9466. state.awaitDrain = 0;
  9467. stream.emit('resume');
  9468. flow(stream);
  9469. if (state.flowing && !state.reading) stream.read(0);
  9470. }
  9471. Readable.prototype.pause = function () {
  9472. debug('call pause flowing=%j', this._readableState.flowing);
  9473. if (false !== this._readableState.flowing) {
  9474. debug('pause');
  9475. this._readableState.flowing = false;
  9476. this.emit('pause');
  9477. }
  9478. return this;
  9479. };
  9480. function flow(stream) {
  9481. var state = stream._readableState;
  9482. debug('flow', state.flowing);
  9483. while (state.flowing && stream.read() !== null) {}
  9484. }
  9485. // wrap an old-style stream as the async data source.
  9486. // This is *not* part of the readable stream interface.
  9487. // It is an ugly unfortunate mess of history.
  9488. Readable.prototype.wrap = function (stream) {
  9489. var _this = this;
  9490. var state = this._readableState;
  9491. var paused = false;
  9492. stream.on('end', function () {
  9493. debug('wrapped end');
  9494. if (state.decoder && !state.ended) {
  9495. var chunk = state.decoder.end();
  9496. if (chunk && chunk.length) _this.push(chunk);
  9497. }
  9498. _this.push(null);
  9499. });
  9500. stream.on('data', function (chunk) {
  9501. debug('wrapped data');
  9502. if (state.decoder) chunk = state.decoder.write(chunk);
  9503. // don't skip over falsy values in objectMode
  9504. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  9505. var ret = _this.push(chunk);
  9506. if (!ret) {
  9507. paused = true;
  9508. stream.pause();
  9509. }
  9510. });
  9511. // proxy all the other methods.
  9512. // important when wrapping filters and duplexes.
  9513. for (var i in stream) {
  9514. if (this[i] === undefined && typeof stream[i] === 'function') {
  9515. this[i] = function (method) {
  9516. return function () {
  9517. return stream[method].apply(stream, arguments);
  9518. };
  9519. }(i);
  9520. }
  9521. }
  9522. // proxy certain important events.
  9523. for (var n = 0; n < kProxyEvents.length; n++) {
  9524. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  9525. }
  9526. // when we try to consume some more bytes, simply unpause the
  9527. // underlying stream.
  9528. this._read = function (n) {
  9529. debug('wrapped _read', n);
  9530. if (paused) {
  9531. paused = false;
  9532. stream.resume();
  9533. }
  9534. };
  9535. return this;
  9536. };
  9537. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  9538. // making it explicit this property is not enumerable
  9539. // because otherwise some prototype manipulation in
  9540. // userland will fail
  9541. enumerable: false,
  9542. get: function () {
  9543. return this._readableState.highWaterMark;
  9544. }
  9545. });
  9546. // exposed for testing purposes only.
  9547. Readable._fromList = fromList;
  9548. // Pluck off n bytes from an array of buffers.
  9549. // Length is the combined lengths of all the buffers in the list.
  9550. // This function is designed to be inlinable, so please take care when making
  9551. // changes to the function body.
  9552. function fromList(n, state) {
  9553. // nothing buffered
  9554. if (state.length === 0) return null;
  9555. var ret;
  9556. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  9557. // read it all, truncate the list
  9558. 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);
  9559. state.buffer.clear();
  9560. } else {
  9561. // read part of list
  9562. ret = fromListPartial(n, state.buffer, state.decoder);
  9563. }
  9564. return ret;
  9565. }
  9566. // Extracts only enough buffered data to satisfy the amount requested.
  9567. // This function is designed to be inlinable, so please take care when making
  9568. // changes to the function body.
  9569. function fromListPartial(n, list, hasStrings) {
  9570. var ret;
  9571. if (n < list.head.data.length) {
  9572. // slice is the same for buffers and strings
  9573. ret = list.head.data.slice(0, n);
  9574. list.head.data = list.head.data.slice(n);
  9575. } else if (n === list.head.data.length) {
  9576. // first chunk is a perfect match
  9577. ret = list.shift();
  9578. } else {
  9579. // result spans more than one buffer
  9580. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  9581. }
  9582. return ret;
  9583. }
  9584. // Copies a specified amount of characters from the list of buffered data
  9585. // chunks.
  9586. // This function is designed to be inlinable, so please take care when making
  9587. // changes to the function body.
  9588. function copyFromBufferString(n, list) {
  9589. var p = list.head;
  9590. var c = 1;
  9591. var ret = p.data;
  9592. n -= ret.length;
  9593. while (p = p.next) {
  9594. var str = p.data;
  9595. var nb = n > str.length ? str.length : n;
  9596. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  9597. n -= nb;
  9598. if (n === 0) {
  9599. if (nb === str.length) {
  9600. ++c;
  9601. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9602. } else {
  9603. list.head = p;
  9604. p.data = str.slice(nb);
  9605. }
  9606. break;
  9607. }
  9608. ++c;
  9609. }
  9610. list.length -= c;
  9611. return ret;
  9612. }
  9613. // Copies a specified amount of bytes from the list of buffered data chunks.
  9614. // This function is designed to be inlinable, so please take care when making
  9615. // changes to the function body.
  9616. function copyFromBuffer(n, list) {
  9617. var ret = Buffer.allocUnsafe(n);
  9618. var p = list.head;
  9619. var c = 1;
  9620. p.data.copy(ret);
  9621. n -= p.data.length;
  9622. while (p = p.next) {
  9623. var buf = p.data;
  9624. var nb = n > buf.length ? buf.length : n;
  9625. buf.copy(ret, ret.length - n, 0, nb);
  9626. n -= nb;
  9627. if (n === 0) {
  9628. if (nb === buf.length) {
  9629. ++c;
  9630. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9631. } else {
  9632. list.head = p;
  9633. p.data = buf.slice(nb);
  9634. }
  9635. break;
  9636. }
  9637. ++c;
  9638. }
  9639. list.length -= c;
  9640. return ret;
  9641. }
  9642. function endReadable(stream) {
  9643. var state = stream._readableState;
  9644. // If we get here before consuming all the bytes, then that is a
  9645. // bug in node. Should never happen.
  9646. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  9647. if (!state.endEmitted) {
  9648. state.ended = true;
  9649. pna.nextTick(endReadableNT, state, stream);
  9650. }
  9651. }
  9652. function endReadableNT(state, stream) {
  9653. // Check that we didn't get one last unshift.
  9654. if (!state.endEmitted && state.length === 0) {
  9655. state.endEmitted = true;
  9656. stream.readable = false;
  9657. stream.emit('end');
  9658. }
  9659. }
  9660. function indexOf(xs, x) {
  9661. for (var i = 0, l = xs.length; i < l; i++) {
  9662. if (xs[i] === x) return i;
  9663. }
  9664. return -1;
  9665. }
  9666. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9667. },{"./_stream_duplex":98,"./internal/streams/BufferList":103,"./internal/streams/destroy":104,"./internal/streams/stream":105,"_process":92,"core-util-is":14,"events":13,"inherits":80,"isarray":106,"process-nextick-args":91,"safe-buffer":110,"string_decoder/":107,"util":11}],101:[function(require,module,exports){
  9668. // Copyright Joyent, Inc. and other Node contributors.
  9669. //
  9670. // Permission is hereby granted, free of charge, to any person obtaining a
  9671. // copy of this software and associated documentation files (the
  9672. // "Software"), to deal in the Software without restriction, including
  9673. // without limitation the rights to use, copy, modify, merge, publish,
  9674. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9675. // persons to whom the Software is furnished to do so, subject to the
  9676. // following conditions:
  9677. //
  9678. // The above copyright notice and this permission notice shall be included
  9679. // in all copies or substantial portions of the Software.
  9680. //
  9681. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9682. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9683. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9684. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9685. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9686. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9687. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9688. // a transform stream is a readable/writable stream where you do
  9689. // something with the data. Sometimes it's called a "filter",
  9690. // but that's not a great name for it, since that implies a thing where
  9691. // some bits pass through, and others are simply ignored. (That would
  9692. // be a valid example of a transform, of course.)
  9693. //
  9694. // While the output is causally related to the input, it's not a
  9695. // necessarily symmetric or synchronous transformation. For example,
  9696. // a zlib stream might take multiple plain-text writes(), and then
  9697. // emit a single compressed chunk some time in the future.
  9698. //
  9699. // Here's how this works:
  9700. //
  9701. // The Transform stream has all the aspects of the readable and writable
  9702. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  9703. // internally, and returns false if there's a lot of pending writes
  9704. // buffered up. When you call read(), that calls _read(n) until
  9705. // there's enough pending readable data buffered up.
  9706. //
  9707. // In a transform stream, the written data is placed in a buffer. When
  9708. // _read(n) is called, it transforms the queued up data, calling the
  9709. // buffered _write cb's as it consumes chunks. If consuming a single
  9710. // written chunk would result in multiple output chunks, then the first
  9711. // outputted bit calls the readcb, and subsequent chunks just go into
  9712. // the read buffer, and will cause it to emit 'readable' if necessary.
  9713. //
  9714. // This way, back-pressure is actually determined by the reading side,
  9715. // since _read has to be called to start processing a new chunk. However,
  9716. // a pathological inflate type of transform can cause excessive buffering
  9717. // here. For example, imagine a stream where every byte of input is
  9718. // interpreted as an integer from 0-255, and then results in that many
  9719. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  9720. // 1kb of data being output. In this case, you could write a very small
  9721. // amount of input, and end up with a very large amount of output. In
  9722. // such a pathological inflating mechanism, there'd be no way to tell
  9723. // the system to stop doing the transform. A single 4MB write could
  9724. // cause the system to run out of memory.
  9725. //
  9726. // However, even in such a pathological case, only a single written chunk
  9727. // would be consumed, and then the rest would wait (un-transformed) until
  9728. // the results of the previous transformed chunk were consumed.
  9729. 'use strict';
  9730. module.exports = Transform;
  9731. var Duplex = require('./_stream_duplex');
  9732. /*<replacement>*/
  9733. var util = require('core-util-is');
  9734. util.inherits = require('inherits');
  9735. /*</replacement>*/
  9736. util.inherits(Transform, Duplex);
  9737. function afterTransform(er, data) {
  9738. var ts = this._transformState;
  9739. ts.transforming = false;
  9740. var cb = ts.writecb;
  9741. if (!cb) {
  9742. return this.emit('error', new Error('write callback called multiple times'));
  9743. }
  9744. ts.writechunk = null;
  9745. ts.writecb = null;
  9746. if (data != null) // single equals check for both `null` and `undefined`
  9747. this.push(data);
  9748. cb(er);
  9749. var rs = this._readableState;
  9750. rs.reading = false;
  9751. if (rs.needReadable || rs.length < rs.highWaterMark) {
  9752. this._read(rs.highWaterMark);
  9753. }
  9754. }
  9755. function Transform(options) {
  9756. if (!(this instanceof Transform)) return new Transform(options);
  9757. Duplex.call(this, options);
  9758. this._transformState = {
  9759. afterTransform: afterTransform.bind(this),
  9760. needTransform: false,
  9761. transforming: false,
  9762. writecb: null,
  9763. writechunk: null,
  9764. writeencoding: null
  9765. };
  9766. // start out asking for a readable event once data is transformed.
  9767. this._readableState.needReadable = true;
  9768. // we have implemented the _read method, and done the other things
  9769. // that Readable wants before the first _read call, so unset the
  9770. // sync guard flag.
  9771. this._readableState.sync = false;
  9772. if (options) {
  9773. if (typeof options.transform === 'function') this._transform = options.transform;
  9774. if (typeof options.flush === 'function') this._flush = options.flush;
  9775. }
  9776. // When the writable side finishes, then flush out anything remaining.
  9777. this.on('prefinish', prefinish);
  9778. }
  9779. function prefinish() {
  9780. var _this = this;
  9781. if (typeof this._flush === 'function') {
  9782. this._flush(function (er, data) {
  9783. done(_this, er, data);
  9784. });
  9785. } else {
  9786. done(this, null, null);
  9787. }
  9788. }
  9789. Transform.prototype.push = function (chunk, encoding) {
  9790. this._transformState.needTransform = false;
  9791. return Duplex.prototype.push.call(this, chunk, encoding);
  9792. };
  9793. // This is the part where you do stuff!
  9794. // override this function in implementation classes.
  9795. // 'chunk' is an input chunk.
  9796. //
  9797. // Call `push(newChunk)` to pass along transformed output
  9798. // to the readable side. You may call 'push' zero or more times.
  9799. //
  9800. // Call `cb(err)` when you are done with this chunk. If you pass
  9801. // an error, then that'll put the hurt on the whole operation. If you
  9802. // never call cb(), then you'll never get another chunk.
  9803. Transform.prototype._transform = function (chunk, encoding, cb) {
  9804. throw new Error('_transform() is not implemented');
  9805. };
  9806. Transform.prototype._write = function (chunk, encoding, cb) {
  9807. var ts = this._transformState;
  9808. ts.writecb = cb;
  9809. ts.writechunk = chunk;
  9810. ts.writeencoding = encoding;
  9811. if (!ts.transforming) {
  9812. var rs = this._readableState;
  9813. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  9814. }
  9815. };
  9816. // Doesn't matter what the args are here.
  9817. // _transform does all the work.
  9818. // That we got here means that the readable side wants more data.
  9819. Transform.prototype._read = function (n) {
  9820. var ts = this._transformState;
  9821. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  9822. ts.transforming = true;
  9823. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  9824. } else {
  9825. // mark that we need a transform, so that any data that comes in
  9826. // will get processed, now that we've asked for it.
  9827. ts.needTransform = true;
  9828. }
  9829. };
  9830. Transform.prototype._destroy = function (err, cb) {
  9831. var _this2 = this;
  9832. Duplex.prototype._destroy.call(this, err, function (err2) {
  9833. cb(err2);
  9834. _this2.emit('close');
  9835. });
  9836. };
  9837. function done(stream, er, data) {
  9838. if (er) return stream.emit('error', er);
  9839. if (data != null) // single equals check for both `null` and `undefined`
  9840. stream.push(data);
  9841. // if there's nothing in the write buffer, then that means
  9842. // that nothing more will ever be provided
  9843. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  9844. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  9845. return stream.push(null);
  9846. }
  9847. },{"./_stream_duplex":98,"core-util-is":14,"inherits":80}],102:[function(require,module,exports){
  9848. (function (process,global,setImmediate){
  9849. // Copyright Joyent, Inc. and other Node contributors.
  9850. //
  9851. // Permission is hereby granted, free of charge, to any person obtaining a
  9852. // copy of this software and associated documentation files (the
  9853. // "Software"), to deal in the Software without restriction, including
  9854. // without limitation the rights to use, copy, modify, merge, publish,
  9855. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9856. // persons to whom the Software is furnished to do so, subject to the
  9857. // following conditions:
  9858. //
  9859. // The above copyright notice and this permission notice shall be included
  9860. // in all copies or substantial portions of the Software.
  9861. //
  9862. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9863. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9864. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9865. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9866. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9867. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9868. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9869. // A bit simpler than readable streams.
  9870. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  9871. // the drain event emission and buffering.
  9872. 'use strict';
  9873. /*<replacement>*/
  9874. var pna = require('process-nextick-args');
  9875. /*</replacement>*/
  9876. module.exports = Writable;
  9877. /* <replacement> */
  9878. function WriteReq(chunk, encoding, cb) {
  9879. this.chunk = chunk;
  9880. this.encoding = encoding;
  9881. this.callback = cb;
  9882. this.next = null;
  9883. }
  9884. // It seems a linked list but it is not
  9885. // there will be only 2 of these for each stream
  9886. function CorkedRequest(state) {
  9887. var _this = this;
  9888. this.next = null;
  9889. this.entry = null;
  9890. this.finish = function () {
  9891. onCorkedFinish(_this, state);
  9892. };
  9893. }
  9894. /* </replacement> */
  9895. /*<replacement>*/
  9896. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  9897. /*</replacement>*/
  9898. /*<replacement>*/
  9899. var Duplex;
  9900. /*</replacement>*/
  9901. Writable.WritableState = WritableState;
  9902. /*<replacement>*/
  9903. var util = require('core-util-is');
  9904. util.inherits = require('inherits');
  9905. /*</replacement>*/
  9906. /*<replacement>*/
  9907. var internalUtil = {
  9908. deprecate: require('util-deprecate')
  9909. };
  9910. /*</replacement>*/
  9911. /*<replacement>*/
  9912. var Stream = require('./internal/streams/stream');
  9913. /*</replacement>*/
  9914. /*<replacement>*/
  9915. var Buffer = require('safe-buffer').Buffer;
  9916. var OurUint8Array = global.Uint8Array || function () {};
  9917. function _uint8ArrayToBuffer(chunk) {
  9918. return Buffer.from(chunk);
  9919. }
  9920. function _isUint8Array(obj) {
  9921. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  9922. }
  9923. /*</replacement>*/
  9924. var destroyImpl = require('./internal/streams/destroy');
  9925. util.inherits(Writable, Stream);
  9926. function nop() {}
  9927. function WritableState(options, stream) {
  9928. Duplex = Duplex || require('./_stream_duplex');
  9929. options = options || {};
  9930. // Duplex streams are both readable and writable, but share
  9931. // the same options object.
  9932. // However, some cases require setting options to different
  9933. // values for the readable and the writable sides of the duplex stream.
  9934. // These options can be provided separately as readableXXX and writableXXX.
  9935. var isDuplex = stream instanceof Duplex;
  9936. // object stream flag to indicate whether or not this stream
  9937. // contains buffers or objects.
  9938. this.objectMode = !!options.objectMode;
  9939. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  9940. // the point at which write() starts returning false
  9941. // Note: 0 is a valid value, means that we always return false if
  9942. // the entire buffer is not flushed immediately on write()
  9943. var hwm = options.highWaterMark;
  9944. var writableHwm = options.writableHighWaterMark;
  9945. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  9946. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  9947. // cast to ints.
  9948. this.highWaterMark = Math.floor(this.highWaterMark);
  9949. // if _final has been called
  9950. this.finalCalled = false;
  9951. // drain event flag.
  9952. this.needDrain = false;
  9953. // at the start of calling end()
  9954. this.ending = false;
  9955. // when end() has been called, and returned
  9956. this.ended = false;
  9957. // when 'finish' is emitted
  9958. this.finished = false;
  9959. // has it been destroyed
  9960. this.destroyed = false;
  9961. // should we decode strings into buffers before passing to _write?
  9962. // this is here so that some node-core streams can optimize string
  9963. // handling at a lower level.
  9964. var noDecode = options.decodeStrings === false;
  9965. this.decodeStrings = !noDecode;
  9966. // Crypto is kind of old and crusty. Historically, its default string
  9967. // encoding is 'binary' so we have to make this configurable.
  9968. // Everything else in the universe uses 'utf8', though.
  9969. this.defaultEncoding = options.defaultEncoding || 'utf8';
  9970. // not an actual buffer we keep track of, but a measurement
  9971. // of how much we're waiting to get pushed to some underlying
  9972. // socket or file.
  9973. this.length = 0;
  9974. // a flag to see when we're in the middle of a write.
  9975. this.writing = false;
  9976. // when true all writes will be buffered until .uncork() call
  9977. this.corked = 0;
  9978. // a flag to be able to tell if the onwrite cb is called immediately,
  9979. // or on a later tick. We set this to true at first, because any
  9980. // actions that shouldn't happen until "later" should generally also
  9981. // not happen before the first write call.
  9982. this.sync = true;
  9983. // a flag to know if we're processing previously buffered items, which
  9984. // may call the _write() callback in the same tick, so that we don't
  9985. // end up in an overlapped onwrite situation.
  9986. this.bufferProcessing = false;
  9987. // the callback that's passed to _write(chunk,cb)
  9988. this.onwrite = function (er) {
  9989. onwrite(stream, er);
  9990. };
  9991. // the callback that the user supplies to write(chunk,encoding,cb)
  9992. this.writecb = null;
  9993. // the amount that is being written when _write is called.
  9994. this.writelen = 0;
  9995. this.bufferedRequest = null;
  9996. this.lastBufferedRequest = null;
  9997. // number of pending user-supplied write callbacks
  9998. // this must be 0 before 'finish' can be emitted
  9999. this.pendingcb = 0;
  10000. // emit prefinish if the only thing we're waiting for is _write cbs
  10001. // This is relevant for synchronous Transform streams
  10002. this.prefinished = false;
  10003. // True if the error was already emitted and should not be thrown again
  10004. this.errorEmitted = false;
  10005. // count buffered requests
  10006. this.bufferedRequestCount = 0;
  10007. // allocate the first CorkedRequest, there is always
  10008. // one allocated and free to use, and we maintain at most two
  10009. this.corkedRequestsFree = new CorkedRequest(this);
  10010. }
  10011. WritableState.prototype.getBuffer = function getBuffer() {
  10012. var current = this.bufferedRequest;
  10013. var out = [];
  10014. while (current) {
  10015. out.push(current);
  10016. current = current.next;
  10017. }
  10018. return out;
  10019. };
  10020. (function () {
  10021. try {
  10022. Object.defineProperty(WritableState.prototype, 'buffer', {
  10023. get: internalUtil.deprecate(function () {
  10024. return this.getBuffer();
  10025. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  10026. });
  10027. } catch (_) {}
  10028. })();
  10029. // Test _writableState for inheritance to account for Duplex streams,
  10030. // whose prototype chain only points to Readable.
  10031. var realHasInstance;
  10032. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  10033. realHasInstance = Function.prototype[Symbol.hasInstance];
  10034. Object.defineProperty(Writable, Symbol.hasInstance, {
  10035. value: function (object) {
  10036. if (realHasInstance.call(this, object)) return true;
  10037. if (this !== Writable) return false;
  10038. return object && object._writableState instanceof WritableState;
  10039. }
  10040. });
  10041. } else {
  10042. realHasInstance = function (object) {
  10043. return object instanceof this;
  10044. };
  10045. }
  10046. function Writable(options) {
  10047. Duplex = Duplex || require('./_stream_duplex');
  10048. // Writable ctor is applied to Duplexes, too.
  10049. // `realHasInstance` is necessary because using plain `instanceof`
  10050. // would return false, as no `_writableState` property is attached.
  10051. // Trying to use the custom `instanceof` for Writable here will also break the
  10052. // Node.js LazyTransform implementation, which has a non-trivial getter for
  10053. // `_writableState` that would lead to infinite recursion.
  10054. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  10055. return new Writable(options);
  10056. }
  10057. this._writableState = new WritableState(options, this);
  10058. // legacy.
  10059. this.writable = true;
  10060. if (options) {
  10061. if (typeof options.write === 'function') this._write = options.write;
  10062. if (typeof options.writev === 'function') this._writev = options.writev;
  10063. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  10064. if (typeof options.final === 'function') this._final = options.final;
  10065. }
  10066. Stream.call(this);
  10067. }
  10068. // Otherwise people can pipe Writable streams, which is just wrong.
  10069. Writable.prototype.pipe = function () {
  10070. this.emit('error', new Error('Cannot pipe, not readable'));
  10071. };
  10072. function writeAfterEnd(stream, cb) {
  10073. var er = new Error('write after end');
  10074. // TODO: defer error events consistently everywhere, not just the cb
  10075. stream.emit('error', er);
  10076. pna.nextTick(cb, er);
  10077. }
  10078. // Checks that a user-supplied chunk is valid, especially for the particular
  10079. // mode the stream is in. Currently this means that `null` is never accepted
  10080. // and undefined/non-string values are only allowed in object mode.
  10081. function validChunk(stream, state, chunk, cb) {
  10082. var valid = true;
  10083. var er = false;
  10084. if (chunk === null) {
  10085. er = new TypeError('May not write null values to stream');
  10086. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  10087. er = new TypeError('Invalid non-string/buffer chunk');
  10088. }
  10089. if (er) {
  10090. stream.emit('error', er);
  10091. pna.nextTick(cb, er);
  10092. valid = false;
  10093. }
  10094. return valid;
  10095. }
  10096. Writable.prototype.write = function (chunk, encoding, cb) {
  10097. var state = this._writableState;
  10098. var ret = false;
  10099. var isBuf = !state.objectMode && _isUint8Array(chunk);
  10100. if (isBuf && !Buffer.isBuffer(chunk)) {
  10101. chunk = _uint8ArrayToBuffer(chunk);
  10102. }
  10103. if (typeof encoding === 'function') {
  10104. cb = encoding;
  10105. encoding = null;
  10106. }
  10107. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  10108. if (typeof cb !== 'function') cb = nop;
  10109. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  10110. state.pendingcb++;
  10111. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  10112. }
  10113. return ret;
  10114. };
  10115. Writable.prototype.cork = function () {
  10116. var state = this._writableState;
  10117. state.corked++;
  10118. };
  10119. Writable.prototype.uncork = function () {
  10120. var state = this._writableState;
  10121. if (state.corked) {
  10122. state.corked--;
  10123. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  10124. }
  10125. };
  10126. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  10127. // node::ParseEncoding() requires lower case.
  10128. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  10129. 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);
  10130. this._writableState.defaultEncoding = encoding;
  10131. return this;
  10132. };
  10133. function decodeChunk(state, chunk, encoding) {
  10134. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  10135. chunk = Buffer.from(chunk, encoding);
  10136. }
  10137. return chunk;
  10138. }
  10139. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  10140. // making it explicit this property is not enumerable
  10141. // because otherwise some prototype manipulation in
  10142. // userland will fail
  10143. enumerable: false,
  10144. get: function () {
  10145. return this._writableState.highWaterMark;
  10146. }
  10147. });
  10148. // if we're already writing something, then just put this
  10149. // in the queue, and wait our turn. Otherwise, call _write
  10150. // If we return false, then we need a drain event, so set that flag.
  10151. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  10152. if (!isBuf) {
  10153. var newChunk = decodeChunk(state, chunk, encoding);
  10154. if (chunk !== newChunk) {
  10155. isBuf = true;
  10156. encoding = 'buffer';
  10157. chunk = newChunk;
  10158. }
  10159. }
  10160. var len = state.objectMode ? 1 : chunk.length;
  10161. state.length += len;
  10162. var ret = state.length < state.highWaterMark;
  10163. // we must ensure that previous needDrain will not be reset to false.
  10164. if (!ret) state.needDrain = true;
  10165. if (state.writing || state.corked) {
  10166. var last = state.lastBufferedRequest;
  10167. state.lastBufferedRequest = {
  10168. chunk: chunk,
  10169. encoding: encoding,
  10170. isBuf: isBuf,
  10171. callback: cb,
  10172. next: null
  10173. };
  10174. if (last) {
  10175. last.next = state.lastBufferedRequest;
  10176. } else {
  10177. state.bufferedRequest = state.lastBufferedRequest;
  10178. }
  10179. state.bufferedRequestCount += 1;
  10180. } else {
  10181. doWrite(stream, state, false, len, chunk, encoding, cb);
  10182. }
  10183. return ret;
  10184. }
  10185. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  10186. state.writelen = len;
  10187. state.writecb = cb;
  10188. state.writing = true;
  10189. state.sync = true;
  10190. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  10191. state.sync = false;
  10192. }
  10193. function onwriteError(stream, state, sync, er, cb) {
  10194. --state.pendingcb;
  10195. if (sync) {
  10196. // defer the callback if we are being called synchronously
  10197. // to avoid piling up things on the stack
  10198. pna.nextTick(cb, er);
  10199. // this can emit finish, and it will always happen
  10200. // after error
  10201. pna.nextTick(finishMaybe, stream, state);
  10202. stream._writableState.errorEmitted = true;
  10203. stream.emit('error', er);
  10204. } else {
  10205. // the caller expect this to happen before if
  10206. // it is async
  10207. cb(er);
  10208. stream._writableState.errorEmitted = true;
  10209. stream.emit('error', er);
  10210. // this can emit finish, but finish must
  10211. // always follow error
  10212. finishMaybe(stream, state);
  10213. }
  10214. }
  10215. function onwriteStateUpdate(state) {
  10216. state.writing = false;
  10217. state.writecb = null;
  10218. state.length -= state.writelen;
  10219. state.writelen = 0;
  10220. }
  10221. function onwrite(stream, er) {
  10222. var state = stream._writableState;
  10223. var sync = state.sync;
  10224. var cb = state.writecb;
  10225. onwriteStateUpdate(state);
  10226. if (er) onwriteError(stream, state, sync, er, cb);else {
  10227. // Check if we're actually ready to finish, but don't emit yet
  10228. var finished = needFinish(state);
  10229. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  10230. clearBuffer(stream, state);
  10231. }
  10232. if (sync) {
  10233. /*<replacement>*/
  10234. asyncWrite(afterWrite, stream, state, finished, cb);
  10235. /*</replacement>*/
  10236. } else {
  10237. afterWrite(stream, state, finished, cb);
  10238. }
  10239. }
  10240. }
  10241. function afterWrite(stream, state, finished, cb) {
  10242. if (!finished) onwriteDrain(stream, state);
  10243. state.pendingcb--;
  10244. cb();
  10245. finishMaybe(stream, state);
  10246. }
  10247. // Must force callback to be called on nextTick, so that we don't
  10248. // emit 'drain' before the write() consumer gets the 'false' return
  10249. // value, and has a chance to attach a 'drain' listener.
  10250. function onwriteDrain(stream, state) {
  10251. if (state.length === 0 && state.needDrain) {
  10252. state.needDrain = false;
  10253. stream.emit('drain');
  10254. }
  10255. }
  10256. // if there's something in the buffer waiting, then process it
  10257. function clearBuffer(stream, state) {
  10258. state.bufferProcessing = true;
  10259. var entry = state.bufferedRequest;
  10260. if (stream._writev && entry && entry.next) {
  10261. // Fast case, write everything using _writev()
  10262. var l = state.bufferedRequestCount;
  10263. var buffer = new Array(l);
  10264. var holder = state.corkedRequestsFree;
  10265. holder.entry = entry;
  10266. var count = 0;
  10267. var allBuffers = true;
  10268. while (entry) {
  10269. buffer[count] = entry;
  10270. if (!entry.isBuf) allBuffers = false;
  10271. entry = entry.next;
  10272. count += 1;
  10273. }
  10274. buffer.allBuffers = allBuffers;
  10275. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  10276. // doWrite is almost always async, defer these to save a bit of time
  10277. // as the hot path ends with doWrite
  10278. state.pendingcb++;
  10279. state.lastBufferedRequest = null;
  10280. if (holder.next) {
  10281. state.corkedRequestsFree = holder.next;
  10282. holder.next = null;
  10283. } else {
  10284. state.corkedRequestsFree = new CorkedRequest(state);
  10285. }
  10286. state.bufferedRequestCount = 0;
  10287. } else {
  10288. // Slow case, write chunks one-by-one
  10289. while (entry) {
  10290. var chunk = entry.chunk;
  10291. var encoding = entry.encoding;
  10292. var cb = entry.callback;
  10293. var len = state.objectMode ? 1 : chunk.length;
  10294. doWrite(stream, state, false, len, chunk, encoding, cb);
  10295. entry = entry.next;
  10296. state.bufferedRequestCount--;
  10297. // if we didn't call the onwrite immediately, then
  10298. // it means that we need to wait until it does.
  10299. // also, that means that the chunk and cb are currently
  10300. // being processed, so move the buffer counter past them.
  10301. if (state.writing) {
  10302. break;
  10303. }
  10304. }
  10305. if (entry === null) state.lastBufferedRequest = null;
  10306. }
  10307. state.bufferedRequest = entry;
  10308. state.bufferProcessing = false;
  10309. }
  10310. Writable.prototype._write = function (chunk, encoding, cb) {
  10311. cb(new Error('_write() is not implemented'));
  10312. };
  10313. Writable.prototype._writev = null;
  10314. Writable.prototype.end = function (chunk, encoding, cb) {
  10315. var state = this._writableState;
  10316. if (typeof chunk === 'function') {
  10317. cb = chunk;
  10318. chunk = null;
  10319. encoding = null;
  10320. } else if (typeof encoding === 'function') {
  10321. cb = encoding;
  10322. encoding = null;
  10323. }
  10324. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  10325. // .end() fully uncorks
  10326. if (state.corked) {
  10327. state.corked = 1;
  10328. this.uncork();
  10329. }
  10330. // ignore unnecessary end() calls.
  10331. if (!state.ending && !state.finished) endWritable(this, state, cb);
  10332. };
  10333. function needFinish(state) {
  10334. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  10335. }
  10336. function callFinal(stream, state) {
  10337. stream._final(function (err) {
  10338. state.pendingcb--;
  10339. if (err) {
  10340. stream.emit('error', err);
  10341. }
  10342. state.prefinished = true;
  10343. stream.emit('prefinish');
  10344. finishMaybe(stream, state);
  10345. });
  10346. }
  10347. function prefinish(stream, state) {
  10348. if (!state.prefinished && !state.finalCalled) {
  10349. if (typeof stream._final === 'function') {
  10350. state.pendingcb++;
  10351. state.finalCalled = true;
  10352. pna.nextTick(callFinal, stream, state);
  10353. } else {
  10354. state.prefinished = true;
  10355. stream.emit('prefinish');
  10356. }
  10357. }
  10358. }
  10359. function finishMaybe(stream, state) {
  10360. var need = needFinish(state);
  10361. if (need) {
  10362. prefinish(stream, state);
  10363. if (state.pendingcb === 0) {
  10364. state.finished = true;
  10365. stream.emit('finish');
  10366. }
  10367. }
  10368. return need;
  10369. }
  10370. function endWritable(stream, state, cb) {
  10371. state.ending = true;
  10372. finishMaybe(stream, state);
  10373. if (cb) {
  10374. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  10375. }
  10376. state.ended = true;
  10377. stream.writable = false;
  10378. }
  10379. function onCorkedFinish(corkReq, state, err) {
  10380. var entry = corkReq.entry;
  10381. corkReq.entry = null;
  10382. while (entry) {
  10383. var cb = entry.callback;
  10384. state.pendingcb--;
  10385. cb(err);
  10386. entry = entry.next;
  10387. }
  10388. if (state.corkedRequestsFree) {
  10389. state.corkedRequestsFree.next = corkReq;
  10390. } else {
  10391. state.corkedRequestsFree = corkReq;
  10392. }
  10393. }
  10394. Object.defineProperty(Writable.prototype, 'destroyed', {
  10395. get: function () {
  10396. if (this._writableState === undefined) {
  10397. return false;
  10398. }
  10399. return this._writableState.destroyed;
  10400. },
  10401. set: function (value) {
  10402. // we ignore the value if the stream
  10403. // has not been initialized yet
  10404. if (!this._writableState) {
  10405. return;
  10406. }
  10407. // backward compatibility, the user is explicitly
  10408. // managing destroyed
  10409. this._writableState.destroyed = value;
  10410. }
  10411. });
  10412. Writable.prototype.destroy = destroyImpl.destroy;
  10413. Writable.prototype._undestroy = destroyImpl.undestroy;
  10414. Writable.prototype._destroy = function (err, cb) {
  10415. this.end();
  10416. cb(err);
  10417. };
  10418. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  10419. },{"./_stream_duplex":98,"./internal/streams/destroy":104,"./internal/streams/stream":105,"_process":92,"core-util-is":14,"inherits":80,"process-nextick-args":91,"safe-buffer":110,"timers":112,"util-deprecate":115}],103:[function(require,module,exports){
  10420. 'use strict';
  10421. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10422. var Buffer = require('safe-buffer').Buffer;
  10423. var util = require('util');
  10424. function copyBuffer(src, target, offset) {
  10425. src.copy(target, offset);
  10426. }
  10427. module.exports = function () {
  10428. function BufferList() {
  10429. _classCallCheck(this, BufferList);
  10430. this.head = null;
  10431. this.tail = null;
  10432. this.length = 0;
  10433. }
  10434. BufferList.prototype.push = function push(v) {
  10435. var entry = { data: v, next: null };
  10436. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  10437. this.tail = entry;
  10438. ++this.length;
  10439. };
  10440. BufferList.prototype.unshift = function unshift(v) {
  10441. var entry = { data: v, next: this.head };
  10442. if (this.length === 0) this.tail = entry;
  10443. this.head = entry;
  10444. ++this.length;
  10445. };
  10446. BufferList.prototype.shift = function shift() {
  10447. if (this.length === 0) return;
  10448. var ret = this.head.data;
  10449. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  10450. --this.length;
  10451. return ret;
  10452. };
  10453. BufferList.prototype.clear = function clear() {
  10454. this.head = this.tail = null;
  10455. this.length = 0;
  10456. };
  10457. BufferList.prototype.join = function join(s) {
  10458. if (this.length === 0) return '';
  10459. var p = this.head;
  10460. var ret = '' + p.data;
  10461. while (p = p.next) {
  10462. ret += s + p.data;
  10463. }return ret;
  10464. };
  10465. BufferList.prototype.concat = function concat(n) {
  10466. if (this.length === 0) return Buffer.alloc(0);
  10467. if (this.length === 1) return this.head.data;
  10468. var ret = Buffer.allocUnsafe(n >>> 0);
  10469. var p = this.head;
  10470. var i = 0;
  10471. while (p) {
  10472. copyBuffer(p.data, ret, i);
  10473. i += p.data.length;
  10474. p = p.next;
  10475. }
  10476. return ret;
  10477. };
  10478. return BufferList;
  10479. }();
  10480. if (util && util.inspect && util.inspect.custom) {
  10481. module.exports.prototype[util.inspect.custom] = function () {
  10482. var obj = util.inspect({ length: this.length });
  10483. return this.constructor.name + ' ' + obj;
  10484. };
  10485. }
  10486. },{"safe-buffer":110,"util":11}],104:[function(require,module,exports){
  10487. 'use strict';
  10488. /*<replacement>*/
  10489. var pna = require('process-nextick-args');
  10490. /*</replacement>*/
  10491. // undocumented cb() API, needed for core, not for public API
  10492. function destroy(err, cb) {
  10493. var _this = this;
  10494. var readableDestroyed = this._readableState && this._readableState.destroyed;
  10495. var writableDestroyed = this._writableState && this._writableState.destroyed;
  10496. if (readableDestroyed || writableDestroyed) {
  10497. if (cb) {
  10498. cb(err);
  10499. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  10500. pna.nextTick(emitErrorNT, this, err);
  10501. }
  10502. return this;
  10503. }
  10504. // we set destroyed to true before firing error callbacks in order
  10505. // to make it re-entrance safe in case destroy() is called within callbacks
  10506. if (this._readableState) {
  10507. this._readableState.destroyed = true;
  10508. }
  10509. // if this is a duplex stream mark the writable part as destroyed as well
  10510. if (this._writableState) {
  10511. this._writableState.destroyed = true;
  10512. }
  10513. this._destroy(err || null, function (err) {
  10514. if (!cb && err) {
  10515. pna.nextTick(emitErrorNT, _this, err);
  10516. if (_this._writableState) {
  10517. _this._writableState.errorEmitted = true;
  10518. }
  10519. } else if (cb) {
  10520. cb(err);
  10521. }
  10522. });
  10523. return this;
  10524. }
  10525. function undestroy() {
  10526. if (this._readableState) {
  10527. this._readableState.destroyed = false;
  10528. this._readableState.reading = false;
  10529. this._readableState.ended = false;
  10530. this._readableState.endEmitted = false;
  10531. }
  10532. if (this._writableState) {
  10533. this._writableState.destroyed = false;
  10534. this._writableState.ended = false;
  10535. this._writableState.ending = false;
  10536. this._writableState.finished = false;
  10537. this._writableState.errorEmitted = false;
  10538. }
  10539. }
  10540. function emitErrorNT(self, err) {
  10541. self.emit('error', err);
  10542. }
  10543. module.exports = {
  10544. destroy: destroy,
  10545. undestroy: undestroy
  10546. };
  10547. },{"process-nextick-args":91}],105:[function(require,module,exports){
  10548. module.exports = require('events').EventEmitter;
  10549. },{"events":13}],106:[function(require,module,exports){
  10550. var toString = {}.toString;
  10551. module.exports = Array.isArray || function (arr) {
  10552. return toString.call(arr) == '[object Array]';
  10553. };
  10554. },{}],107:[function(require,module,exports){
  10555. // Copyright Joyent, Inc. and other Node contributors.
  10556. //
  10557. // Permission is hereby granted, free of charge, to any person obtaining a
  10558. // copy of this software and associated documentation files (the
  10559. // "Software"), to deal in the Software without restriction, including
  10560. // without limitation the rights to use, copy, modify, merge, publish,
  10561. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10562. // persons to whom the Software is furnished to do so, subject to the
  10563. // following conditions:
  10564. //
  10565. // The above copyright notice and this permission notice shall be included
  10566. // in all copies or substantial portions of the Software.
  10567. //
  10568. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10569. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10570. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10571. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10572. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10573. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10574. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10575. 'use strict';
  10576. /*<replacement>*/
  10577. var Buffer = require('safe-buffer').Buffer;
  10578. /*</replacement>*/
  10579. var isEncoding = Buffer.isEncoding || function (encoding) {
  10580. encoding = '' + encoding;
  10581. switch (encoding && encoding.toLowerCase()) {
  10582. 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':
  10583. return true;
  10584. default:
  10585. return false;
  10586. }
  10587. };
  10588. function _normalizeEncoding(enc) {
  10589. if (!enc) return 'utf8';
  10590. var retried;
  10591. while (true) {
  10592. switch (enc) {
  10593. case 'utf8':
  10594. case 'utf-8':
  10595. return 'utf8';
  10596. case 'ucs2':
  10597. case 'ucs-2':
  10598. case 'utf16le':
  10599. case 'utf-16le':
  10600. return 'utf16le';
  10601. case 'latin1':
  10602. case 'binary':
  10603. return 'latin1';
  10604. case 'base64':
  10605. case 'ascii':
  10606. case 'hex':
  10607. return enc;
  10608. default:
  10609. if (retried) return; // undefined
  10610. enc = ('' + enc).toLowerCase();
  10611. retried = true;
  10612. }
  10613. }
  10614. };
  10615. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  10616. // modules monkey-patch it to support additional encodings
  10617. function normalizeEncoding(enc) {
  10618. var nenc = _normalizeEncoding(enc);
  10619. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  10620. return nenc || enc;
  10621. }
  10622. // StringDecoder provides an interface for efficiently splitting a series of
  10623. // buffers into a series of JS strings without breaking apart multi-byte
  10624. // characters.
  10625. exports.StringDecoder = StringDecoder;
  10626. function StringDecoder(encoding) {
  10627. this.encoding = normalizeEncoding(encoding);
  10628. var nb;
  10629. switch (this.encoding) {
  10630. case 'utf16le':
  10631. this.text = utf16Text;
  10632. this.end = utf16End;
  10633. nb = 4;
  10634. break;
  10635. case 'utf8':
  10636. this.fillLast = utf8FillLast;
  10637. nb = 4;
  10638. break;
  10639. case 'base64':
  10640. this.text = base64Text;
  10641. this.end = base64End;
  10642. nb = 3;
  10643. break;
  10644. default:
  10645. this.write = simpleWrite;
  10646. this.end = simpleEnd;
  10647. return;
  10648. }
  10649. this.lastNeed = 0;
  10650. this.lastTotal = 0;
  10651. this.lastChar = Buffer.allocUnsafe(nb);
  10652. }
  10653. StringDecoder.prototype.write = function (buf) {
  10654. if (buf.length === 0) return '';
  10655. var r;
  10656. var i;
  10657. if (this.lastNeed) {
  10658. r = this.fillLast(buf);
  10659. if (r === undefined) return '';
  10660. i = this.lastNeed;
  10661. this.lastNeed = 0;
  10662. } else {
  10663. i = 0;
  10664. }
  10665. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  10666. return r || '';
  10667. };
  10668. StringDecoder.prototype.end = utf8End;
  10669. // Returns only complete characters in a Buffer
  10670. StringDecoder.prototype.text = utf8Text;
  10671. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  10672. StringDecoder.prototype.fillLast = function (buf) {
  10673. if (this.lastNeed <= buf.length) {
  10674. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  10675. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10676. }
  10677. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  10678. this.lastNeed -= buf.length;
  10679. };
  10680. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  10681. // continuation byte. If an invalid byte is detected, -2 is returned.
  10682. function utf8CheckByte(byte) {
  10683. 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;
  10684. return byte >> 6 === 0x02 ? -1 : -2;
  10685. }
  10686. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  10687. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  10688. // needed to complete the UTF-8 character (if applicable) are returned.
  10689. function utf8CheckIncomplete(self, buf, i) {
  10690. var j = buf.length - 1;
  10691. if (j < i) return 0;
  10692. var nb = utf8CheckByte(buf[j]);
  10693. if (nb >= 0) {
  10694. if (nb > 0) self.lastNeed = nb - 1;
  10695. return nb;
  10696. }
  10697. if (--j < i || nb === -2) return 0;
  10698. nb = utf8CheckByte(buf[j]);
  10699. if (nb >= 0) {
  10700. if (nb > 0) self.lastNeed = nb - 2;
  10701. return nb;
  10702. }
  10703. if (--j < i || nb === -2) return 0;
  10704. nb = utf8CheckByte(buf[j]);
  10705. if (nb >= 0) {
  10706. if (nb > 0) {
  10707. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  10708. }
  10709. return nb;
  10710. }
  10711. return 0;
  10712. }
  10713. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  10714. // needed or are available. If we see a non-continuation byte where we expect
  10715. // one, we "replace" the validated continuation bytes we've seen so far with
  10716. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  10717. // behavior. The continuation byte check is included three times in the case
  10718. // where all of the continuation bytes for a character exist in the same buffer.
  10719. // It is also done this way as a slight performance increase instead of using a
  10720. // loop.
  10721. function utf8CheckExtraBytes(self, buf, p) {
  10722. if ((buf[0] & 0xC0) !== 0x80) {
  10723. self.lastNeed = 0;
  10724. return '\ufffd';
  10725. }
  10726. if (self.lastNeed > 1 && buf.length > 1) {
  10727. if ((buf[1] & 0xC0) !== 0x80) {
  10728. self.lastNeed = 1;
  10729. return '\ufffd';
  10730. }
  10731. if (self.lastNeed > 2 && buf.length > 2) {
  10732. if ((buf[2] & 0xC0) !== 0x80) {
  10733. self.lastNeed = 2;
  10734. return '\ufffd';
  10735. }
  10736. }
  10737. }
  10738. }
  10739. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  10740. function utf8FillLast(buf) {
  10741. var p = this.lastTotal - this.lastNeed;
  10742. var r = utf8CheckExtraBytes(this, buf, p);
  10743. if (r !== undefined) return r;
  10744. if (this.lastNeed <= buf.length) {
  10745. buf.copy(this.lastChar, p, 0, this.lastNeed);
  10746. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10747. }
  10748. buf.copy(this.lastChar, p, 0, buf.length);
  10749. this.lastNeed -= buf.length;
  10750. }
  10751. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  10752. // partial character, the character's bytes are buffered until the required
  10753. // number of bytes are available.
  10754. function utf8Text(buf, i) {
  10755. var total = utf8CheckIncomplete(this, buf, i);
  10756. if (!this.lastNeed) return buf.toString('utf8', i);
  10757. this.lastTotal = total;
  10758. var end = buf.length - (total - this.lastNeed);
  10759. buf.copy(this.lastChar, 0, end);
  10760. return buf.toString('utf8', i, end);
  10761. }
  10762. // For UTF-8, a replacement character is added when ending on a partial
  10763. // character.
  10764. function utf8End(buf) {
  10765. var r = buf && buf.length ? this.write(buf) : '';
  10766. if (this.lastNeed) return r + '\ufffd';
  10767. return r;
  10768. }
  10769. // UTF-16LE typically needs two bytes per character, but even if we have an even
  10770. // number of bytes available, we need to check if we end on a leading/high
  10771. // surrogate. In that case, we need to wait for the next two bytes in order to
  10772. // decode the last character properly.
  10773. function utf16Text(buf, i) {
  10774. if ((buf.length - i) % 2 === 0) {
  10775. var r = buf.toString('utf16le', i);
  10776. if (r) {
  10777. var c = r.charCodeAt(r.length - 1);
  10778. if (c >= 0xD800 && c <= 0xDBFF) {
  10779. this.lastNeed = 2;
  10780. this.lastTotal = 4;
  10781. this.lastChar[0] = buf[buf.length - 2];
  10782. this.lastChar[1] = buf[buf.length - 1];
  10783. return r.slice(0, -1);
  10784. }
  10785. }
  10786. return r;
  10787. }
  10788. this.lastNeed = 1;
  10789. this.lastTotal = 2;
  10790. this.lastChar[0] = buf[buf.length - 1];
  10791. return buf.toString('utf16le', i, buf.length - 1);
  10792. }
  10793. // For UTF-16LE we do not explicitly append special replacement characters if we
  10794. // end on a partial character, we simply let v8 handle that.
  10795. function utf16End(buf) {
  10796. var r = buf && buf.length ? this.write(buf) : '';
  10797. if (this.lastNeed) {
  10798. var end = this.lastTotal - this.lastNeed;
  10799. return r + this.lastChar.toString('utf16le', 0, end);
  10800. }
  10801. return r;
  10802. }
  10803. function base64Text(buf, i) {
  10804. var n = (buf.length - i) % 3;
  10805. if (n === 0) return buf.toString('base64', i);
  10806. this.lastNeed = 3 - n;
  10807. this.lastTotal = 3;
  10808. if (n === 1) {
  10809. this.lastChar[0] = buf[buf.length - 1];
  10810. } else {
  10811. this.lastChar[0] = buf[buf.length - 2];
  10812. this.lastChar[1] = buf[buf.length - 1];
  10813. }
  10814. return buf.toString('base64', i, buf.length - n);
  10815. }
  10816. function base64End(buf) {
  10817. var r = buf && buf.length ? this.write(buf) : '';
  10818. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  10819. return r;
  10820. }
  10821. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  10822. function simpleWrite(buf) {
  10823. return buf.toString(this.encoding);
  10824. }
  10825. function simpleEnd(buf) {
  10826. return buf && buf.length ? this.write(buf) : '';
  10827. }
  10828. },{"safe-buffer":110}],108:[function(require,module,exports){
  10829. exports = module.exports = require('./lib/_stream_readable.js');
  10830. exports.Stream = exports;
  10831. exports.Readable = exports;
  10832. exports.Writable = require('./lib/_stream_writable.js');
  10833. exports.Duplex = require('./lib/_stream_duplex.js');
  10834. exports.Transform = require('./lib/_stream_transform.js');
  10835. exports.PassThrough = require('./lib/_stream_passthrough.js');
  10836. },{"./lib/_stream_duplex.js":98,"./lib/_stream_passthrough.js":99,"./lib/_stream_readable.js":100,"./lib/_stream_transform.js":101,"./lib/_stream_writable.js":102}],109:[function(require,module,exports){
  10837. 'use strict'
  10838. function ReInterval (callback, interval, args) {
  10839. var self = this;
  10840. this._callback = callback;
  10841. this._args = args;
  10842. this._interval = setInterval(callback, interval, this._args);
  10843. this.reschedule = function (interval) {
  10844. // if no interval entered, use the interval passed in on creation
  10845. if (!interval)
  10846. interval = self._interval;
  10847. if (self._interval)
  10848. clearInterval(self._interval);
  10849. self._interval = setInterval(self._callback, interval, self._args);
  10850. };
  10851. this.clear = function () {
  10852. if (self._interval) {
  10853. clearInterval(self._interval);
  10854. self._interval = undefined;
  10855. }
  10856. };
  10857. this.destroy = function () {
  10858. if (self._interval) {
  10859. clearInterval(self._interval);
  10860. }
  10861. self._callback = undefined;
  10862. self._interval = undefined;
  10863. self._args = undefined;
  10864. };
  10865. }
  10866. function reInterval () {
  10867. if (typeof arguments[0] !== 'function')
  10868. throw new Error('callback needed');
  10869. if (typeof arguments[1] !== 'number')
  10870. throw new Error('interval needed');
  10871. var args;
  10872. if (arguments.length > 0) {
  10873. args = new Array(arguments.length - 2);
  10874. for (var i = 0; i < args.length; i++) {
  10875. args[i] = arguments[i + 2];
  10876. }
  10877. }
  10878. return new ReInterval(arguments[0], arguments[1], args);
  10879. }
  10880. module.exports = reInterval;
  10881. },{}],110:[function(require,module,exports){
  10882. /* eslint-disable node/no-deprecated-api */
  10883. var buffer = require('buffer')
  10884. var Buffer = buffer.Buffer
  10885. // alternative to using Object.keys for old browsers
  10886. function copyProps (src, dst) {
  10887. for (var key in src) {
  10888. dst[key] = src[key]
  10889. }
  10890. }
  10891. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  10892. module.exports = buffer
  10893. } else {
  10894. // Copy properties from require('buffer')
  10895. copyProps(buffer, exports)
  10896. exports.Buffer = SafeBuffer
  10897. }
  10898. function SafeBuffer (arg, encodingOrOffset, length) {
  10899. return Buffer(arg, encodingOrOffset, length)
  10900. }
  10901. // Copy static methods from Buffer
  10902. copyProps(Buffer, SafeBuffer)
  10903. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  10904. if (typeof arg === 'number') {
  10905. throw new TypeError('Argument must not be a number')
  10906. }
  10907. return Buffer(arg, encodingOrOffset, length)
  10908. }
  10909. SafeBuffer.alloc = function (size, fill, encoding) {
  10910. if (typeof size !== 'number') {
  10911. throw new TypeError('Argument must be a number')
  10912. }
  10913. var buf = Buffer(size)
  10914. if (fill !== undefined) {
  10915. if (typeof encoding === 'string') {
  10916. buf.fill(fill, encoding)
  10917. } else {
  10918. buf.fill(fill)
  10919. }
  10920. } else {
  10921. buf.fill(0)
  10922. }
  10923. return buf
  10924. }
  10925. SafeBuffer.allocUnsafe = function (size) {
  10926. if (typeof size !== 'number') {
  10927. throw new TypeError('Argument must be a number')
  10928. }
  10929. return Buffer(size)
  10930. }
  10931. SafeBuffer.allocUnsafeSlow = function (size) {
  10932. if (typeof size !== 'number') {
  10933. throw new TypeError('Argument must be a number')
  10934. }
  10935. return buffer.SlowBuffer(size)
  10936. }
  10937. },{"buffer":12}],111:[function(require,module,exports){
  10938. module.exports = shift
  10939. function shift (stream) {
  10940. var rs = stream._readableState
  10941. if (!rs) return null
  10942. return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
  10943. }
  10944. function getStateLength (state) {
  10945. if (state.buffer.length) {
  10946. // Since node 6.3.0 state.buffer is a BufferList not an array
  10947. if (state.buffer.head) {
  10948. return state.buffer.head.data.length
  10949. }
  10950. return state.buffer[0].length
  10951. }
  10952. return state.length
  10953. }
  10954. },{}],112:[function(require,module,exports){
  10955. (function (setImmediate,clearImmediate){
  10956. var nextTick = require('process/browser.js').nextTick;
  10957. var apply = Function.prototype.apply;
  10958. var slice = Array.prototype.slice;
  10959. var immediateIds = {};
  10960. var nextImmediateId = 0;
  10961. // DOM APIs, for completeness
  10962. exports.setTimeout = function() {
  10963. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  10964. };
  10965. exports.setInterval = function() {
  10966. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  10967. };
  10968. exports.clearTimeout =
  10969. exports.clearInterval = function(timeout) { timeout.close(); };
  10970. function Timeout(id, clearFn) {
  10971. this._id = id;
  10972. this._clearFn = clearFn;
  10973. }
  10974. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  10975. Timeout.prototype.close = function() {
  10976. this._clearFn.call(window, this._id);
  10977. };
  10978. // Does not start the time, just sets up the members needed.
  10979. exports.enroll = function(item, msecs) {
  10980. clearTimeout(item._idleTimeoutId);
  10981. item._idleTimeout = msecs;
  10982. };
  10983. exports.unenroll = function(item) {
  10984. clearTimeout(item._idleTimeoutId);
  10985. item._idleTimeout = -1;
  10986. };
  10987. exports._unrefActive = exports.active = function(item) {
  10988. clearTimeout(item._idleTimeoutId);
  10989. var msecs = item._idleTimeout;
  10990. if (msecs >= 0) {
  10991. item._idleTimeoutId = setTimeout(function onTimeout() {
  10992. if (item._onTimeout)
  10993. item._onTimeout();
  10994. }, msecs);
  10995. }
  10996. };
  10997. // That's not how node.js implements it but the exposed api is the same.
  10998. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  10999. var id = nextImmediateId++;
  11000. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  11001. immediateIds[id] = true;
  11002. nextTick(function onNextTick() {
  11003. if (immediateIds[id]) {
  11004. // fn.call() is faster so we optimize for the common use-case
  11005. // @see http://jsperf.com/call-apply-segu
  11006. if (args) {
  11007. fn.apply(null, args);
  11008. } else {
  11009. fn.call(null);
  11010. }
  11011. // Prevent ids from leaking
  11012. exports.clearImmediate(id);
  11013. }
  11014. });
  11015. return id;
  11016. };
  11017. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  11018. delete immediateIds[id];
  11019. };
  11020. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  11021. },{"process/browser.js":92,"timers":112}],113:[function(require,module,exports){
  11022. // Copyright Joyent, Inc. and other Node contributors.
  11023. //
  11024. // Permission is hereby granted, free of charge, to any person obtaining a
  11025. // copy of this software and associated documentation files (the
  11026. // "Software"), to deal in the Software without restriction, including
  11027. // without limitation the rights to use, copy, modify, merge, publish,
  11028. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11029. // persons to whom the Software is furnished to do so, subject to the
  11030. // following conditions:
  11031. //
  11032. // The above copyright notice and this permission notice shall be included
  11033. // in all copies or substantial portions of the Software.
  11034. //
  11035. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11036. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11037. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11038. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11039. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11040. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11041. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11042. 'use strict';
  11043. var punycode = require('punycode');
  11044. var util = require('./util');
  11045. exports.parse = urlParse;
  11046. exports.resolve = urlResolve;
  11047. exports.resolveObject = urlResolveObject;
  11048. exports.format = urlFormat;
  11049. exports.Url = Url;
  11050. function Url() {
  11051. this.protocol = null;
  11052. this.slashes = null;
  11053. this.auth = null;
  11054. this.host = null;
  11055. this.port = null;
  11056. this.hostname = null;
  11057. this.hash = null;
  11058. this.search = null;
  11059. this.query = null;
  11060. this.pathname = null;
  11061. this.path = null;
  11062. this.href = null;
  11063. }
  11064. // Reference: RFC 3986, RFC 1808, RFC 2396
  11065. // define these here so at least they only have to be
  11066. // compiled once on the first module load.
  11067. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  11068. portPattern = /:[0-9]*$/,
  11069. // Special case for a simple path URL
  11070. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  11071. // RFC 2396: characters reserved for delimiting URLs.
  11072. // We actually just auto-escape these.
  11073. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  11074. // RFC 2396: characters not allowed for various reasons.
  11075. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  11076. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  11077. autoEscape = ['\''].concat(unwise),
  11078. // Characters that are never ever allowed in a hostname.
  11079. // Note that any invalid chars are also handled, but these
  11080. // are the ones that are *expected* to be seen, so we fast-path
  11081. // them.
  11082. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  11083. hostEndingChars = ['/', '?', '#'],
  11084. hostnameMaxLen = 255,
  11085. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  11086. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  11087. // protocols that can allow "unsafe" and "unwise" chars.
  11088. unsafeProtocol = {
  11089. 'javascript': true,
  11090. 'javascript:': true
  11091. },
  11092. // protocols that never have a hostname.
  11093. hostlessProtocol = {
  11094. 'javascript': true,
  11095. 'javascript:': true
  11096. },
  11097. // protocols that always contain a // bit.
  11098. slashedProtocol = {
  11099. 'http': true,
  11100. 'https': true,
  11101. 'ftp': true,
  11102. 'gopher': true,
  11103. 'file': true,
  11104. 'http:': true,
  11105. 'https:': true,
  11106. 'ftp:': true,
  11107. 'gopher:': true,
  11108. 'file:': true
  11109. },
  11110. querystring = require('querystring');
  11111. function urlParse(url, parseQueryString, slashesDenoteHost) {
  11112. if (url && util.isObject(url) && url instanceof Url) return url;
  11113. var u = new Url;
  11114. u.parse(url, parseQueryString, slashesDenoteHost);
  11115. return u;
  11116. }
  11117. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  11118. if (!util.isString(url)) {
  11119. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  11120. }
  11121. // Copy chrome, IE, opera backslash-handling behavior.
  11122. // Back slashes before the query string get converted to forward slashes
  11123. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  11124. var queryIndex = url.indexOf('?'),
  11125. splitter =
  11126. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  11127. uSplit = url.split(splitter),
  11128. slashRegex = /\\/g;
  11129. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  11130. url = uSplit.join(splitter);
  11131. var rest = url;
  11132. // trim before proceeding.
  11133. // This is to support parse stuff like " http://foo.com \n"
  11134. rest = rest.trim();
  11135. if (!slashesDenoteHost && url.split('#').length === 1) {
  11136. // Try fast path regexp
  11137. var simplePath = simplePathPattern.exec(rest);
  11138. if (simplePath) {
  11139. this.path = rest;
  11140. this.href = rest;
  11141. this.pathname = simplePath[1];
  11142. if (simplePath[2]) {
  11143. this.search = simplePath[2];
  11144. if (parseQueryString) {
  11145. this.query = querystring.parse(this.search.substr(1));
  11146. } else {
  11147. this.query = this.search.substr(1);
  11148. }
  11149. } else if (parseQueryString) {
  11150. this.search = '';
  11151. this.query = {};
  11152. }
  11153. return this;
  11154. }
  11155. }
  11156. var proto = protocolPattern.exec(rest);
  11157. if (proto) {
  11158. proto = proto[0];
  11159. var lowerProto = proto.toLowerCase();
  11160. this.protocol = lowerProto;
  11161. rest = rest.substr(proto.length);
  11162. }
  11163. // figure out if it's got a host
  11164. // user@server is *always* interpreted as a hostname, and url
  11165. // resolution will treat //foo/bar as host=foo,path=bar because that's
  11166. // how the browser resolves relative URLs.
  11167. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  11168. var slashes = rest.substr(0, 2) === '//';
  11169. if (slashes && !(proto && hostlessProtocol[proto])) {
  11170. rest = rest.substr(2);
  11171. this.slashes = true;
  11172. }
  11173. }
  11174. if (!hostlessProtocol[proto] &&
  11175. (slashes || (proto && !slashedProtocol[proto]))) {
  11176. // there's a hostname.
  11177. // the first instance of /, ?, ;, or # ends the host.
  11178. //
  11179. // If there is an @ in the hostname, then non-host chars *are* allowed
  11180. // to the left of the last @ sign, unless some host-ending character
  11181. // comes *before* the @-sign.
  11182. // URLs are obnoxious.
  11183. //
  11184. // ex:
  11185. // http://a@b@c/ => user:a@b host:c
  11186. // http://a@b?@c => user:a host:c path:/?@c
  11187. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  11188. // Review our test case against browsers more comprehensively.
  11189. // find the first instance of any hostEndingChars
  11190. var hostEnd = -1;
  11191. for (var i = 0; i < hostEndingChars.length; i++) {
  11192. var hec = rest.indexOf(hostEndingChars[i]);
  11193. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  11194. hostEnd = hec;
  11195. }
  11196. // at this point, either we have an explicit point where the
  11197. // auth portion cannot go past, or the last @ char is the decider.
  11198. var auth, atSign;
  11199. if (hostEnd === -1) {
  11200. // atSign can be anywhere.
  11201. atSign = rest.lastIndexOf('@');
  11202. } else {
  11203. // atSign must be in auth portion.
  11204. // http://a@b/c@d => host:b auth:a path:/c@d
  11205. atSign = rest.lastIndexOf('@', hostEnd);
  11206. }
  11207. // Now we have a portion which is definitely the auth.
  11208. // Pull that off.
  11209. if (atSign !== -1) {
  11210. auth = rest.slice(0, atSign);
  11211. rest = rest.slice(atSign + 1);
  11212. this.auth = decodeURIComponent(auth);
  11213. }
  11214. // the host is the remaining to the left of the first non-host char
  11215. hostEnd = -1;
  11216. for (var i = 0; i < nonHostChars.length; i++) {
  11217. var hec = rest.indexOf(nonHostChars[i]);
  11218. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  11219. hostEnd = hec;
  11220. }
  11221. // if we still have not hit it, then the entire thing is a host.
  11222. if (hostEnd === -1)
  11223. hostEnd = rest.length;
  11224. this.host = rest.slice(0, hostEnd);
  11225. rest = rest.slice(hostEnd);
  11226. // pull out port.
  11227. this.parseHost();
  11228. // we've indicated that there is a hostname,
  11229. // so even if it's empty, it has to be present.
  11230. this.hostname = this.hostname || '';
  11231. // if hostname begins with [ and ends with ]
  11232. // assume that it's an IPv6 address.
  11233. var ipv6Hostname = this.hostname[0] === '[' &&
  11234. this.hostname[this.hostname.length - 1] === ']';
  11235. // validate a little.
  11236. if (!ipv6Hostname) {
  11237. var hostparts = this.hostname.split(/\./);
  11238. for (var i = 0, l = hostparts.length; i < l; i++) {
  11239. var part = hostparts[i];
  11240. if (!part) continue;
  11241. if (!part.match(hostnamePartPattern)) {
  11242. var newpart = '';
  11243. for (var j = 0, k = part.length; j < k; j++) {
  11244. if (part.charCodeAt(j) > 127) {
  11245. // we replace non-ASCII char with a temporary placeholder
  11246. // we need this to make sure size of hostname is not
  11247. // broken by replacing non-ASCII by nothing
  11248. newpart += 'x';
  11249. } else {
  11250. newpart += part[j];
  11251. }
  11252. }
  11253. // we test again with ASCII char only
  11254. if (!newpart.match(hostnamePartPattern)) {
  11255. var validParts = hostparts.slice(0, i);
  11256. var notHost = hostparts.slice(i + 1);
  11257. var bit = part.match(hostnamePartStart);
  11258. if (bit) {
  11259. validParts.push(bit[1]);
  11260. notHost.unshift(bit[2]);
  11261. }
  11262. if (notHost.length) {
  11263. rest = '/' + notHost.join('.') + rest;
  11264. }
  11265. this.hostname = validParts.join('.');
  11266. break;
  11267. }
  11268. }
  11269. }
  11270. }
  11271. if (this.hostname.length > hostnameMaxLen) {
  11272. this.hostname = '';
  11273. } else {
  11274. // hostnames are always lower case.
  11275. this.hostname = this.hostname.toLowerCase();
  11276. }
  11277. if (!ipv6Hostname) {
  11278. // IDNA Support: Returns a punycoded representation of "domain".
  11279. // It only converts parts of the domain name that
  11280. // have non-ASCII characters, i.e. it doesn't matter if
  11281. // you call it with a domain that already is ASCII-only.
  11282. this.hostname = punycode.toASCII(this.hostname);
  11283. }
  11284. var p = this.port ? ':' + this.port : '';
  11285. var h = this.hostname || '';
  11286. this.host = h + p;
  11287. this.href += this.host;
  11288. // strip [ and ] from the hostname
  11289. // the host field still retains them, though
  11290. if (ipv6Hostname) {
  11291. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  11292. if (rest[0] !== '/') {
  11293. rest = '/' + rest;
  11294. }
  11295. }
  11296. }
  11297. // now rest is set to the post-host stuff.
  11298. // chop off any delim chars.
  11299. if (!unsafeProtocol[lowerProto]) {
  11300. // First, make 100% sure that any "autoEscape" chars get
  11301. // escaped, even if encodeURIComponent doesn't think they
  11302. // need to be.
  11303. for (var i = 0, l = autoEscape.length; i < l; i++) {
  11304. var ae = autoEscape[i];
  11305. if (rest.indexOf(ae) === -1)
  11306. continue;
  11307. var esc = encodeURIComponent(ae);
  11308. if (esc === ae) {
  11309. esc = escape(ae);
  11310. }
  11311. rest = rest.split(ae).join(esc);
  11312. }
  11313. }
  11314. // chop off from the tail first.
  11315. var hash = rest.indexOf('#');
  11316. if (hash !== -1) {
  11317. // got a fragment string.
  11318. this.hash = rest.substr(hash);
  11319. rest = rest.slice(0, hash);
  11320. }
  11321. var qm = rest.indexOf('?');
  11322. if (qm !== -1) {
  11323. this.search = rest.substr(qm);
  11324. this.query = rest.substr(qm + 1);
  11325. if (parseQueryString) {
  11326. this.query = querystring.parse(this.query);
  11327. }
  11328. rest = rest.slice(0, qm);
  11329. } else if (parseQueryString) {
  11330. // no query string, but parseQueryString still requested
  11331. this.search = '';
  11332. this.query = {};
  11333. }
  11334. if (rest) this.pathname = rest;
  11335. if (slashedProtocol[lowerProto] &&
  11336. this.hostname && !this.pathname) {
  11337. this.pathname = '/';
  11338. }
  11339. //to support http.request
  11340. if (this.pathname || this.search) {
  11341. var p = this.pathname || '';
  11342. var s = this.search || '';
  11343. this.path = p + s;
  11344. }
  11345. // finally, reconstruct the href based on what has been validated.
  11346. this.href = this.format();
  11347. return this;
  11348. };
  11349. // format a parsed object into a url string
  11350. function urlFormat(obj) {
  11351. // ensure it's an object, and not a string url.
  11352. // If it's an obj, this is a no-op.
  11353. // this way, you can call url_format() on strings
  11354. // to clean up potentially wonky urls.
  11355. if (util.isString(obj)) obj = urlParse(obj);
  11356. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  11357. return obj.format();
  11358. }
  11359. Url.prototype.format = function() {
  11360. var auth = this.auth || '';
  11361. if (auth) {
  11362. auth = encodeURIComponent(auth);
  11363. auth = auth.replace(/%3A/i, ':');
  11364. auth += '@';
  11365. }
  11366. var protocol = this.protocol || '',
  11367. pathname = this.pathname || '',
  11368. hash = this.hash || '',
  11369. host = false,
  11370. query = '';
  11371. if (this.host) {
  11372. host = auth + this.host;
  11373. } else if (this.hostname) {
  11374. host = auth + (this.hostname.indexOf(':') === -1 ?
  11375. this.hostname :
  11376. '[' + this.hostname + ']');
  11377. if (this.port) {
  11378. host += ':' + this.port;
  11379. }
  11380. }
  11381. if (this.query &&
  11382. util.isObject(this.query) &&
  11383. Object.keys(this.query).length) {
  11384. query = querystring.stringify(this.query);
  11385. }
  11386. var search = this.search || (query && ('?' + query)) || '';
  11387. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  11388. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  11389. // unless they had them to begin with.
  11390. if (this.slashes ||
  11391. (!protocol || slashedProtocol[protocol]) && host !== false) {
  11392. host = '//' + (host || '');
  11393. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  11394. } else if (!host) {
  11395. host = '';
  11396. }
  11397. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  11398. if (search && search.charAt(0) !== '?') search = '?' + search;
  11399. pathname = pathname.replace(/[?#]/g, function(match) {
  11400. return encodeURIComponent(match);
  11401. });
  11402. search = search.replace('#', '%23');
  11403. return protocol + host + pathname + search + hash;
  11404. };
  11405. function urlResolve(source, relative) {
  11406. return urlParse(source, false, true).resolve(relative);
  11407. }
  11408. Url.prototype.resolve = function(relative) {
  11409. return this.resolveObject(urlParse(relative, false, true)).format();
  11410. };
  11411. function urlResolveObject(source, relative) {
  11412. if (!source) return relative;
  11413. return urlParse(source, false, true).resolveObject(relative);
  11414. }
  11415. Url.prototype.resolveObject = function(relative) {
  11416. if (util.isString(relative)) {
  11417. var rel = new Url();
  11418. rel.parse(relative, false, true);
  11419. relative = rel;
  11420. }
  11421. var result = new Url();
  11422. var tkeys = Object.keys(this);
  11423. for (var tk = 0; tk < tkeys.length; tk++) {
  11424. var tkey = tkeys[tk];
  11425. result[tkey] = this[tkey];
  11426. }
  11427. // hash is always overridden, no matter what.
  11428. // even href="" will remove it.
  11429. result.hash = relative.hash;
  11430. // if the relative url is empty, then there's nothing left to do here.
  11431. if (relative.href === '') {
  11432. result.href = result.format();
  11433. return result;
  11434. }
  11435. // hrefs like //foo/bar always cut to the protocol.
  11436. if (relative.slashes && !relative.protocol) {
  11437. // take everything except the protocol from relative
  11438. var rkeys = Object.keys(relative);
  11439. for (var rk = 0; rk < rkeys.length; rk++) {
  11440. var rkey = rkeys[rk];
  11441. if (rkey !== 'protocol')
  11442. result[rkey] = relative[rkey];
  11443. }
  11444. //urlParse appends trailing / to urls like http://www.example.com
  11445. if (slashedProtocol[result.protocol] &&
  11446. result.hostname && !result.pathname) {
  11447. result.path = result.pathname = '/';
  11448. }
  11449. result.href = result.format();
  11450. return result;
  11451. }
  11452. if (relative.protocol && relative.protocol !== result.protocol) {
  11453. // if it's a known url protocol, then changing
  11454. // the protocol does weird things
  11455. // first, if it's not file:, then we MUST have a host,
  11456. // and if there was a path
  11457. // to begin with, then we MUST have a path.
  11458. // if it is file:, then the host is dropped,
  11459. // because that's known to be hostless.
  11460. // anything else is assumed to be absolute.
  11461. if (!slashedProtocol[relative.protocol]) {
  11462. var keys = Object.keys(relative);
  11463. for (var v = 0; v < keys.length; v++) {
  11464. var k = keys[v];
  11465. result[k] = relative[k];
  11466. }
  11467. result.href = result.format();
  11468. return result;
  11469. }
  11470. result.protocol = relative.protocol;
  11471. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  11472. var relPath = (relative.pathname || '').split('/');
  11473. while (relPath.length && !(relative.host = relPath.shift()));
  11474. if (!relative.host) relative.host = '';
  11475. if (!relative.hostname) relative.hostname = '';
  11476. if (relPath[0] !== '') relPath.unshift('');
  11477. if (relPath.length < 2) relPath.unshift('');
  11478. result.pathname = relPath.join('/');
  11479. } else {
  11480. result.pathname = relative.pathname;
  11481. }
  11482. result.search = relative.search;
  11483. result.query = relative.query;
  11484. result.host = relative.host || '';
  11485. result.auth = relative.auth;
  11486. result.hostname = relative.hostname || relative.host;
  11487. result.port = relative.port;
  11488. // to support http.request
  11489. if (result.pathname || result.search) {
  11490. var p = result.pathname || '';
  11491. var s = result.search || '';
  11492. result.path = p + s;
  11493. }
  11494. result.slashes = result.slashes || relative.slashes;
  11495. result.href = result.format();
  11496. return result;
  11497. }
  11498. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  11499. isRelAbs = (
  11500. relative.host ||
  11501. relative.pathname && relative.pathname.charAt(0) === '/'
  11502. ),
  11503. mustEndAbs = (isRelAbs || isSourceAbs ||
  11504. (result.host && relative.pathname)),
  11505. removeAllDots = mustEndAbs,
  11506. srcPath = result.pathname && result.pathname.split('/') || [],
  11507. relPath = relative.pathname && relative.pathname.split('/') || [],
  11508. psychotic = result.protocol && !slashedProtocol[result.protocol];
  11509. // if the url is a non-slashed url, then relative
  11510. // links like ../.. should be able
  11511. // to crawl up to the hostname, as well. This is strange.
  11512. // result.protocol has already been set by now.
  11513. // Later on, put the first path part into the host field.
  11514. if (psychotic) {
  11515. result.hostname = '';
  11516. result.port = null;
  11517. if (result.host) {
  11518. if (srcPath[0] === '') srcPath[0] = result.host;
  11519. else srcPath.unshift(result.host);
  11520. }
  11521. result.host = '';
  11522. if (relative.protocol) {
  11523. relative.hostname = null;
  11524. relative.port = null;
  11525. if (relative.host) {
  11526. if (relPath[0] === '') relPath[0] = relative.host;
  11527. else relPath.unshift(relative.host);
  11528. }
  11529. relative.host = null;
  11530. }
  11531. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  11532. }
  11533. if (isRelAbs) {
  11534. // it's absolute.
  11535. result.host = (relative.host || relative.host === '') ?
  11536. relative.host : result.host;
  11537. result.hostname = (relative.hostname || relative.hostname === '') ?
  11538. relative.hostname : result.hostname;
  11539. result.search = relative.search;
  11540. result.query = relative.query;
  11541. srcPath = relPath;
  11542. // fall through to the dot-handling below.
  11543. } else if (relPath.length) {
  11544. // it's relative
  11545. // throw away the existing file, and take the new path instead.
  11546. if (!srcPath) srcPath = [];
  11547. srcPath.pop();
  11548. srcPath = srcPath.concat(relPath);
  11549. result.search = relative.search;
  11550. result.query = relative.query;
  11551. } else if (!util.isNullOrUndefined(relative.search)) {
  11552. // just pull out the search.
  11553. // like href='?foo'.
  11554. // Put this after the other two cases because it simplifies the booleans
  11555. if (psychotic) {
  11556. result.hostname = result.host = srcPath.shift();
  11557. //occationaly the auth can get stuck only in host
  11558. //this especially happens in cases like
  11559. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  11560. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  11561. result.host.split('@') : false;
  11562. if (authInHost) {
  11563. result.auth = authInHost.shift();
  11564. result.host = result.hostname = authInHost.shift();
  11565. }
  11566. }
  11567. result.search = relative.search;
  11568. result.query = relative.query;
  11569. //to support http.request
  11570. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  11571. result.path = (result.pathname ? result.pathname : '') +
  11572. (result.search ? result.search : '');
  11573. }
  11574. result.href = result.format();
  11575. return result;
  11576. }
  11577. if (!srcPath.length) {
  11578. // no path at all. easy.
  11579. // we've already handled the other stuff above.
  11580. result.pathname = null;
  11581. //to support http.request
  11582. if (result.search) {
  11583. result.path = '/' + result.search;
  11584. } else {
  11585. result.path = null;
  11586. }
  11587. result.href = result.format();
  11588. return result;
  11589. }
  11590. // if a url ENDs in . or .., then it must get a trailing slash.
  11591. // however, if it ends in anything else non-slashy,
  11592. // then it must NOT get a trailing slash.
  11593. var last = srcPath.slice(-1)[0];
  11594. var hasTrailingSlash = (
  11595. (result.host || relative.host || srcPath.length > 1) &&
  11596. (last === '.' || last === '..') || last === '');
  11597. // strip single dots, resolve double dots to parent dir
  11598. // if the path tries to go above the root, `up` ends up > 0
  11599. var up = 0;
  11600. for (var i = srcPath.length; i >= 0; i--) {
  11601. last = srcPath[i];
  11602. if (last === '.') {
  11603. srcPath.splice(i, 1);
  11604. } else if (last === '..') {
  11605. srcPath.splice(i, 1);
  11606. up++;
  11607. } else if (up) {
  11608. srcPath.splice(i, 1);
  11609. up--;
  11610. }
  11611. }
  11612. // if the path is allowed to go above the root, restore leading ..s
  11613. if (!mustEndAbs && !removeAllDots) {
  11614. for (; up--; up) {
  11615. srcPath.unshift('..');
  11616. }
  11617. }
  11618. if (mustEndAbs && srcPath[0] !== '' &&
  11619. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  11620. srcPath.unshift('');
  11621. }
  11622. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  11623. srcPath.push('');
  11624. }
  11625. var isAbsolute = srcPath[0] === '' ||
  11626. (srcPath[0] && srcPath[0].charAt(0) === '/');
  11627. // put the host back
  11628. if (psychotic) {
  11629. result.hostname = result.host = isAbsolute ? '' :
  11630. srcPath.length ? srcPath.shift() : '';
  11631. //occationaly the auth can get stuck only in host
  11632. //this especially happens in cases like
  11633. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  11634. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  11635. result.host.split('@') : false;
  11636. if (authInHost) {
  11637. result.auth = authInHost.shift();
  11638. result.host = result.hostname = authInHost.shift();
  11639. }
  11640. }
  11641. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  11642. if (mustEndAbs && !isAbsolute) {
  11643. srcPath.unshift('');
  11644. }
  11645. if (!srcPath.length) {
  11646. result.pathname = null;
  11647. result.path = null;
  11648. } else {
  11649. result.pathname = srcPath.join('/');
  11650. }
  11651. //to support request.http
  11652. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  11653. result.path = (result.pathname ? result.pathname : '') +
  11654. (result.search ? result.search : '');
  11655. }
  11656. result.auth = relative.auth || result.auth;
  11657. result.slashes = result.slashes || relative.slashes;
  11658. result.href = result.format();
  11659. return result;
  11660. };
  11661. Url.prototype.parseHost = function() {
  11662. var host = this.host;
  11663. var port = portPattern.exec(host);
  11664. if (port) {
  11665. port = port[0];
  11666. if (port !== ':') {
  11667. this.port = port.substr(1);
  11668. }
  11669. host = host.substr(0, host.length - port.length);
  11670. }
  11671. if (host) this.hostname = host;
  11672. };
  11673. },{"./util":114,"punycode":93,"querystring":96}],114:[function(require,module,exports){
  11674. 'use strict';
  11675. module.exports = {
  11676. isString: function(arg) {
  11677. return typeof(arg) === 'string';
  11678. },
  11679. isObject: function(arg) {
  11680. return typeof(arg) === 'object' && arg !== null;
  11681. },
  11682. isNull: function(arg) {
  11683. return arg === null;
  11684. },
  11685. isNullOrUndefined: function(arg) {
  11686. return arg == null;
  11687. }
  11688. };
  11689. },{}],115:[function(require,module,exports){
  11690. (function (global){
  11691. /**
  11692. * Module exports.
  11693. */
  11694. module.exports = deprecate;
  11695. /**
  11696. * Mark that a method should not be used.
  11697. * Returns a modified function which warns once by default.
  11698. *
  11699. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  11700. *
  11701. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  11702. * will throw an Error when invoked.
  11703. *
  11704. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  11705. * will invoke `console.trace()` instead of `console.error()`.
  11706. *
  11707. * @param {Function} fn - the function to deprecate
  11708. * @param {String} msg - the string to print to the console when `fn` is invoked
  11709. * @returns {Function} a new "deprecated" version of `fn`
  11710. * @api public
  11711. */
  11712. function deprecate (fn, msg) {
  11713. if (config('noDeprecation')) {
  11714. return fn;
  11715. }
  11716. var warned = false;
  11717. function deprecated() {
  11718. if (!warned) {
  11719. if (config('throwDeprecation')) {
  11720. throw new Error(msg);
  11721. } else if (config('traceDeprecation')) {
  11722. console.trace(msg);
  11723. } else {
  11724. console.warn(msg);
  11725. }
  11726. warned = true;
  11727. }
  11728. return fn.apply(this, arguments);
  11729. }
  11730. return deprecated;
  11731. }
  11732. /**
  11733. * Checks `localStorage` for boolean values for the given `name`.
  11734. *
  11735. * @param {String} name
  11736. * @returns {Boolean}
  11737. * @api private
  11738. */
  11739. function config (name) {
  11740. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  11741. try {
  11742. if (!global.localStorage) return false;
  11743. } catch (_) {
  11744. return false;
  11745. }
  11746. var val = global.localStorage[name];
  11747. if (null == val) return false;
  11748. return String(val).toLowerCase() === 'true';
  11749. }
  11750. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11751. },{}],116:[function(require,module,exports){
  11752. module.exports = function isBuffer(arg) {
  11753. return arg && typeof arg === 'object'
  11754. && typeof arg.copy === 'function'
  11755. && typeof arg.fill === 'function'
  11756. && typeof arg.readUInt8 === 'function';
  11757. }
  11758. },{}],117:[function(require,module,exports){
  11759. (function (process,global){
  11760. // Copyright Joyent, Inc. and other Node contributors.
  11761. //
  11762. // Permission is hereby granted, free of charge, to any person obtaining a
  11763. // copy of this software and associated documentation files (the
  11764. // "Software"), to deal in the Software without restriction, including
  11765. // without limitation the rights to use, copy, modify, merge, publish,
  11766. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11767. // persons to whom the Software is furnished to do so, subject to the
  11768. // following conditions:
  11769. //
  11770. // The above copyright notice and this permission notice shall be included
  11771. // in all copies or substantial portions of the Software.
  11772. //
  11773. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11774. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11775. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11776. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11777. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11778. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11779. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11780. var formatRegExp = /%[sdj%]/g;
  11781. exports.format = function(f) {
  11782. if (!isString(f)) {
  11783. var objects = [];
  11784. for (var i = 0; i < arguments.length; i++) {
  11785. objects.push(inspect(arguments[i]));
  11786. }
  11787. return objects.join(' ');
  11788. }
  11789. var i = 1;
  11790. var args = arguments;
  11791. var len = args.length;
  11792. var str = String(f).replace(formatRegExp, function(x) {
  11793. if (x === '%%') return '%';
  11794. if (i >= len) return x;
  11795. switch (x) {
  11796. case '%s': return String(args[i++]);
  11797. case '%d': return Number(args[i++]);
  11798. case '%j':
  11799. try {
  11800. return JSON.stringify(args[i++]);
  11801. } catch (_) {
  11802. return '[Circular]';
  11803. }
  11804. default:
  11805. return x;
  11806. }
  11807. });
  11808. for (var x = args[i]; i < len; x = args[++i]) {
  11809. if (isNull(x) || !isObject(x)) {
  11810. str += ' ' + x;
  11811. } else {
  11812. str += ' ' + inspect(x);
  11813. }
  11814. }
  11815. return str;
  11816. };
  11817. // Mark that a method should not be used.
  11818. // Returns a modified function which warns once by default.
  11819. // If --no-deprecation is set, then it is a no-op.
  11820. exports.deprecate = function(fn, msg) {
  11821. // Allow for deprecating things in the process of starting up.
  11822. if (isUndefined(global.process)) {
  11823. return function() {
  11824. return exports.deprecate(fn, msg).apply(this, arguments);
  11825. };
  11826. }
  11827. if (process.noDeprecation === true) {
  11828. return fn;
  11829. }
  11830. var warned = false;
  11831. function deprecated() {
  11832. if (!warned) {
  11833. if (process.throwDeprecation) {
  11834. throw new Error(msg);
  11835. } else if (process.traceDeprecation) {
  11836. console.trace(msg);
  11837. } else {
  11838. console.error(msg);
  11839. }
  11840. warned = true;
  11841. }
  11842. return fn.apply(this, arguments);
  11843. }
  11844. return deprecated;
  11845. };
  11846. var debugs = {};
  11847. var debugEnviron;
  11848. exports.debuglog = function(set) {
  11849. if (isUndefined(debugEnviron))
  11850. debugEnviron = process.env.NODE_DEBUG || '';
  11851. set = set.toUpperCase();
  11852. if (!debugs[set]) {
  11853. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  11854. var pid = process.pid;
  11855. debugs[set] = function() {
  11856. var msg = exports.format.apply(exports, arguments);
  11857. console.error('%s %d: %s', set, pid, msg);
  11858. };
  11859. } else {
  11860. debugs[set] = function() {};
  11861. }
  11862. }
  11863. return debugs[set];
  11864. };
  11865. /**
  11866. * Echos the value of a value. Trys to print the value out
  11867. * in the best way possible given the different types.
  11868. *
  11869. * @param {Object} obj The object to print out.
  11870. * @param {Object} opts Optional options object that alters the output.
  11871. */
  11872. /* legacy: obj, showHidden, depth, colors*/
  11873. function inspect(obj, opts) {
  11874. // default options
  11875. var ctx = {
  11876. seen: [],
  11877. stylize: stylizeNoColor
  11878. };
  11879. // legacy...
  11880. if (arguments.length >= 3) ctx.depth = arguments[2];
  11881. if (arguments.length >= 4) ctx.colors = arguments[3];
  11882. if (isBoolean(opts)) {
  11883. // legacy...
  11884. ctx.showHidden = opts;
  11885. } else if (opts) {
  11886. // got an "options" object
  11887. exports._extend(ctx, opts);
  11888. }
  11889. // set default options
  11890. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  11891. if (isUndefined(ctx.depth)) ctx.depth = 2;
  11892. if (isUndefined(ctx.colors)) ctx.colors = false;
  11893. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  11894. if (ctx.colors) ctx.stylize = stylizeWithColor;
  11895. return formatValue(ctx, obj, ctx.depth);
  11896. }
  11897. exports.inspect = inspect;
  11898. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  11899. inspect.colors = {
  11900. 'bold' : [1, 22],
  11901. 'italic' : [3, 23],
  11902. 'underline' : [4, 24],
  11903. 'inverse' : [7, 27],
  11904. 'white' : [37, 39],
  11905. 'grey' : [90, 39],
  11906. 'black' : [30, 39],
  11907. 'blue' : [34, 39],
  11908. 'cyan' : [36, 39],
  11909. 'green' : [32, 39],
  11910. 'magenta' : [35, 39],
  11911. 'red' : [31, 39],
  11912. 'yellow' : [33, 39]
  11913. };
  11914. // Don't use 'blue' not visible on cmd.exe
  11915. inspect.styles = {
  11916. 'special': 'cyan',
  11917. 'number': 'yellow',
  11918. 'boolean': 'yellow',
  11919. 'undefined': 'grey',
  11920. 'null': 'bold',
  11921. 'string': 'green',
  11922. 'date': 'magenta',
  11923. // "name": intentionally not styling
  11924. 'regexp': 'red'
  11925. };
  11926. function stylizeWithColor(str, styleType) {
  11927. var style = inspect.styles[styleType];
  11928. if (style) {
  11929. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  11930. '\u001b[' + inspect.colors[style][1] + 'm';
  11931. } else {
  11932. return str;
  11933. }
  11934. }
  11935. function stylizeNoColor(str, styleType) {
  11936. return str;
  11937. }
  11938. function arrayToHash(array) {
  11939. var hash = {};
  11940. array.forEach(function(val, idx) {
  11941. hash[val] = true;
  11942. });
  11943. return hash;
  11944. }
  11945. function formatValue(ctx, value, recurseTimes) {
  11946. // Provide a hook for user-specified inspect functions.
  11947. // Check that value is an object with an inspect function on it
  11948. if (ctx.customInspect &&
  11949. value &&
  11950. isFunction(value.inspect) &&
  11951. // Filter out the util module, it's inspect function is special
  11952. value.inspect !== exports.inspect &&
  11953. // Also filter out any prototype objects using the circular check.
  11954. !(value.constructor && value.constructor.prototype === value)) {
  11955. var ret = value.inspect(recurseTimes, ctx);
  11956. if (!isString(ret)) {
  11957. ret = formatValue(ctx, ret, recurseTimes);
  11958. }
  11959. return ret;
  11960. }
  11961. // Primitive types cannot have properties
  11962. var primitive = formatPrimitive(ctx, value);
  11963. if (primitive) {
  11964. return primitive;
  11965. }
  11966. // Look up the keys of the object.
  11967. var keys = Object.keys(value);
  11968. var visibleKeys = arrayToHash(keys);
  11969. if (ctx.showHidden) {
  11970. keys = Object.getOwnPropertyNames(value);
  11971. }
  11972. // IE doesn't make error fields non-enumerable
  11973. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  11974. if (isError(value)
  11975. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  11976. return formatError(value);
  11977. }
  11978. // Some type of object without properties can be shortcutted.
  11979. if (keys.length === 0) {
  11980. if (isFunction(value)) {
  11981. var name = value.name ? ': ' + value.name : '';
  11982. return ctx.stylize('[Function' + name + ']', 'special');
  11983. }
  11984. if (isRegExp(value)) {
  11985. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  11986. }
  11987. if (isDate(value)) {
  11988. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  11989. }
  11990. if (isError(value)) {
  11991. return formatError(value);
  11992. }
  11993. }
  11994. var base = '', array = false, braces = ['{', '}'];
  11995. // Make Array say that they are Array
  11996. if (isArray(value)) {
  11997. array = true;
  11998. braces = ['[', ']'];
  11999. }
  12000. // Make functions say that they are functions
  12001. if (isFunction(value)) {
  12002. var n = value.name ? ': ' + value.name : '';
  12003. base = ' [Function' + n + ']';
  12004. }
  12005. // Make RegExps say that they are RegExps
  12006. if (isRegExp(value)) {
  12007. base = ' ' + RegExp.prototype.toString.call(value);
  12008. }
  12009. // Make dates with properties first say the date
  12010. if (isDate(value)) {
  12011. base = ' ' + Date.prototype.toUTCString.call(value);
  12012. }
  12013. // Make error with message first say the error
  12014. if (isError(value)) {
  12015. base = ' ' + formatError(value);
  12016. }
  12017. if (keys.length === 0 && (!array || value.length == 0)) {
  12018. return braces[0] + base + braces[1];
  12019. }
  12020. if (recurseTimes < 0) {
  12021. if (isRegExp(value)) {
  12022. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12023. } else {
  12024. return ctx.stylize('[Object]', 'special');
  12025. }
  12026. }
  12027. ctx.seen.push(value);
  12028. var output;
  12029. if (array) {
  12030. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  12031. } else {
  12032. output = keys.map(function(key) {
  12033. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  12034. });
  12035. }
  12036. ctx.seen.pop();
  12037. return reduceToSingleString(output, base, braces);
  12038. }
  12039. function formatPrimitive(ctx, value) {
  12040. if (isUndefined(value))
  12041. return ctx.stylize('undefined', 'undefined');
  12042. if (isString(value)) {
  12043. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  12044. .replace(/'/g, "\\'")
  12045. .replace(/\\"/g, '"') + '\'';
  12046. return ctx.stylize(simple, 'string');
  12047. }
  12048. if (isNumber(value))
  12049. return ctx.stylize('' + value, 'number');
  12050. if (isBoolean(value))
  12051. return ctx.stylize('' + value, 'boolean');
  12052. // For some reason typeof null is "object", so special case here.
  12053. if (isNull(value))
  12054. return ctx.stylize('null', 'null');
  12055. }
  12056. function formatError(value) {
  12057. return '[' + Error.prototype.toString.call(value) + ']';
  12058. }
  12059. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  12060. var output = [];
  12061. for (var i = 0, l = value.length; i < l; ++i) {
  12062. if (hasOwnProperty(value, String(i))) {
  12063. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12064. String(i), true));
  12065. } else {
  12066. output.push('');
  12067. }
  12068. }
  12069. keys.forEach(function(key) {
  12070. if (!key.match(/^\d+$/)) {
  12071. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12072. key, true));
  12073. }
  12074. });
  12075. return output;
  12076. }
  12077. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  12078. var name, str, desc;
  12079. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  12080. if (desc.get) {
  12081. if (desc.set) {
  12082. str = ctx.stylize('[Getter/Setter]', 'special');
  12083. } else {
  12084. str = ctx.stylize('[Getter]', 'special');
  12085. }
  12086. } else {
  12087. if (desc.set) {
  12088. str = ctx.stylize('[Setter]', 'special');
  12089. }
  12090. }
  12091. if (!hasOwnProperty(visibleKeys, key)) {
  12092. name = '[' + key + ']';
  12093. }
  12094. if (!str) {
  12095. if (ctx.seen.indexOf(desc.value) < 0) {
  12096. if (isNull(recurseTimes)) {
  12097. str = formatValue(ctx, desc.value, null);
  12098. } else {
  12099. str = formatValue(ctx, desc.value, recurseTimes - 1);
  12100. }
  12101. if (str.indexOf('\n') > -1) {
  12102. if (array) {
  12103. str = str.split('\n').map(function(line) {
  12104. return ' ' + line;
  12105. }).join('\n').substr(2);
  12106. } else {
  12107. str = '\n' + str.split('\n').map(function(line) {
  12108. return ' ' + line;
  12109. }).join('\n');
  12110. }
  12111. }
  12112. } else {
  12113. str = ctx.stylize('[Circular]', 'special');
  12114. }
  12115. }
  12116. if (isUndefined(name)) {
  12117. if (array && key.match(/^\d+$/)) {
  12118. return str;
  12119. }
  12120. name = JSON.stringify('' + key);
  12121. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  12122. name = name.substr(1, name.length - 2);
  12123. name = ctx.stylize(name, 'name');
  12124. } else {
  12125. name = name.replace(/'/g, "\\'")
  12126. .replace(/\\"/g, '"')
  12127. .replace(/(^"|"$)/g, "'");
  12128. name = ctx.stylize(name, 'string');
  12129. }
  12130. }
  12131. return name + ': ' + str;
  12132. }
  12133. function reduceToSingleString(output, base, braces) {
  12134. var numLinesEst = 0;
  12135. var length = output.reduce(function(prev, cur) {
  12136. numLinesEst++;
  12137. if (cur.indexOf('\n') >= 0) numLinesEst++;
  12138. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  12139. }, 0);
  12140. if (length > 60) {
  12141. return braces[0] +
  12142. (base === '' ? '' : base + '\n ') +
  12143. ' ' +
  12144. output.join(',\n ') +
  12145. ' ' +
  12146. braces[1];
  12147. }
  12148. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  12149. }
  12150. // NOTE: These type checking functions intentionally don't use `instanceof`
  12151. // because it is fragile and can be easily faked with `Object.create()`.
  12152. function isArray(ar) {
  12153. return Array.isArray(ar);
  12154. }
  12155. exports.isArray = isArray;
  12156. function isBoolean(arg) {
  12157. return typeof arg === 'boolean';
  12158. }
  12159. exports.isBoolean = isBoolean;
  12160. function isNull(arg) {
  12161. return arg === null;
  12162. }
  12163. exports.isNull = isNull;
  12164. function isNullOrUndefined(arg) {
  12165. return arg == null;
  12166. }
  12167. exports.isNullOrUndefined = isNullOrUndefined;
  12168. function isNumber(arg) {
  12169. return typeof arg === 'number';
  12170. }
  12171. exports.isNumber = isNumber;
  12172. function isString(arg) {
  12173. return typeof arg === 'string';
  12174. }
  12175. exports.isString = isString;
  12176. function isSymbol(arg) {
  12177. return typeof arg === 'symbol';
  12178. }
  12179. exports.isSymbol = isSymbol;
  12180. function isUndefined(arg) {
  12181. return arg === void 0;
  12182. }
  12183. exports.isUndefined = isUndefined;
  12184. function isRegExp(re) {
  12185. return isObject(re) && objectToString(re) === '[object RegExp]';
  12186. }
  12187. exports.isRegExp = isRegExp;
  12188. function isObject(arg) {
  12189. return typeof arg === 'object' && arg !== null;
  12190. }
  12191. exports.isObject = isObject;
  12192. function isDate(d) {
  12193. return isObject(d) && objectToString(d) === '[object Date]';
  12194. }
  12195. exports.isDate = isDate;
  12196. function isError(e) {
  12197. return isObject(e) &&
  12198. (objectToString(e) === '[object Error]' || e instanceof Error);
  12199. }
  12200. exports.isError = isError;
  12201. function isFunction(arg) {
  12202. return typeof arg === 'function';
  12203. }
  12204. exports.isFunction = isFunction;
  12205. function isPrimitive(arg) {
  12206. return arg === null ||
  12207. typeof arg === 'boolean' ||
  12208. typeof arg === 'number' ||
  12209. typeof arg === 'string' ||
  12210. typeof arg === 'symbol' || // ES6 symbol
  12211. typeof arg === 'undefined';
  12212. }
  12213. exports.isPrimitive = isPrimitive;
  12214. exports.isBuffer = require('./support/isBuffer');
  12215. function objectToString(o) {
  12216. return Object.prototype.toString.call(o);
  12217. }
  12218. function pad(n) {
  12219. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  12220. }
  12221. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  12222. 'Oct', 'Nov', 'Dec'];
  12223. // 26 Feb 16:19:34
  12224. function timestamp() {
  12225. var d = new Date();
  12226. var time = [pad(d.getHours()),
  12227. pad(d.getMinutes()),
  12228. pad(d.getSeconds())].join(':');
  12229. return [d.getDate(), months[d.getMonth()], time].join(' ');
  12230. }
  12231. // log is just a thin wrapper to console.log that prepends a timestamp
  12232. exports.log = function() {
  12233. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  12234. };
  12235. /**
  12236. * Inherit the prototype methods from one constructor into another.
  12237. *
  12238. * The Function.prototype.inherits from lang.js rewritten as a standalone
  12239. * function (not on Function.prototype). NOTE: If this file is to be loaded
  12240. * during bootstrapping this function needs to be rewritten using some native
  12241. * functions as prototype setup using normal JavaScript does not work as
  12242. * expected during bootstrapping (see mirror.js in r114903).
  12243. *
  12244. * @param {function} ctor Constructor function which needs to inherit the
  12245. * prototype.
  12246. * @param {function} superCtor Constructor function to inherit prototype from.
  12247. */
  12248. exports.inherits = require('inherits');
  12249. exports._extend = function(origin, add) {
  12250. // Don't do anything if add isn't an object
  12251. if (!add || !isObject(add)) return origin;
  12252. var keys = Object.keys(add);
  12253. var i = keys.length;
  12254. while (i--) {
  12255. origin[keys[i]] = add[keys[i]];
  12256. }
  12257. return origin;
  12258. };
  12259. function hasOwnProperty(obj, prop) {
  12260. return Object.prototype.hasOwnProperty.call(obj, prop);
  12261. }
  12262. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12263. },{"./support/isBuffer":116,"_process":92,"inherits":80}],118:[function(require,module,exports){
  12264. (function (process,global){
  12265. 'use strict'
  12266. var Transform = require('readable-stream').Transform
  12267. var duplexify = require('duplexify')
  12268. var WS = require('ws')
  12269. var Buffer = require('safe-buffer').Buffer
  12270. module.exports = WebSocketStream
  12271. function buildProxy (options, socketWrite, socketEnd) {
  12272. var proxy = new Transform({
  12273. objectMode: options.objectMode
  12274. })
  12275. proxy._write = socketWrite
  12276. proxy._flush = socketEnd
  12277. return proxy
  12278. }
  12279. function WebSocketStream(target, protocols, options) {
  12280. var stream, socket
  12281. var isBrowser = process.title === 'browser'
  12282. var isNative = !!global.WebSocket
  12283. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  12284. if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
  12285. // accept the "options" Object as the 2nd argument
  12286. options = protocols
  12287. protocols = null
  12288. if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
  12289. protocols = options.protocol;
  12290. }
  12291. }
  12292. if (!options) options = {}
  12293. if (options.objectMode === undefined) {
  12294. options.objectMode = !(options.binary === true || options.binary === undefined)
  12295. }
  12296. var proxy = buildProxy(options, socketWrite, socketEnd)
  12297. if (!options.objectMode) {
  12298. proxy._writev = writev
  12299. }
  12300. // browser only: sets the maximum socket buffer size before throttling
  12301. var bufferSize = options.browserBufferSize || 1024 * 512
  12302. // browser only: how long to wait when throttling
  12303. var bufferTimeout = options.browserBufferTimeout || 1000
  12304. // use existing WebSocket object that was passed in
  12305. if (typeof target === 'object') {
  12306. socket = target
  12307. // otherwise make a new one
  12308. } else {
  12309. // special constructor treatment for native websockets in browsers, see
  12310. // https://github.com/maxogden/websocket-stream/issues/82
  12311. if (isNative && isBrowser) {
  12312. socket = new WS(target, protocols)
  12313. } else {
  12314. socket = new WS(target, protocols, options)
  12315. }
  12316. socket.binaryType = 'arraybuffer'
  12317. }
  12318. // was already open when passed in
  12319. if (socket.readyState === socket.OPEN) {
  12320. stream = proxy
  12321. } else {
  12322. stream = duplexify.obj()
  12323. socket.onopen = onopen
  12324. }
  12325. stream.socket = socket
  12326. socket.onclose = onclose
  12327. socket.onerror = onerror
  12328. socket.onmessage = onmessage
  12329. proxy.on('close', destroy)
  12330. var coerceToBuffer = !options.objectMode
  12331. function socketWriteNode(chunk, enc, next) {
  12332. // avoid errors, this never happens unless
  12333. // destroy() is called
  12334. if (socket.readyState !== socket.OPEN) {
  12335. next()
  12336. return
  12337. }
  12338. if (coerceToBuffer && typeof chunk === 'string') {
  12339. chunk = Buffer.from(chunk, 'utf8')
  12340. }
  12341. socket.send(chunk, next)
  12342. }
  12343. function socketWriteBrowser(chunk, enc, next) {
  12344. if (socket.bufferedAmount > bufferSize) {
  12345. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  12346. return
  12347. }
  12348. if (coerceToBuffer && typeof chunk === 'string') {
  12349. chunk = Buffer.from(chunk, 'utf8')
  12350. }
  12351. try {
  12352. socket.send(chunk)
  12353. } catch(err) {
  12354. return next(err)
  12355. }
  12356. next()
  12357. }
  12358. function socketEnd(done) {
  12359. socket.close()
  12360. done()
  12361. }
  12362. function onopen() {
  12363. stream.setReadable(proxy)
  12364. stream.setWritable(proxy)
  12365. stream.emit('connect')
  12366. }
  12367. function onclose() {
  12368. stream.end()
  12369. stream.destroy()
  12370. }
  12371. function onerror(err) {
  12372. stream.destroy(err)
  12373. }
  12374. function onmessage(event) {
  12375. var data = event.data
  12376. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  12377. else data = Buffer.from(data, 'utf8')
  12378. proxy.push(data)
  12379. }
  12380. function destroy() {
  12381. socket.close()
  12382. }
  12383. // this is to be enabled only if objectMode is false
  12384. function writev (chunks, cb) {
  12385. var buffers = new Array(chunks.length)
  12386. for (var i = 0; i < chunks.length; i++) {
  12387. if (typeof chunks[i].chunk === 'string') {
  12388. buffers[i] = Buffer.from(chunks[i], 'utf8')
  12389. } else {
  12390. buffers[i] = chunks[i].chunk
  12391. }
  12392. }
  12393. this._write(Buffer.concat(buffers), 'binary', cb)
  12394. }
  12395. return stream
  12396. }
  12397. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12398. },{"_process":92,"duplexify":17,"readable-stream":108,"safe-buffer":110,"ws":119}],119:[function(require,module,exports){
  12399. var ws = null
  12400. if (typeof WebSocket !== 'undefined') {
  12401. ws = WebSocket
  12402. } else if (typeof MozWebSocket !== 'undefined') {
  12403. ws = MozWebSocket
  12404. } else if (typeof window !== 'undefined') {
  12405. ws = window.WebSocket || window.MozWebSocket
  12406. }
  12407. module.exports = ws
  12408. },{}],120:[function(require,module,exports){
  12409. // Returns a wrapper function that returns a wrapped callback
  12410. // The wrapper function should do some stuff, and return a
  12411. // presumably different callback function.
  12412. // This makes sure that own properties are retained, so that
  12413. // decorations and such are not lost along the way.
  12414. module.exports = wrappy
  12415. function wrappy (fn, cb) {
  12416. if (fn && cb) return wrappy(fn)(cb)
  12417. if (typeof fn !== 'function')
  12418. throw new TypeError('need wrapper function')
  12419. Object.keys(fn).forEach(function (k) {
  12420. wrapper[k] = fn[k]
  12421. })
  12422. return wrapper
  12423. function wrapper() {
  12424. var args = new Array(arguments.length)
  12425. for (var i = 0; i < args.length; i++) {
  12426. args[i] = arguments[i]
  12427. }
  12428. var ret = fn.apply(this, args)
  12429. var cb = args[args.length-1]
  12430. if (typeof ret === 'function' && ret !== cb) {
  12431. Object.keys(cb).forEach(function (k) {
  12432. ret[k] = cb[k]
  12433. })
  12434. }
  12435. return ret
  12436. }
  12437. }
  12438. },{}],121:[function(require,module,exports){
  12439. module.exports = extend
  12440. var hasOwnProperty = Object.prototype.hasOwnProperty;
  12441. function extend() {
  12442. var target = {}
  12443. for (var i = 0; i < arguments.length; i++) {
  12444. var source = arguments[i]
  12445. for (var key in source) {
  12446. if (hasOwnProperty.call(source, key)) {
  12447. target[key] = source[key]
  12448. }
  12449. }
  12450. }
  12451. return target
  12452. }
  12453. },{}]},{},[9])(9)
  12454. });