mqtt.js 399 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626
  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. console.log('MqttClient.prototype._onConnect this.emit(connect')
  1166. this.emit('connect', packet)
  1167. return
  1168. }
  1169. var that = this
  1170. this._setupPingTimer()
  1171. this._resubscribe(packet)
  1172. this.connected = true
  1173. function startStreamProcess () {
  1174. var outStore = that.outgoingStore.createStream()
  1175. function clearStoreProcessing () {
  1176. that._storeProcessing = false
  1177. that._packetIdsDuringStoreProcessing = {}
  1178. }
  1179. that.once('close', remove)
  1180. outStore.on('error', function (err) {
  1181. clearStoreProcessing()
  1182. that.removeListener('close', remove)
  1183. that.emit('error', err)
  1184. })
  1185. function remove () {
  1186. outStore.destroy()
  1187. outStore = null
  1188. clearStoreProcessing()
  1189. }
  1190. function storeDeliver () {
  1191. // edge case, we wrapped this twice
  1192. if (!outStore) {
  1193. return
  1194. }
  1195. that._storeProcessing = true
  1196. var packet = outStore.read(1)
  1197. var cb
  1198. if (!packet) {
  1199. // read when data is available in the future
  1200. outStore.once('readable', storeDeliver)
  1201. return
  1202. }
  1203. // Skip already processed store packets
  1204. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1205. storeDeliver()
  1206. return
  1207. }
  1208. // Avoid unnecessary stream read operations when disconnected
  1209. if (!that.disconnecting && !that.reconnectTimer) {
  1210. cb = that.outgoing[packet.messageId]
  1211. that.outgoing[packet.messageId] = function (err, status) {
  1212. // Ensure that the original callback passed in to publish gets invoked
  1213. if (cb) {
  1214. cb(err, status)
  1215. }
  1216. storeDeliver()
  1217. }
  1218. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1219. that._sendPacket(packet)
  1220. } else if (outStore.destroy) {
  1221. outStore.destroy()
  1222. }
  1223. }
  1224. outStore.on('end', function () {
  1225. var allProcessed = true
  1226. for (var id in that._packetIdsDuringStoreProcessing) {
  1227. if (!that._packetIdsDuringStoreProcessing[id]) {
  1228. allProcessed = false
  1229. break
  1230. }
  1231. }
  1232. if (allProcessed) {
  1233. clearStoreProcessing()
  1234. that.removeListener('close', remove)
  1235. that.emit('connect', packet)
  1236. } else {
  1237. startStreamProcess()
  1238. }
  1239. })
  1240. storeDeliver()
  1241. }
  1242. // start flowing
  1243. startStreamProcess()
  1244. }
  1245. module.exports = MqttClient
  1246. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1247. },{"./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){
  1248. (function (Buffer){
  1249. 'use strict'
  1250. var Transform = require('readable-stream').Transform
  1251. var duplexify = require('duplexify')
  1252. var base64 = require('base64-js')
  1253. /* global FileReader */
  1254. var my
  1255. var proxy
  1256. var stream
  1257. var isInitialized = false
  1258. function buildProxy () {
  1259. var proxy = new Transform()
  1260. proxy._write = function (chunk, encoding, next) {
  1261. my.sendSocketMessage({
  1262. data: chunk.buffer,
  1263. success: function () {
  1264. next()
  1265. },
  1266. fail: function () {
  1267. next(new Error())
  1268. }
  1269. })
  1270. }
  1271. proxy._flush = function socketEnd (done) {
  1272. my.closeSocket({
  1273. success: function () {
  1274. done()
  1275. }
  1276. })
  1277. }
  1278. return proxy
  1279. }
  1280. function setDefaultOpts (opts) {
  1281. if (!opts.hostname) {
  1282. opts.hostname = 'localhost'
  1283. }
  1284. if (!opts.path) {
  1285. opts.path = '/'
  1286. }
  1287. if (!opts.wsOptions) {
  1288. opts.wsOptions = {}
  1289. }
  1290. }
  1291. function buildUrl (opts, client) {
  1292. var protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1293. var url = protocol + '://' + opts.hostname + opts.path
  1294. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1295. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1296. }
  1297. if (typeof (opts.transformWsUrl) === 'function') {
  1298. url = opts.transformWsUrl(url, opts, client)
  1299. }
  1300. return url
  1301. }
  1302. function bindEventHandler () {
  1303. if (isInitialized) return
  1304. isInitialized = true
  1305. my.onSocketOpen(function () {
  1306. stream.setReadable(proxy)
  1307. stream.setWritable(proxy)
  1308. stream.emit('connect')
  1309. })
  1310. my.onSocketMessage(function (res) {
  1311. if (typeof res.data === 'string') {
  1312. var array = base64.toByteArray(res.data)
  1313. var buffer = Buffer.from(array)
  1314. proxy.push(buffer)
  1315. } else {
  1316. var reader = new FileReader()
  1317. reader.addEventListener('load', function () {
  1318. var data = reader.result
  1319. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1320. else data = Buffer.from(data, 'utf8')
  1321. proxy.push(data)
  1322. })
  1323. reader.readAsArrayBuffer(res.data)
  1324. }
  1325. })
  1326. my.onSocketClose(function () {
  1327. stream.end()
  1328. stream.destroy()
  1329. })
  1330. my.onSocketError(function (res) {
  1331. stream.destroy(res)
  1332. })
  1333. }
  1334. function buildStream (client, opts) {
  1335. opts.hostname = opts.hostname || opts.host
  1336. if (!opts.hostname) {
  1337. throw new Error('Could not determine host. Specify host manually.')
  1338. }
  1339. var websocketSubProtocol =
  1340. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1341. ? 'mqttv3.1'
  1342. : 'mqtt'
  1343. setDefaultOpts(opts)
  1344. var url = buildUrl(opts, client)
  1345. console.log(`buildStream url = ${url}`)
  1346. my = opts.my
  1347. my.connectSocket({
  1348. url: url,
  1349. protocols: websocketSubProtocol
  1350. })
  1351. proxy = buildProxy()
  1352. stream = duplexify.obj()
  1353. bindEventHandler()
  1354. return stream
  1355. }
  1356. module.exports = buildStream
  1357. }).call(this,require("buffer").Buffer)
  1358. },{"base64-js":10,"buffer":12,"duplexify":17,"readable-stream":108}],3:[function(require,module,exports){
  1359. 'use strict'
  1360. var net = require('net')
  1361. /*
  1362. variables port and host can be removed since
  1363. you have all required information in opts object
  1364. */
  1365. function buildBuilder (client, opts) {
  1366. var port, host
  1367. opts.port = opts.port || 1883
  1368. opts.hostname = opts.hostname || opts.host || 'localhost'
  1369. port = opts.port
  1370. host = opts.hostname
  1371. return net.createConnection(port, host)
  1372. }
  1373. module.exports = buildBuilder
  1374. },{"net":11}],4:[function(require,module,exports){
  1375. 'use strict'
  1376. var tls = require('tls')
  1377. function buildBuilder (mqttClient, opts) {
  1378. var connection
  1379. opts.port = opts.port || 8883
  1380. opts.host = opts.hostname || opts.host || 'localhost'
  1381. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1382. delete opts.path
  1383. connection = tls.connect(opts)
  1384. /* eslint no-use-before-define: [2, "nofunc"] */
  1385. connection.on('secureConnect', function () {
  1386. if (opts.rejectUnauthorized && !connection.authorized) {
  1387. connection.emit('error', new Error('TLS not authorized'))
  1388. } else {
  1389. connection.removeListener('error', handleTLSerrors)
  1390. }
  1391. })
  1392. function handleTLSerrors (err) {
  1393. // How can I get verify this error is a tls error?
  1394. if (opts.rejectUnauthorized) {
  1395. mqttClient.emit('error', err)
  1396. }
  1397. // close this connection to match the behaviour of net
  1398. // otherwise all we get is an error from the connection
  1399. // and close event doesn't fire. This is a work around
  1400. // to enable the reconnect code to work the same as with
  1401. // net.createConnection
  1402. connection.end()
  1403. }
  1404. connection.on('error', handleTLSerrors)
  1405. return connection
  1406. }
  1407. module.exports = buildBuilder
  1408. },{"tls":11}],5:[function(require,module,exports){
  1409. (function (process){
  1410. 'use strict'
  1411. var websocket = require('websocket-stream')
  1412. var urlModule = require('url')
  1413. var WSS_OPTIONS = [
  1414. 'rejectUnauthorized',
  1415. 'ca',
  1416. 'cert',
  1417. 'key',
  1418. 'pfx',
  1419. 'passphrase'
  1420. ]
  1421. var IS_BROWSER = process.title === 'browser'
  1422. function buildUrl (opts, client) {
  1423. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1424. if (typeof (opts.transformWsUrl) === 'function') {
  1425. url = opts.transformWsUrl(url, opts, client)
  1426. }
  1427. return url
  1428. }
  1429. function setDefaultOpts (opts) {
  1430. if (!opts.hostname) {
  1431. opts.hostname = 'localhost'
  1432. }
  1433. if (!opts.port) {
  1434. if (opts.protocol === 'wss') {
  1435. opts.port = 443
  1436. } else {
  1437. opts.port = 80
  1438. }
  1439. }
  1440. if (!opts.path) {
  1441. opts.path = '/'
  1442. }
  1443. if (!opts.wsOptions) {
  1444. opts.wsOptions = {}
  1445. }
  1446. if (!IS_BROWSER && opts.protocol === 'wss') {
  1447. // Add cert/key/ca etc options
  1448. WSS_OPTIONS.forEach(function (prop) {
  1449. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  1450. opts.wsOptions[prop] = opts[prop]
  1451. }
  1452. })
  1453. }
  1454. }
  1455. function createWebSocket (client, opts) {
  1456. var websocketSubProtocol =
  1457. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1458. ? 'mqttv3.1'
  1459. : 'mqtt'
  1460. setDefaultOpts(opts)
  1461. var url = buildUrl(opts, client)
  1462. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1463. }
  1464. function buildBuilder (client, opts) {
  1465. return createWebSocket(client, opts)
  1466. }
  1467. function buildBuilderBrowser (client, opts) {
  1468. if (!opts.hostname) {
  1469. opts.hostname = opts.host
  1470. }
  1471. if (!opts.hostname) {
  1472. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1473. // can not determine the `hostname` automatically. If connecting to
  1474. // localhost, please supply the `hostname` as an argument.
  1475. if (typeof (document) === 'undefined') {
  1476. throw new Error('Could not determine host. Specify host manually.')
  1477. }
  1478. var parsed = urlModule.parse(document.URL)
  1479. opts.hostname = parsed.hostname
  1480. if (!opts.port) {
  1481. opts.port = parsed.port
  1482. }
  1483. }
  1484. return createWebSocket(client, opts)
  1485. }
  1486. if (IS_BROWSER) {
  1487. module.exports = buildBuilderBrowser
  1488. } else {
  1489. module.exports = buildBuilder
  1490. }
  1491. }).call(this,require('_process'))
  1492. },{"_process":92,"url":113,"websocket-stream":118}],6:[function(require,module,exports){
  1493. (function (process,Buffer){
  1494. 'use strict'
  1495. var Transform = require('readable-stream').Transform
  1496. var duplexify = require('duplexify')
  1497. /* global wx */
  1498. var socketTask
  1499. var proxy
  1500. var stream
  1501. function buildProxy () {
  1502. var proxy = new Transform()
  1503. proxy._write = function (chunk, encoding, next) {
  1504. //console.log(`发送数据`)
  1505. socketTask.send({
  1506. data: chunk.buffer,
  1507. success: function () {
  1508. console.log(`发送数据成功 chunk = ${chunk}`)
  1509. next()
  1510. },
  1511. fail: function (errMsg) {
  1512. //console.log(`发送数据失败 errMsg = ${errMsg}`)
  1513. next(new Error(errMsg))
  1514. }
  1515. })
  1516. }
  1517. proxy._flush = function socketEnd (done) {
  1518. socketTask.close({
  1519. success: function () {
  1520. console.log('proxy._flush socketTask.close success')
  1521. done()
  1522. },
  1523. fail:function(err){
  1524. console.log('proxy._flush socketTask.close fail')
  1525. console.log(err)
  1526. }
  1527. })
  1528. }
  1529. return proxy
  1530. }
  1531. function setDefaultOpts (opts) {
  1532. if (!opts.hostname) {
  1533. opts.hostname = 'localhost'
  1534. }
  1535. if (!opts.path) {
  1536. opts.path = '/'
  1537. }
  1538. if (!opts.wsOptions) {
  1539. opts.wsOptions = {}
  1540. }
  1541. }
  1542. function buildUrl (opts, client) {
  1543. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1544. var url = protocol + '://' + opts.hostname + opts.path
  1545. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1546. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1547. }
  1548. if (typeof (opts.transformWsUrl) === 'function') {
  1549. url = opts.transformWsUrl(url, opts, client)
  1550. }
  1551. return url
  1552. }
  1553. function bindEventHandler () {
  1554. socketTask.onOpen(function () {
  1555. console.log("socketTask.onOpen")
  1556. stream.setReadable(proxy)
  1557. stream.setWritable(proxy)
  1558. stream.emit('connect')
  1559. })
  1560. socketTask.onMessage(function (res) {
  1561. var data = res.data
  1562. if (data instanceof ArrayBuffer){
  1563. data = Buffer.from(data)
  1564. }
  1565. else{
  1566. data = Buffer.from(data, 'utf8')
  1567. }
  1568. //console.log(`socketTask.onMessage data = ${data}`)
  1569. proxy.push(data)
  1570. })
  1571. socketTask.onClose(function () {
  1572. console.log(`socketTask.onClose`)
  1573. stream.end()
  1574. stream.destroy()
  1575. stream.emit('close')
  1576. })
  1577. socketTask.onError(function (res) {
  1578. console.log(`socketTask.onError res = ${res}`)
  1579. stream.destroy(new Error(res.errMsg))
  1580. })
  1581. }
  1582. function buildStream (client, opts) {
  1583. var that = this
  1584. opts.hostname = opts.hostname || opts.host
  1585. if (!opts.hostname) {
  1586. throw new Error('Could not determine host. Specify host manually.')
  1587. }
  1588. var websocketSubProtocol =
  1589. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1590. ? 'mqttv3.1'
  1591. : 'mqtt'
  1592. setDefaultOpts(opts)
  1593. var url = buildUrl(opts, client)
  1594. console.log(`buildStream111 url = ${url}`)
  1595. socketTask = wx.connectSocket({
  1596. url: url,
  1597. protocols: websocketSubProtocol,
  1598. success(res){
  1599. console.log('服务器连接成功');
  1600. },
  1601. fail(err){
  1602. console.log('服务器连接失败');
  1603. }
  1604. })
  1605. proxy = buildProxy()
  1606. stream = duplexify.obj()
  1607. stream._destroy = function (err, cb) {
  1608. console.log('____socketTask.close')
  1609. socketTask.close({
  1610. success: function () {
  1611. console.log('___socketTask.close success')
  1612. //cb && cb(err)
  1613. },
  1614. fail:function (err) {
  1615. console.log('___socketTask.close failed')
  1616. console.log(err)
  1617. },
  1618. complete:function(){
  1619. console.log('___socketTask.close complete')
  1620. console.log(cb)
  1621. cb && cb(err)
  1622. }
  1623. })
  1624. }
  1625. var destroyRef = stream.destroy
  1626. stream.destroy = function () {
  1627. stream.destroy = destroyRef
  1628. var self = this
  1629. console.log('process.nextTick socketTask.close')
  1630. process.nextTick(function () {
  1631. console.log('socketTask.close')
  1632. socketTask.close({
  1633. success:function(){
  1634. //that.emit('close')
  1635. console.log('socketTask.close success')
  1636. },
  1637. fail: function (err) {
  1638. console.log('socketTask.close fail')
  1639. console.log(err)
  1640. self._destroy(new Error())
  1641. }
  1642. })
  1643. })
  1644. }.bind(stream)
  1645. bindEventHandler()
  1646. return stream
  1647. }
  1648. module.exports = buildStream
  1649. }).call(this,require('_process'),require("buffer").Buffer)
  1650. },{"_process":92,"buffer":12,"duplexify":17,"readable-stream":108}],7:[function(require,module,exports){
  1651. (function (process){
  1652. 'use strict'
  1653. /**
  1654. * Module dependencies
  1655. */
  1656. var xtend = require('xtend')
  1657. var Readable = require('readable-stream').Readable
  1658. var streamsOpts = { objectMode: true }
  1659. var defaultStoreOptions = {
  1660. clean: true
  1661. }
  1662. /**
  1663. * es6-map can preserve insertion order even if ES version is older.
  1664. *
  1665. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
  1666. * It should be noted that a Map which is a map of an object, especially
  1667. * a dictionary of dictionaries, will only map to the object's insertion
  1668. * order. In ES2015 this is ordered for objects but for older versions of
  1669. * ES, this may be random and not ordered.
  1670. *
  1671. */
  1672. var Map = require('es6-map')
  1673. /**
  1674. * In-memory implementation of the message store
  1675. * This can actually be saved into files.
  1676. *
  1677. * @param {Object} [options] - store options
  1678. */
  1679. function Store (options) {
  1680. if (!(this instanceof Store)) {
  1681. return new Store(options)
  1682. }
  1683. this.options = options || {}
  1684. // Defaults
  1685. this.options = xtend(defaultStoreOptions, options)
  1686. this._inflights = new Map()
  1687. }
  1688. /**
  1689. * Adds a packet to the store, a packet is
  1690. * anything that has a messageId property.
  1691. *
  1692. */
  1693. Store.prototype.put = function (packet, cb) {
  1694. this._inflights.set(packet.messageId, packet)
  1695. if (cb) {
  1696. cb()
  1697. }
  1698. return this
  1699. }
  1700. /**
  1701. * Creates a stream with all the packets in the store
  1702. *
  1703. */
  1704. Store.prototype.createStream = function () {
  1705. var stream = new Readable(streamsOpts)
  1706. var destroyed = false
  1707. var values = []
  1708. var i = 0
  1709. this._inflights.forEach(function (value, key) {
  1710. values.push(value)
  1711. })
  1712. stream._read = function () {
  1713. if (!destroyed && i < values.length) {
  1714. this.push(values[i++])
  1715. } else {
  1716. this.push(null)
  1717. }
  1718. }
  1719. stream.destroy = function () {
  1720. if (destroyed) {
  1721. return
  1722. }
  1723. var self = this
  1724. destroyed = true
  1725. process.nextTick(function () {
  1726. console.log(`process.nextTick(function () {`)
  1727. self.emit('close')
  1728. })
  1729. }
  1730. return stream
  1731. }
  1732. /**
  1733. * deletes a packet from the store.
  1734. */
  1735. Store.prototype.del = function (packet, cb) {
  1736. packet = this._inflights.get(packet.messageId)
  1737. if (packet) {
  1738. this._inflights.delete(packet.messageId)
  1739. cb(null, packet)
  1740. } else if (cb) {
  1741. cb(new Error('missing packet'))
  1742. }
  1743. return this
  1744. }
  1745. /**
  1746. * get a packet from the store.
  1747. */
  1748. Store.prototype.get = function (packet, cb) {
  1749. packet = this._inflights.get(packet.messageId)
  1750. if (packet) {
  1751. cb(null, packet)
  1752. } else if (cb) {
  1753. cb(new Error('missing packet'))
  1754. }
  1755. return this
  1756. }
  1757. /**
  1758. * Close the store
  1759. */
  1760. Store.prototype.close = function (cb) {
  1761. if (this.options.clean) {
  1762. this._inflights = null
  1763. }
  1764. if (cb) {
  1765. cb()
  1766. }
  1767. }
  1768. module.exports = Store
  1769. }).call(this,require('_process'))
  1770. },{"_process":92,"es6-map":67,"readable-stream":108,"xtend":121}],8:[function(require,module,exports){
  1771. 'use strict'
  1772. /**
  1773. * Validate a topic to see if it's valid or not.
  1774. * A topic is valid if it follow below rules:
  1775. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1776. * - Rule #2: Part `#` must be located at the end of the mailbox
  1777. *
  1778. * @param {String} topic - A topic
  1779. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1780. */
  1781. function validateTopic (topic) {
  1782. var parts = topic.split('/')
  1783. for (var i = 0; i < parts.length; i++) {
  1784. if (parts[i] === '+') {
  1785. continue
  1786. }
  1787. if (parts[i] === '#') {
  1788. // for Rule #2
  1789. return i === parts.length - 1
  1790. }
  1791. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1792. return false
  1793. }
  1794. }
  1795. return true
  1796. }
  1797. /**
  1798. * Validate an array of topics to see if any of them is valid or not
  1799. * @param {Array} topics - Array of topics
  1800. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1801. */
  1802. function validateTopics (topics) {
  1803. if (topics.length === 0) {
  1804. return 'empty_topic_list'
  1805. }
  1806. for (var i = 0; i < topics.length; i++) {
  1807. if (!validateTopic(topics[i])) {
  1808. return topics[i]
  1809. }
  1810. }
  1811. return null
  1812. }
  1813. module.exports = {
  1814. validateTopics: validateTopics
  1815. }
  1816. },{}],9:[function(require,module,exports){
  1817. (function (process){
  1818. 'use strict'
  1819. var MqttClient = require('../client')
  1820. var Store = require('../store')
  1821. var url = require('url')
  1822. var xtend = require('xtend')
  1823. var protocols = {}
  1824. if (process.title !== 'browser') {
  1825. protocols.mqtt = require('./tcp')
  1826. protocols.tcp = require('./tcp')
  1827. protocols.ssl = require('./tls')
  1828. protocols.tls = require('./tls')
  1829. protocols.mqtts = require('./tls')
  1830. } else {
  1831. protocols.wx = require('./wx')
  1832. protocols.wxs = require('./wx')
  1833. protocols.ali = require('./ali')
  1834. protocols.alis = require('./ali')
  1835. }
  1836. protocols.ws = require('./ws')
  1837. protocols.wss = require('./ws')
  1838. /**
  1839. * Parse the auth attribute and merge username and password in the options object.
  1840. *
  1841. * @param {Object} [opts] option object
  1842. */
  1843. function parseAuthOptions (opts) {
  1844. var matches
  1845. if (opts.auth) {
  1846. matches = opts.auth.match(/^(.+):(.+)$/)
  1847. if (matches) {
  1848. opts.username = matches[1]
  1849. opts.password = matches[2]
  1850. } else {
  1851. opts.username = opts.auth
  1852. }
  1853. }
  1854. }
  1855. /**
  1856. * connect - connect to an MQTT broker.
  1857. *
  1858. * @param {String} [brokerUrl] - url of the broker, optional
  1859. * @param {Object} opts - see MqttClient#constructor
  1860. */
  1861. function connect (brokerUrl, opts) {
  1862. if ((typeof brokerUrl === 'object') && !opts) {
  1863. opts = brokerUrl
  1864. brokerUrl = null
  1865. }
  1866. opts = opts || {}
  1867. if (brokerUrl) {
  1868. var parsed = url.parse(brokerUrl, true)
  1869. if (parsed.port != null) {
  1870. parsed.port = Number(parsed.port)
  1871. }
  1872. opts = xtend(parsed, opts)
  1873. if (opts.protocol === null) {
  1874. throw new Error('Missing protocol')
  1875. }
  1876. opts.protocol = opts.protocol.replace(/:$/, '')
  1877. }
  1878. // merge in the auth options if supplied
  1879. parseAuthOptions(opts)
  1880. // support clientId passed in the query string of the url
  1881. if (opts.query && typeof opts.query.clientId === 'string') {
  1882. opts.clientId = opts.query.clientId
  1883. }
  1884. if (opts.cert && opts.key) {
  1885. if (opts.protocol) {
  1886. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  1887. switch (opts.protocol) {
  1888. case 'mqtt':
  1889. opts.protocol = 'mqtts'
  1890. break
  1891. case 'ws':
  1892. opts.protocol = 'wss'
  1893. break
  1894. case 'wx':
  1895. opts.protocol = 'wxs'
  1896. break
  1897. case 'ali':
  1898. opts.protocol = 'alis'
  1899. break
  1900. default:
  1901. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  1902. }
  1903. }
  1904. } else {
  1905. // don't know what protocol he want to use, mqtts or wss
  1906. throw new Error('Missing secure protocol key')
  1907. }
  1908. }
  1909. if (!protocols[opts.protocol]) {
  1910. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  1911. opts.protocol = [
  1912. 'mqtt',
  1913. 'mqtts',
  1914. 'ws',
  1915. 'wss',
  1916. 'wx',
  1917. 'wxs',
  1918. 'ali',
  1919. 'alis'
  1920. ].filter(function (key, index) {
  1921. if (isSecure && index % 2 === 0) {
  1922. // Skip insecure protocols when requesting a secure one.
  1923. return false
  1924. }
  1925. return (typeof protocols[key] === 'function')
  1926. })[0]
  1927. }
  1928. if (opts.clean === false && !opts.clientId) {
  1929. throw new Error('Missing clientId for unclean clients')
  1930. }
  1931. if (opts.protocol) {
  1932. opts.defaultProtocol = opts.protocol
  1933. }
  1934. function wrapper (client) {
  1935. if (opts.servers) {
  1936. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  1937. client._reconnectCount = 0
  1938. }
  1939. opts.host = opts.servers[client._reconnectCount].host
  1940. opts.port = opts.servers[client._reconnectCount].port
  1941. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  1942. opts.hostname = opts.host
  1943. client._reconnectCount++
  1944. }
  1945. return protocols[opts.protocol](client, opts)
  1946. }
  1947. return new MqttClient(wrapper, opts)
  1948. }
  1949. module.exports = connect
  1950. module.exports.connect = connect
  1951. module.exports.MqttClient = MqttClient
  1952. module.exports.Store = Store
  1953. }).call(this,require('_process'))
  1954. },{"../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){
  1955. 'use strict'
  1956. exports.byteLength = byteLength
  1957. exports.toByteArray = toByteArray
  1958. exports.fromByteArray = fromByteArray
  1959. var lookup = []
  1960. var revLookup = []
  1961. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1962. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1963. for (var i = 0, len = code.length; i < len; ++i) {
  1964. lookup[i] = code[i]
  1965. revLookup[code.charCodeAt(i)] = i
  1966. }
  1967. // Support decoding URL-safe base64 strings, as Node.js does.
  1968. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  1969. revLookup['-'.charCodeAt(0)] = 62
  1970. revLookup['_'.charCodeAt(0)] = 63
  1971. function getLens (b64) {
  1972. var len = b64.length
  1973. if (len % 4 > 0) {
  1974. throw new Error('Invalid string. Length must be a multiple of 4')
  1975. }
  1976. // Trim off extra bytes after placeholder bytes are found
  1977. // See: https://github.com/beatgammit/base64-js/issues/42
  1978. var validLen = b64.indexOf('=')
  1979. if (validLen === -1) validLen = len
  1980. var placeHoldersLen = validLen === len
  1981. ? 0
  1982. : 4 - (validLen % 4)
  1983. return [validLen, placeHoldersLen]
  1984. }
  1985. // base64 is 4/3 + up to two characters of the original data
  1986. function byteLength (b64) {
  1987. var lens = getLens(b64)
  1988. var validLen = lens[0]
  1989. var placeHoldersLen = lens[1]
  1990. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1991. }
  1992. function _byteLength (b64, validLen, placeHoldersLen) {
  1993. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1994. }
  1995. function toByteArray (b64) {
  1996. var tmp
  1997. var lens = getLens(b64)
  1998. var validLen = lens[0]
  1999. var placeHoldersLen = lens[1]
  2000. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2001. var curByte = 0
  2002. // if there are placeholders, only get up to the last complete 4 chars
  2003. var len = placeHoldersLen > 0
  2004. ? validLen - 4
  2005. : validLen
  2006. for (var i = 0; i < len; i += 4) {
  2007. tmp =
  2008. (revLookup[b64.charCodeAt(i)] << 18) |
  2009. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2010. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2011. revLookup[b64.charCodeAt(i + 3)]
  2012. arr[curByte++] = (tmp >> 16) & 0xFF
  2013. arr[curByte++] = (tmp >> 8) & 0xFF
  2014. arr[curByte++] = tmp & 0xFF
  2015. }
  2016. if (placeHoldersLen === 2) {
  2017. tmp =
  2018. (revLookup[b64.charCodeAt(i)] << 2) |
  2019. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2020. arr[curByte++] = tmp & 0xFF
  2021. }
  2022. if (placeHoldersLen === 1) {
  2023. tmp =
  2024. (revLookup[b64.charCodeAt(i)] << 10) |
  2025. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2026. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2027. arr[curByte++] = (tmp >> 8) & 0xFF
  2028. arr[curByte++] = tmp & 0xFF
  2029. }
  2030. return arr
  2031. }
  2032. function tripletToBase64 (num) {
  2033. return lookup[num >> 18 & 0x3F] +
  2034. lookup[num >> 12 & 0x3F] +
  2035. lookup[num >> 6 & 0x3F] +
  2036. lookup[num & 0x3F]
  2037. }
  2038. function encodeChunk (uint8, start, end) {
  2039. var tmp
  2040. var output = []
  2041. for (var i = start; i < end; i += 3) {
  2042. tmp =
  2043. ((uint8[i] << 16) & 0xFF0000) +
  2044. ((uint8[i + 1] << 8) & 0xFF00) +
  2045. (uint8[i + 2] & 0xFF)
  2046. output.push(tripletToBase64(tmp))
  2047. }
  2048. return output.join('')
  2049. }
  2050. function fromByteArray (uint8) {
  2051. var tmp
  2052. var len = uint8.length
  2053. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2054. var parts = []
  2055. var maxChunkLength = 16383 // must be multiple of 3
  2056. // go through the array every three bytes, we'll deal with trailing stuff later
  2057. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2058. parts.push(encodeChunk(
  2059. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2060. ))
  2061. }
  2062. // pad the end with zeros, but make sure to not forget the extra bytes
  2063. if (extraBytes === 1) {
  2064. tmp = uint8[len - 1]
  2065. parts.push(
  2066. lookup[tmp >> 2] +
  2067. lookup[(tmp << 4) & 0x3F] +
  2068. '=='
  2069. )
  2070. } else if (extraBytes === 2) {
  2071. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2072. parts.push(
  2073. lookup[tmp >> 10] +
  2074. lookup[(tmp >> 4) & 0x3F] +
  2075. lookup[(tmp << 2) & 0x3F] +
  2076. '='
  2077. )
  2078. }
  2079. return parts.join('')
  2080. }
  2081. },{}],11:[function(require,module,exports){
  2082. },{}],12:[function(require,module,exports){
  2083. /*!
  2084. * The buffer module from node.js, for the browser.
  2085. *
  2086. * @author Feross Aboukhadijeh <https://feross.org>
  2087. * @license MIT
  2088. */
  2089. /* eslint-disable no-proto */
  2090. 'use strict'
  2091. var base64 = require('base64-js')
  2092. var ieee754 = require('ieee754')
  2093. exports.Buffer = Buffer
  2094. exports.SlowBuffer = SlowBuffer
  2095. exports.INSPECT_MAX_BYTES = 50
  2096. var K_MAX_LENGTH = 0x7fffffff
  2097. exports.kMaxLength = K_MAX_LENGTH
  2098. /**
  2099. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2100. * === true Use Uint8Array implementation (fastest)
  2101. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2102. * implementation (most compatible, even IE6)
  2103. *
  2104. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2105. * Opera 11.6+, iOS 4.2+.
  2106. *
  2107. * We report that the browser does not support typed arrays if the are not subclassable
  2108. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2109. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2110. * for __proto__ and has a buggy typed array implementation.
  2111. */
  2112. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2113. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2114. typeof console.error === 'function') {
  2115. console.error(
  2116. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2117. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2118. )
  2119. }
  2120. function typedArraySupport () {
  2121. // Can typed array instances can be augmented?
  2122. try {
  2123. var arr = new Uint8Array(1)
  2124. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2125. return arr.foo() === 42
  2126. } catch (e) {
  2127. return false
  2128. }
  2129. }
  2130. Object.defineProperty(Buffer.prototype, 'parent', {
  2131. enumerable: true,
  2132. get: function () {
  2133. if (!Buffer.isBuffer(this)) return undefined
  2134. return this.buffer
  2135. }
  2136. })
  2137. Object.defineProperty(Buffer.prototype, 'offset', {
  2138. enumerable: true,
  2139. get: function () {
  2140. if (!Buffer.isBuffer(this)) return undefined
  2141. return this.byteOffset
  2142. }
  2143. })
  2144. function createBuffer (length) {
  2145. if (length > K_MAX_LENGTH) {
  2146. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2147. }
  2148. // Return an augmented `Uint8Array` instance
  2149. var buf = new Uint8Array(length)
  2150. buf.__proto__ = Buffer.prototype
  2151. return buf
  2152. }
  2153. /**
  2154. * The Buffer constructor returns instances of `Uint8Array` that have their
  2155. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2156. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2157. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2158. * returns a single octet.
  2159. *
  2160. * The `Uint8Array` prototype remains unmodified.
  2161. */
  2162. function Buffer (arg, encodingOrOffset, length) {
  2163. // Common case.
  2164. if (typeof arg === 'number') {
  2165. if (typeof encodingOrOffset === 'string') {
  2166. throw new TypeError(
  2167. 'The "string" argument must be of type string. Received type number'
  2168. )
  2169. }
  2170. return allocUnsafe(arg)
  2171. }
  2172. return from(arg, encodingOrOffset, length)
  2173. }
  2174. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2175. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2176. Buffer[Symbol.species] === Buffer) {
  2177. Object.defineProperty(Buffer, Symbol.species, {
  2178. value: null,
  2179. configurable: true,
  2180. enumerable: false,
  2181. writable: false
  2182. })
  2183. }
  2184. Buffer.poolSize = 8192 // not used by this implementation
  2185. function from (value, encodingOrOffset, length) {
  2186. if (typeof value === 'string') {
  2187. return fromString(value, encodingOrOffset)
  2188. }
  2189. if (ArrayBuffer.isView(value)) {
  2190. return fromArrayLike(value)
  2191. }
  2192. if (value == null) {
  2193. throw 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. if (isInstance(value, ArrayBuffer) ||
  2199. (value && isInstance(value.buffer, ArrayBuffer))) {
  2200. return fromArrayBuffer(value, encodingOrOffset, length)
  2201. }
  2202. if (typeof value === 'number') {
  2203. throw new TypeError(
  2204. 'The "value" argument must not be of type number. Received type number'
  2205. )
  2206. }
  2207. var valueOf = value.valueOf && value.valueOf()
  2208. if (valueOf != null && valueOf !== value) {
  2209. return Buffer.from(valueOf, encodingOrOffset, length)
  2210. }
  2211. var b = fromObject(value)
  2212. if (b) return b
  2213. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2214. typeof value[Symbol.toPrimitive] === 'function') {
  2215. return Buffer.from(
  2216. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2217. )
  2218. }
  2219. throw new TypeError(
  2220. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2221. 'or Array-like Object. Received type ' + (typeof value)
  2222. )
  2223. }
  2224. /**
  2225. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2226. * if value is a number.
  2227. * Buffer.from(str[, encoding])
  2228. * Buffer.from(array)
  2229. * Buffer.from(buffer)
  2230. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2231. **/
  2232. Buffer.from = function (value, encodingOrOffset, length) {
  2233. return from(value, encodingOrOffset, length)
  2234. }
  2235. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2236. // https://github.com/feross/buffer/pull/148
  2237. Buffer.prototype.__proto__ = Uint8Array.prototype
  2238. Buffer.__proto__ = Uint8Array
  2239. function assertSize (size) {
  2240. if (typeof size !== 'number') {
  2241. throw new TypeError('"size" argument must be of type number')
  2242. } else if (size < 0) {
  2243. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2244. }
  2245. }
  2246. function alloc (size, fill, encoding) {
  2247. assertSize(size)
  2248. if (size <= 0) {
  2249. return createBuffer(size)
  2250. }
  2251. if (fill !== undefined) {
  2252. // Only pay attention to encoding if it's a string. This
  2253. // prevents accidentally sending in a number that would
  2254. // be interpretted as a start offset.
  2255. return typeof encoding === 'string'
  2256. ? createBuffer(size).fill(fill, encoding)
  2257. : createBuffer(size).fill(fill)
  2258. }
  2259. return createBuffer(size)
  2260. }
  2261. /**
  2262. * Creates a new filled Buffer instance.
  2263. * alloc(size[, fill[, encoding]])
  2264. **/
  2265. Buffer.alloc = function (size, fill, encoding) {
  2266. return alloc(size, fill, encoding)
  2267. }
  2268. function allocUnsafe (size) {
  2269. assertSize(size)
  2270. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2271. }
  2272. /**
  2273. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2274. * */
  2275. Buffer.allocUnsafe = function (size) {
  2276. return allocUnsafe(size)
  2277. }
  2278. /**
  2279. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2280. */
  2281. Buffer.allocUnsafeSlow = function (size) {
  2282. return allocUnsafe(size)
  2283. }
  2284. function fromString (string, encoding) {
  2285. if (typeof encoding !== 'string' || encoding === '') {
  2286. encoding = 'utf8'
  2287. }
  2288. if (!Buffer.isEncoding(encoding)) {
  2289. throw new TypeError('Unknown encoding: ' + encoding)
  2290. }
  2291. var length = byteLength(string, encoding) | 0
  2292. var buf = createBuffer(length)
  2293. var actual = buf.write(string, encoding)
  2294. if (actual !== length) {
  2295. // Writing a hex string, for example, that contains invalid characters will
  2296. // cause everything after the first invalid character to be ignored. (e.g.
  2297. // 'abxxcd' will be treated as 'ab')
  2298. buf = buf.slice(0, actual)
  2299. }
  2300. return buf
  2301. }
  2302. function fromArrayLike (array) {
  2303. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2304. var buf = createBuffer(length)
  2305. for (var i = 0; i < length; i += 1) {
  2306. buf[i] = array[i] & 255
  2307. }
  2308. return buf
  2309. }
  2310. function fromArrayBuffer (array, byteOffset, length) {
  2311. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2312. throw new RangeError('"offset" is outside of buffer bounds')
  2313. }
  2314. if (array.byteLength < byteOffset + (length || 0)) {
  2315. throw new RangeError('"length" is outside of buffer bounds')
  2316. }
  2317. var buf
  2318. if (byteOffset === undefined && length === undefined) {
  2319. buf = new Uint8Array(array)
  2320. } else if (length === undefined) {
  2321. buf = new Uint8Array(array, byteOffset)
  2322. } else {
  2323. buf = new Uint8Array(array, byteOffset, length)
  2324. }
  2325. // Return an augmented `Uint8Array` instance
  2326. buf.__proto__ = Buffer.prototype
  2327. return buf
  2328. }
  2329. function fromObject (obj) {
  2330. if (Buffer.isBuffer(obj)) {
  2331. var len = checked(obj.length) | 0
  2332. var buf = createBuffer(len)
  2333. if (buf.length === 0) {
  2334. return buf
  2335. }
  2336. obj.copy(buf, 0, 0, len)
  2337. return buf
  2338. }
  2339. if (obj.length !== undefined) {
  2340. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2341. return createBuffer(0)
  2342. }
  2343. return fromArrayLike(obj)
  2344. }
  2345. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2346. return fromArrayLike(obj.data)
  2347. }
  2348. }
  2349. function checked (length) {
  2350. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2351. // length is NaN (which is otherwise coerced to zero.)
  2352. if (length >= K_MAX_LENGTH) {
  2353. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2354. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2355. }
  2356. return length | 0
  2357. }
  2358. function SlowBuffer (length) {
  2359. if (+length != length) { // eslint-disable-line eqeqeq
  2360. length = 0
  2361. }
  2362. return Buffer.alloc(+length)
  2363. }
  2364. Buffer.isBuffer = function isBuffer (b) {
  2365. return b != null && b._isBuffer === true &&
  2366. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2367. }
  2368. Buffer.compare = function compare (a, b) {
  2369. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2370. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2371. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2372. throw new TypeError(
  2373. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2374. )
  2375. }
  2376. if (a === b) return 0
  2377. var x = a.length
  2378. var y = b.length
  2379. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2380. if (a[i] !== b[i]) {
  2381. x = a[i]
  2382. y = b[i]
  2383. break
  2384. }
  2385. }
  2386. if (x < y) return -1
  2387. if (y < x) return 1
  2388. return 0
  2389. }
  2390. Buffer.isEncoding = function isEncoding (encoding) {
  2391. switch (String(encoding).toLowerCase()) {
  2392. case 'hex':
  2393. case 'utf8':
  2394. case 'utf-8':
  2395. case 'ascii':
  2396. case 'latin1':
  2397. case 'binary':
  2398. case 'base64':
  2399. case 'ucs2':
  2400. case 'ucs-2':
  2401. case 'utf16le':
  2402. case 'utf-16le':
  2403. return true
  2404. default:
  2405. return false
  2406. }
  2407. }
  2408. Buffer.concat = function concat (list, length) {
  2409. if (!Array.isArray(list)) {
  2410. throw new TypeError('"list" argument must be an Array of Buffers')
  2411. }
  2412. if (list.length === 0) {
  2413. return Buffer.alloc(0)
  2414. }
  2415. var i
  2416. if (length === undefined) {
  2417. length = 0
  2418. for (i = 0; i < list.length; ++i) {
  2419. length += list[i].length
  2420. }
  2421. }
  2422. var buffer = Buffer.allocUnsafe(length)
  2423. var pos = 0
  2424. for (i = 0; i < list.length; ++i) {
  2425. var buf = list[i]
  2426. if (isInstance(buf, Uint8Array)) {
  2427. buf = Buffer.from(buf)
  2428. }
  2429. if (!Buffer.isBuffer(buf)) {
  2430. throw new TypeError('"list" argument must be an Array of Buffers')
  2431. }
  2432. buf.copy(buffer, pos)
  2433. pos += buf.length
  2434. }
  2435. return buffer
  2436. }
  2437. function byteLength (string, encoding) {
  2438. if (Buffer.isBuffer(string)) {
  2439. return string.length
  2440. }
  2441. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2442. return string.byteLength
  2443. }
  2444. if (typeof string !== 'string') {
  2445. throw new TypeError(
  2446. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2447. 'Received type ' + typeof string
  2448. )
  2449. }
  2450. var len = string.length
  2451. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2452. if (!mustMatch && len === 0) return 0
  2453. // Use a for loop to avoid recursion
  2454. var loweredCase = false
  2455. for (;;) {
  2456. switch (encoding) {
  2457. case 'ascii':
  2458. case 'latin1':
  2459. case 'binary':
  2460. return len
  2461. case 'utf8':
  2462. case 'utf-8':
  2463. return utf8ToBytes(string).length
  2464. case 'ucs2':
  2465. case 'ucs-2':
  2466. case 'utf16le':
  2467. case 'utf-16le':
  2468. return len * 2
  2469. case 'hex':
  2470. return len >>> 1
  2471. case 'base64':
  2472. return base64ToBytes(string).length
  2473. default:
  2474. if (loweredCase) {
  2475. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2476. }
  2477. encoding = ('' + encoding).toLowerCase()
  2478. loweredCase = true
  2479. }
  2480. }
  2481. }
  2482. Buffer.byteLength = byteLength
  2483. function slowToString (encoding, start, end) {
  2484. var loweredCase = false
  2485. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2486. // property of a typed array.
  2487. // This behaves neither like String nor Uint8Array in that we set start/end
  2488. // to their upper/lower bounds if the value passed is out of range.
  2489. // undefined is handled specially as per ECMA-262 6th Edition,
  2490. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2491. if (start === undefined || start < 0) {
  2492. start = 0
  2493. }
  2494. // Return early if start > this.length. Done here to prevent potential uint32
  2495. // coercion fail below.
  2496. if (start > this.length) {
  2497. return ''
  2498. }
  2499. if (end === undefined || end > this.length) {
  2500. end = this.length
  2501. }
  2502. if (end <= 0) {
  2503. return ''
  2504. }
  2505. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2506. end >>>= 0
  2507. start >>>= 0
  2508. if (end <= start) {
  2509. return ''
  2510. }
  2511. if (!encoding) encoding = 'utf8'
  2512. while (true) {
  2513. switch (encoding) {
  2514. case 'hex':
  2515. return hexSlice(this, start, end)
  2516. case 'utf8':
  2517. case 'utf-8':
  2518. return utf8Slice(this, start, end)
  2519. case 'ascii':
  2520. return asciiSlice(this, start, end)
  2521. case 'latin1':
  2522. case 'binary':
  2523. return latin1Slice(this, start, end)
  2524. case 'base64':
  2525. return base64Slice(this, start, end)
  2526. case 'ucs2':
  2527. case 'ucs-2':
  2528. case 'utf16le':
  2529. case 'utf-16le':
  2530. return utf16leSlice(this, start, end)
  2531. default:
  2532. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2533. encoding = (encoding + '').toLowerCase()
  2534. loweredCase = true
  2535. }
  2536. }
  2537. }
  2538. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2539. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2540. // reliably in a browserify context because there could be multiple different
  2541. // copies of the 'buffer' package in use. This method works even for Buffer
  2542. // instances that were created from another copy of the `buffer` package.
  2543. // See: https://github.com/feross/buffer/issues/154
  2544. Buffer.prototype._isBuffer = true
  2545. function swap (b, n, m) {
  2546. var i = b[n]
  2547. b[n] = b[m]
  2548. b[m] = i
  2549. }
  2550. Buffer.prototype.swap16 = function swap16 () {
  2551. var len = this.length
  2552. if (len % 2 !== 0) {
  2553. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2554. }
  2555. for (var i = 0; i < len; i += 2) {
  2556. swap(this, i, i + 1)
  2557. }
  2558. return this
  2559. }
  2560. Buffer.prototype.swap32 = function swap32 () {
  2561. var len = this.length
  2562. if (len % 4 !== 0) {
  2563. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2564. }
  2565. for (var i = 0; i < len; i += 4) {
  2566. swap(this, i, i + 3)
  2567. swap(this, i + 1, i + 2)
  2568. }
  2569. return this
  2570. }
  2571. Buffer.prototype.swap64 = function swap64 () {
  2572. var len = this.length
  2573. if (len % 8 !== 0) {
  2574. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2575. }
  2576. for (var i = 0; i < len; i += 8) {
  2577. swap(this, i, i + 7)
  2578. swap(this, i + 1, i + 6)
  2579. swap(this, i + 2, i + 5)
  2580. swap(this, i + 3, i + 4)
  2581. }
  2582. return this
  2583. }
  2584. Buffer.prototype.toString = function toString () {
  2585. var length = this.length
  2586. if (length === 0) return ''
  2587. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2588. return slowToString.apply(this, arguments)
  2589. }
  2590. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2591. Buffer.prototype.equals = function equals (b) {
  2592. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2593. if (this === b) return true
  2594. return Buffer.compare(this, b) === 0
  2595. }
  2596. Buffer.prototype.inspect = function inspect () {
  2597. var str = ''
  2598. var max = exports.INSPECT_MAX_BYTES
  2599. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2600. if (this.length > max) str += ' ... '
  2601. return '<Buffer ' + str + '>'
  2602. }
  2603. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2604. if (isInstance(target, Uint8Array)) {
  2605. target = Buffer.from(target, target.offset, target.byteLength)
  2606. }
  2607. if (!Buffer.isBuffer(target)) {
  2608. throw new TypeError(
  2609. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2610. 'Received type ' + (typeof target)
  2611. )
  2612. }
  2613. if (start === undefined) {
  2614. start = 0
  2615. }
  2616. if (end === undefined) {
  2617. end = target ? target.length : 0
  2618. }
  2619. if (thisStart === undefined) {
  2620. thisStart = 0
  2621. }
  2622. if (thisEnd === undefined) {
  2623. thisEnd = this.length
  2624. }
  2625. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2626. throw new RangeError('out of range index')
  2627. }
  2628. if (thisStart >= thisEnd && start >= end) {
  2629. return 0
  2630. }
  2631. if (thisStart >= thisEnd) {
  2632. return -1
  2633. }
  2634. if (start >= end) {
  2635. return 1
  2636. }
  2637. start >>>= 0
  2638. end >>>= 0
  2639. thisStart >>>= 0
  2640. thisEnd >>>= 0
  2641. if (this === target) return 0
  2642. var x = thisEnd - thisStart
  2643. var y = end - start
  2644. var len = Math.min(x, y)
  2645. var thisCopy = this.slice(thisStart, thisEnd)
  2646. var targetCopy = target.slice(start, end)
  2647. for (var i = 0; i < len; ++i) {
  2648. if (thisCopy[i] !== targetCopy[i]) {
  2649. x = thisCopy[i]
  2650. y = targetCopy[i]
  2651. break
  2652. }
  2653. }
  2654. if (x < y) return -1
  2655. if (y < x) return 1
  2656. return 0
  2657. }
  2658. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2659. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2660. //
  2661. // Arguments:
  2662. // - buffer - a Buffer to search
  2663. // - val - a string, Buffer, or number
  2664. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2665. // - encoding - an optional encoding, relevant is val is a string
  2666. // - dir - true for indexOf, false for lastIndexOf
  2667. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2668. // Empty buffer means no match
  2669. if (buffer.length === 0) return -1
  2670. // Normalize byteOffset
  2671. if (typeof byteOffset === 'string') {
  2672. encoding = byteOffset
  2673. byteOffset = 0
  2674. } else if (byteOffset > 0x7fffffff) {
  2675. byteOffset = 0x7fffffff
  2676. } else if (byteOffset < -0x80000000) {
  2677. byteOffset = -0x80000000
  2678. }
  2679. byteOffset = +byteOffset // Coerce to Number.
  2680. if (numberIsNaN(byteOffset)) {
  2681. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2682. byteOffset = dir ? 0 : (buffer.length - 1)
  2683. }
  2684. // Normalize byteOffset: negative offsets start from the end of the buffer
  2685. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2686. if (byteOffset >= buffer.length) {
  2687. if (dir) return -1
  2688. else byteOffset = buffer.length - 1
  2689. } else if (byteOffset < 0) {
  2690. if (dir) byteOffset = 0
  2691. else return -1
  2692. }
  2693. // Normalize val
  2694. if (typeof val === 'string') {
  2695. val = Buffer.from(val, encoding)
  2696. }
  2697. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2698. if (Buffer.isBuffer(val)) {
  2699. // Special case: looking for empty string/buffer always fails
  2700. if (val.length === 0) {
  2701. return -1
  2702. }
  2703. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2704. } else if (typeof val === 'number') {
  2705. val = val & 0xFF // Search for a byte value [0-255]
  2706. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2707. if (dir) {
  2708. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2709. } else {
  2710. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2711. }
  2712. }
  2713. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2714. }
  2715. throw new TypeError('val must be string, number or Buffer')
  2716. }
  2717. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2718. var indexSize = 1
  2719. var arrLength = arr.length
  2720. var valLength = val.length
  2721. if (encoding !== undefined) {
  2722. encoding = String(encoding).toLowerCase()
  2723. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2724. encoding === 'utf16le' || encoding === 'utf-16le') {
  2725. if (arr.length < 2 || val.length < 2) {
  2726. return -1
  2727. }
  2728. indexSize = 2
  2729. arrLength /= 2
  2730. valLength /= 2
  2731. byteOffset /= 2
  2732. }
  2733. }
  2734. function read (buf, i) {
  2735. if (indexSize === 1) {
  2736. return buf[i]
  2737. } else {
  2738. return buf.readUInt16BE(i * indexSize)
  2739. }
  2740. }
  2741. var i
  2742. if (dir) {
  2743. var foundIndex = -1
  2744. for (i = byteOffset; i < arrLength; i++) {
  2745. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2746. if (foundIndex === -1) foundIndex = i
  2747. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2748. } else {
  2749. if (foundIndex !== -1) i -= i - foundIndex
  2750. foundIndex = -1
  2751. }
  2752. }
  2753. } else {
  2754. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2755. for (i = byteOffset; i >= 0; i--) {
  2756. var found = true
  2757. for (var j = 0; j < valLength; j++) {
  2758. if (read(arr, i + j) !== read(val, j)) {
  2759. found = false
  2760. break
  2761. }
  2762. }
  2763. if (found) return i
  2764. }
  2765. }
  2766. return -1
  2767. }
  2768. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2769. return this.indexOf(val, byteOffset, encoding) !== -1
  2770. }
  2771. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2772. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2773. }
  2774. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2775. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2776. }
  2777. function hexWrite (buf, string, offset, length) {
  2778. offset = Number(offset) || 0
  2779. var remaining = buf.length - offset
  2780. if (!length) {
  2781. length = remaining
  2782. } else {
  2783. length = Number(length)
  2784. if (length > remaining) {
  2785. length = remaining
  2786. }
  2787. }
  2788. var strLen = string.length
  2789. if (length > strLen / 2) {
  2790. length = strLen / 2
  2791. }
  2792. for (var i = 0; i < length; ++i) {
  2793. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2794. if (numberIsNaN(parsed)) return i
  2795. buf[offset + i] = parsed
  2796. }
  2797. return i
  2798. }
  2799. function utf8Write (buf, string, offset, length) {
  2800. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2801. }
  2802. function asciiWrite (buf, string, offset, length) {
  2803. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2804. }
  2805. function latin1Write (buf, string, offset, length) {
  2806. return asciiWrite(buf, string, offset, length)
  2807. }
  2808. function base64Write (buf, string, offset, length) {
  2809. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2810. }
  2811. function ucs2Write (buf, string, offset, length) {
  2812. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2813. }
  2814. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2815. // Buffer#write(string)
  2816. if (offset === undefined) {
  2817. encoding = 'utf8'
  2818. length = this.length
  2819. offset = 0
  2820. // Buffer#write(string, encoding)
  2821. } else if (length === undefined && typeof offset === 'string') {
  2822. encoding = offset
  2823. length = this.length
  2824. offset = 0
  2825. // Buffer#write(string, offset[, length][, encoding])
  2826. } else if (isFinite(offset)) {
  2827. offset = offset >>> 0
  2828. if (isFinite(length)) {
  2829. length = length >>> 0
  2830. if (encoding === undefined) encoding = 'utf8'
  2831. } else {
  2832. encoding = length
  2833. length = undefined
  2834. }
  2835. } else {
  2836. throw new Error(
  2837. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2838. )
  2839. }
  2840. var remaining = this.length - offset
  2841. if (length === undefined || length > remaining) length = remaining
  2842. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2843. throw new RangeError('Attempt to write outside buffer bounds')
  2844. }
  2845. if (!encoding) encoding = 'utf8'
  2846. var loweredCase = false
  2847. for (;;) {
  2848. switch (encoding) {
  2849. case 'hex':
  2850. return hexWrite(this, string, offset, length)
  2851. case 'utf8':
  2852. case 'utf-8':
  2853. return utf8Write(this, string, offset, length)
  2854. case 'ascii':
  2855. return asciiWrite(this, string, offset, length)
  2856. case 'latin1':
  2857. case 'binary':
  2858. return latin1Write(this, string, offset, length)
  2859. case 'base64':
  2860. // Warning: maxLength not taken into account in base64Write
  2861. return base64Write(this, string, offset, length)
  2862. case 'ucs2':
  2863. case 'ucs-2':
  2864. case 'utf16le':
  2865. case 'utf-16le':
  2866. return ucs2Write(this, string, offset, length)
  2867. default:
  2868. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2869. encoding = ('' + encoding).toLowerCase()
  2870. loweredCase = true
  2871. }
  2872. }
  2873. }
  2874. Buffer.prototype.toJSON = function toJSON () {
  2875. return {
  2876. type: 'Buffer',
  2877. data: Array.prototype.slice.call(this._arr || this, 0)
  2878. }
  2879. }
  2880. function base64Slice (buf, start, end) {
  2881. if (start === 0 && end === buf.length) {
  2882. return base64.fromByteArray(buf)
  2883. } else {
  2884. return base64.fromByteArray(buf.slice(start, end))
  2885. }
  2886. }
  2887. function utf8Slice (buf, start, end) {
  2888. end = Math.min(buf.length, end)
  2889. var res = []
  2890. var i = start
  2891. while (i < end) {
  2892. var firstByte = buf[i]
  2893. var codePoint = null
  2894. var bytesPerSequence = (firstByte > 0xEF) ? 4
  2895. : (firstByte > 0xDF) ? 3
  2896. : (firstByte > 0xBF) ? 2
  2897. : 1
  2898. if (i + bytesPerSequence <= end) {
  2899. var secondByte, thirdByte, fourthByte, tempCodePoint
  2900. switch (bytesPerSequence) {
  2901. case 1:
  2902. if (firstByte < 0x80) {
  2903. codePoint = firstByte
  2904. }
  2905. break
  2906. case 2:
  2907. secondByte = buf[i + 1]
  2908. if ((secondByte & 0xC0) === 0x80) {
  2909. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  2910. if (tempCodePoint > 0x7F) {
  2911. codePoint = tempCodePoint
  2912. }
  2913. }
  2914. break
  2915. case 3:
  2916. secondByte = buf[i + 1]
  2917. thirdByte = buf[i + 2]
  2918. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  2919. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  2920. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  2921. codePoint = tempCodePoint
  2922. }
  2923. }
  2924. break
  2925. case 4:
  2926. secondByte = buf[i + 1]
  2927. thirdByte = buf[i + 2]
  2928. fourthByte = buf[i + 3]
  2929. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  2930. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  2931. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  2932. codePoint = tempCodePoint
  2933. }
  2934. }
  2935. }
  2936. }
  2937. if (codePoint === null) {
  2938. // we did not generate a valid codePoint so insert a
  2939. // replacement char (U+FFFD) and advance only 1 byte
  2940. codePoint = 0xFFFD
  2941. bytesPerSequence = 1
  2942. } else if (codePoint > 0xFFFF) {
  2943. // encode to utf16 (surrogate pair dance)
  2944. codePoint -= 0x10000
  2945. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  2946. codePoint = 0xDC00 | codePoint & 0x3FF
  2947. }
  2948. res.push(codePoint)
  2949. i += bytesPerSequence
  2950. }
  2951. return decodeCodePointsArray(res)
  2952. }
  2953. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  2954. // the lowest limit is Chrome, with 0x10000 args.
  2955. // We go 1 magnitude less, for safety
  2956. var MAX_ARGUMENTS_LENGTH = 0x1000
  2957. function decodeCodePointsArray (codePoints) {
  2958. var len = codePoints.length
  2959. if (len <= MAX_ARGUMENTS_LENGTH) {
  2960. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  2961. }
  2962. // Decode in chunks to avoid "call stack size exceeded".
  2963. var res = ''
  2964. var i = 0
  2965. while (i < len) {
  2966. res += String.fromCharCode.apply(
  2967. String,
  2968. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  2969. )
  2970. }
  2971. return res
  2972. }
  2973. function asciiSlice (buf, start, end) {
  2974. var ret = ''
  2975. end = Math.min(buf.length, end)
  2976. for (var i = start; i < end; ++i) {
  2977. ret += String.fromCharCode(buf[i] & 0x7F)
  2978. }
  2979. return ret
  2980. }
  2981. function latin1Slice (buf, start, end) {
  2982. var ret = ''
  2983. end = Math.min(buf.length, end)
  2984. for (var i = start; i < end; ++i) {
  2985. ret += String.fromCharCode(buf[i])
  2986. }
  2987. return ret
  2988. }
  2989. function hexSlice (buf, start, end) {
  2990. var len = buf.length
  2991. if (!start || start < 0) start = 0
  2992. if (!end || end < 0 || end > len) end = len
  2993. var out = ''
  2994. for (var i = start; i < end; ++i) {
  2995. out += toHex(buf[i])
  2996. }
  2997. return out
  2998. }
  2999. function utf16leSlice (buf, start, end) {
  3000. var bytes = buf.slice(start, end)
  3001. var res = ''
  3002. for (var i = 0; i < bytes.length; i += 2) {
  3003. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3004. }
  3005. return res
  3006. }
  3007. Buffer.prototype.slice = function slice (start, end) {
  3008. var len = this.length
  3009. start = ~~start
  3010. end = end === undefined ? len : ~~end
  3011. if (start < 0) {
  3012. start += len
  3013. if (start < 0) start = 0
  3014. } else if (start > len) {
  3015. start = len
  3016. }
  3017. if (end < 0) {
  3018. end += len
  3019. if (end < 0) end = 0
  3020. } else if (end > len) {
  3021. end = len
  3022. }
  3023. if (end < start) end = start
  3024. var newBuf = this.subarray(start, end)
  3025. // Return an augmented `Uint8Array` instance
  3026. newBuf.__proto__ = Buffer.prototype
  3027. return newBuf
  3028. }
  3029. /*
  3030. * Need to make sure that buffer isn't trying to write out of bounds.
  3031. */
  3032. function checkOffset (offset, ext, length) {
  3033. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3034. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3035. }
  3036. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3037. offset = offset >>> 0
  3038. byteLength = byteLength >>> 0
  3039. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3040. var val = this[offset]
  3041. var mul = 1
  3042. var i = 0
  3043. while (++i < byteLength && (mul *= 0x100)) {
  3044. val += this[offset + i] * mul
  3045. }
  3046. return val
  3047. }
  3048. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3049. offset = offset >>> 0
  3050. byteLength = byteLength >>> 0
  3051. if (!noAssert) {
  3052. checkOffset(offset, byteLength, this.length)
  3053. }
  3054. var val = this[offset + --byteLength]
  3055. var mul = 1
  3056. while (byteLength > 0 && (mul *= 0x100)) {
  3057. val += this[offset + --byteLength] * mul
  3058. }
  3059. return val
  3060. }
  3061. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3062. offset = offset >>> 0
  3063. if (!noAssert) checkOffset(offset, 1, this.length)
  3064. return this[offset]
  3065. }
  3066. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3067. offset = offset >>> 0
  3068. if (!noAssert) checkOffset(offset, 2, this.length)
  3069. return this[offset] | (this[offset + 1] << 8)
  3070. }
  3071. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3072. offset = offset >>> 0
  3073. if (!noAssert) checkOffset(offset, 2, this.length)
  3074. return (this[offset] << 8) | this[offset + 1]
  3075. }
  3076. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3077. offset = offset >>> 0
  3078. if (!noAssert) checkOffset(offset, 4, this.length)
  3079. return ((this[offset]) |
  3080. (this[offset + 1] << 8) |
  3081. (this[offset + 2] << 16)) +
  3082. (this[offset + 3] * 0x1000000)
  3083. }
  3084. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3085. offset = offset >>> 0
  3086. if (!noAssert) checkOffset(offset, 4, this.length)
  3087. return (this[offset] * 0x1000000) +
  3088. ((this[offset + 1] << 16) |
  3089. (this[offset + 2] << 8) |
  3090. this[offset + 3])
  3091. }
  3092. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3093. offset = offset >>> 0
  3094. byteLength = byteLength >>> 0
  3095. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3096. var val = this[offset]
  3097. var mul = 1
  3098. var i = 0
  3099. while (++i < byteLength && (mul *= 0x100)) {
  3100. val += this[offset + i] * mul
  3101. }
  3102. mul *= 0x80
  3103. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3104. return val
  3105. }
  3106. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3107. offset = offset >>> 0
  3108. byteLength = byteLength >>> 0
  3109. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3110. var i = byteLength
  3111. var mul = 1
  3112. var val = this[offset + --i]
  3113. while (i > 0 && (mul *= 0x100)) {
  3114. val += this[offset + --i] * mul
  3115. }
  3116. mul *= 0x80
  3117. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3118. return val
  3119. }
  3120. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3121. offset = offset >>> 0
  3122. if (!noAssert) checkOffset(offset, 1, this.length)
  3123. if (!(this[offset] & 0x80)) return (this[offset])
  3124. return ((0xff - this[offset] + 1) * -1)
  3125. }
  3126. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3127. offset = offset >>> 0
  3128. if (!noAssert) checkOffset(offset, 2, this.length)
  3129. var val = this[offset] | (this[offset + 1] << 8)
  3130. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3131. }
  3132. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3133. offset = offset >>> 0
  3134. if (!noAssert) checkOffset(offset, 2, this.length)
  3135. var val = this[offset + 1] | (this[offset] << 8)
  3136. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3137. }
  3138. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3139. offset = offset >>> 0
  3140. if (!noAssert) checkOffset(offset, 4, this.length)
  3141. return (this[offset]) |
  3142. (this[offset + 1] << 8) |
  3143. (this[offset + 2] << 16) |
  3144. (this[offset + 3] << 24)
  3145. }
  3146. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3147. offset = offset >>> 0
  3148. if (!noAssert) checkOffset(offset, 4, this.length)
  3149. return (this[offset] << 24) |
  3150. (this[offset + 1] << 16) |
  3151. (this[offset + 2] << 8) |
  3152. (this[offset + 3])
  3153. }
  3154. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3155. offset = offset >>> 0
  3156. if (!noAssert) checkOffset(offset, 4, this.length)
  3157. return ieee754.read(this, offset, true, 23, 4)
  3158. }
  3159. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3160. offset = offset >>> 0
  3161. if (!noAssert) checkOffset(offset, 4, this.length)
  3162. return ieee754.read(this, offset, false, 23, 4)
  3163. }
  3164. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3165. offset = offset >>> 0
  3166. if (!noAssert) checkOffset(offset, 8, this.length)
  3167. return ieee754.read(this, offset, true, 52, 8)
  3168. }
  3169. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3170. offset = offset >>> 0
  3171. if (!noAssert) checkOffset(offset, 8, this.length)
  3172. return ieee754.read(this, offset, false, 52, 8)
  3173. }
  3174. function checkInt (buf, value, offset, ext, max, min) {
  3175. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3176. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3177. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3178. }
  3179. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3180. value = +value
  3181. offset = offset >>> 0
  3182. byteLength = byteLength >>> 0
  3183. if (!noAssert) {
  3184. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3185. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3186. }
  3187. var mul = 1
  3188. var i = 0
  3189. this[offset] = value & 0xFF
  3190. while (++i < byteLength && (mul *= 0x100)) {
  3191. this[offset + i] = (value / mul) & 0xFF
  3192. }
  3193. return offset + byteLength
  3194. }
  3195. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3196. value = +value
  3197. offset = offset >>> 0
  3198. byteLength = byteLength >>> 0
  3199. if (!noAssert) {
  3200. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3201. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3202. }
  3203. var i = byteLength - 1
  3204. var mul = 1
  3205. this[offset + i] = value & 0xFF
  3206. while (--i >= 0 && (mul *= 0x100)) {
  3207. this[offset + i] = (value / mul) & 0xFF
  3208. }
  3209. return offset + byteLength
  3210. }
  3211. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3212. value = +value
  3213. offset = offset >>> 0
  3214. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3215. this[offset] = (value & 0xff)
  3216. return offset + 1
  3217. }
  3218. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3219. value = +value
  3220. offset = offset >>> 0
  3221. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3222. this[offset] = (value & 0xff)
  3223. this[offset + 1] = (value >>> 8)
  3224. return offset + 2
  3225. }
  3226. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3227. value = +value
  3228. offset = offset >>> 0
  3229. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3230. this[offset] = (value >>> 8)
  3231. this[offset + 1] = (value & 0xff)
  3232. return offset + 2
  3233. }
  3234. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3235. value = +value
  3236. offset = offset >>> 0
  3237. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3238. this[offset + 3] = (value >>> 24)
  3239. this[offset + 2] = (value >>> 16)
  3240. this[offset + 1] = (value >>> 8)
  3241. this[offset] = (value & 0xff)
  3242. return offset + 4
  3243. }
  3244. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3245. value = +value
  3246. offset = offset >>> 0
  3247. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3248. this[offset] = (value >>> 24)
  3249. this[offset + 1] = (value >>> 16)
  3250. this[offset + 2] = (value >>> 8)
  3251. this[offset + 3] = (value & 0xff)
  3252. return offset + 4
  3253. }
  3254. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3255. value = +value
  3256. offset = offset >>> 0
  3257. if (!noAssert) {
  3258. var limit = Math.pow(2, (8 * byteLength) - 1)
  3259. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3260. }
  3261. var i = 0
  3262. var mul = 1
  3263. var sub = 0
  3264. this[offset] = value & 0xFF
  3265. while (++i < byteLength && (mul *= 0x100)) {
  3266. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3267. sub = 1
  3268. }
  3269. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3270. }
  3271. return offset + byteLength
  3272. }
  3273. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3274. value = +value
  3275. offset = offset >>> 0
  3276. if (!noAssert) {
  3277. var limit = Math.pow(2, (8 * byteLength) - 1)
  3278. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3279. }
  3280. var i = byteLength - 1
  3281. var mul = 1
  3282. var sub = 0
  3283. this[offset + i] = value & 0xFF
  3284. while (--i >= 0 && (mul *= 0x100)) {
  3285. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3286. sub = 1
  3287. }
  3288. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3289. }
  3290. return offset + byteLength
  3291. }
  3292. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3293. value = +value
  3294. offset = offset >>> 0
  3295. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3296. if (value < 0) value = 0xff + value + 1
  3297. this[offset] = (value & 0xff)
  3298. return offset + 1
  3299. }
  3300. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3301. value = +value
  3302. offset = offset >>> 0
  3303. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3304. this[offset] = (value & 0xff)
  3305. this[offset + 1] = (value >>> 8)
  3306. return offset + 2
  3307. }
  3308. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3309. value = +value
  3310. offset = offset >>> 0
  3311. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3312. this[offset] = (value >>> 8)
  3313. this[offset + 1] = (value & 0xff)
  3314. return offset + 2
  3315. }
  3316. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3317. value = +value
  3318. offset = offset >>> 0
  3319. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3320. this[offset] = (value & 0xff)
  3321. this[offset + 1] = (value >>> 8)
  3322. this[offset + 2] = (value >>> 16)
  3323. this[offset + 3] = (value >>> 24)
  3324. return offset + 4
  3325. }
  3326. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3327. value = +value
  3328. offset = offset >>> 0
  3329. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3330. if (value < 0) value = 0xffffffff + value + 1
  3331. this[offset] = (value >>> 24)
  3332. this[offset + 1] = (value >>> 16)
  3333. this[offset + 2] = (value >>> 8)
  3334. this[offset + 3] = (value & 0xff)
  3335. return offset + 4
  3336. }
  3337. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3338. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3339. if (offset < 0) throw new RangeError('Index out of range')
  3340. }
  3341. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3342. value = +value
  3343. offset = offset >>> 0
  3344. if (!noAssert) {
  3345. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3346. }
  3347. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3348. return offset + 4
  3349. }
  3350. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3351. return writeFloat(this, value, offset, true, noAssert)
  3352. }
  3353. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3354. return writeFloat(this, value, offset, false, noAssert)
  3355. }
  3356. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3357. value = +value
  3358. offset = offset >>> 0
  3359. if (!noAssert) {
  3360. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3361. }
  3362. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3363. return offset + 8
  3364. }
  3365. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3366. return writeDouble(this, value, offset, true, noAssert)
  3367. }
  3368. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3369. return writeDouble(this, value, offset, false, noAssert)
  3370. }
  3371. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3372. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3373. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3374. if (!start) start = 0
  3375. if (!end && end !== 0) end = this.length
  3376. if (targetStart >= target.length) targetStart = target.length
  3377. if (!targetStart) targetStart = 0
  3378. if (end > 0 && end < start) end = start
  3379. // Copy 0 bytes; we're done
  3380. if (end === start) return 0
  3381. if (target.length === 0 || this.length === 0) return 0
  3382. // Fatal error conditions
  3383. if (targetStart < 0) {
  3384. throw new RangeError('targetStart out of bounds')
  3385. }
  3386. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3387. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3388. // Are we oob?
  3389. if (end > this.length) end = this.length
  3390. if (target.length - targetStart < end - start) {
  3391. end = target.length - targetStart + start
  3392. }
  3393. var len = end - start
  3394. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3395. // Use built-in when available, missing from IE11
  3396. this.copyWithin(targetStart, start, end)
  3397. } else if (this === target && start < targetStart && targetStart < end) {
  3398. // descending copy from end
  3399. for (var i = len - 1; i >= 0; --i) {
  3400. target[i + targetStart] = this[i + start]
  3401. }
  3402. } else {
  3403. Uint8Array.prototype.set.call(
  3404. target,
  3405. this.subarray(start, end),
  3406. targetStart
  3407. )
  3408. }
  3409. return len
  3410. }
  3411. // Usage:
  3412. // buffer.fill(number[, offset[, end]])
  3413. // buffer.fill(buffer[, offset[, end]])
  3414. // buffer.fill(string[, offset[, end]][, encoding])
  3415. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3416. // Handle string cases:
  3417. if (typeof val === 'string') {
  3418. if (typeof start === 'string') {
  3419. encoding = start
  3420. start = 0
  3421. end = this.length
  3422. } else if (typeof end === 'string') {
  3423. encoding = end
  3424. end = this.length
  3425. }
  3426. if (encoding !== undefined && typeof encoding !== 'string') {
  3427. throw new TypeError('encoding must be a string')
  3428. }
  3429. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3430. throw new TypeError('Unknown encoding: ' + encoding)
  3431. }
  3432. if (val.length === 1) {
  3433. var code = val.charCodeAt(0)
  3434. if ((encoding === 'utf8' && code < 128) ||
  3435. encoding === 'latin1') {
  3436. // Fast path: If `val` fits into a single byte, use that numeric value.
  3437. val = code
  3438. }
  3439. }
  3440. } else if (typeof val === 'number') {
  3441. val = val & 255
  3442. }
  3443. // Invalid ranges are not set to a default, so can range check early.
  3444. if (start < 0 || this.length < start || this.length < end) {
  3445. throw new RangeError('Out of range index')
  3446. }
  3447. if (end <= start) {
  3448. return this
  3449. }
  3450. start = start >>> 0
  3451. end = end === undefined ? this.length : end >>> 0
  3452. if (!val) val = 0
  3453. var i
  3454. if (typeof val === 'number') {
  3455. for (i = start; i < end; ++i) {
  3456. this[i] = val
  3457. }
  3458. } else {
  3459. var bytes = Buffer.isBuffer(val)
  3460. ? val
  3461. : Buffer.from(val, encoding)
  3462. var len = bytes.length
  3463. if (len === 0) {
  3464. throw new TypeError('The value "' + val +
  3465. '" is invalid for argument "value"')
  3466. }
  3467. for (i = 0; i < end - start; ++i) {
  3468. this[i + start] = bytes[i % len]
  3469. }
  3470. }
  3471. return this
  3472. }
  3473. // HELPER FUNCTIONS
  3474. // ================
  3475. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3476. function base64clean (str) {
  3477. // Node takes equal signs as end of the Base64 encoding
  3478. str = str.split('=')[0]
  3479. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3480. str = str.trim().replace(INVALID_BASE64_RE, '')
  3481. // Node converts strings with length < 2 to ''
  3482. if (str.length < 2) return ''
  3483. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3484. while (str.length % 4 !== 0) {
  3485. str = str + '='
  3486. }
  3487. return str
  3488. }
  3489. function toHex (n) {
  3490. if (n < 16) return '0' + n.toString(16)
  3491. return n.toString(16)
  3492. }
  3493. function utf8ToBytes (string, units) {
  3494. units = units || Infinity
  3495. var codePoint
  3496. var length = string.length
  3497. var leadSurrogate = null
  3498. var bytes = []
  3499. for (var i = 0; i < length; ++i) {
  3500. codePoint = string.charCodeAt(i)
  3501. // is surrogate component
  3502. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3503. // last char was a lead
  3504. if (!leadSurrogate) {
  3505. // no lead yet
  3506. if (codePoint > 0xDBFF) {
  3507. // unexpected trail
  3508. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3509. continue
  3510. } else if (i + 1 === length) {
  3511. // unpaired lead
  3512. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3513. continue
  3514. }
  3515. // valid lead
  3516. leadSurrogate = codePoint
  3517. continue
  3518. }
  3519. // 2 leads in a row
  3520. if (codePoint < 0xDC00) {
  3521. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3522. leadSurrogate = codePoint
  3523. continue
  3524. }
  3525. // valid surrogate pair
  3526. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3527. } else if (leadSurrogate) {
  3528. // valid bmp char, but last char was a lead
  3529. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3530. }
  3531. leadSurrogate = null
  3532. // encode utf8
  3533. if (codePoint < 0x80) {
  3534. if ((units -= 1) < 0) break
  3535. bytes.push(codePoint)
  3536. } else if (codePoint < 0x800) {
  3537. if ((units -= 2) < 0) break
  3538. bytes.push(
  3539. codePoint >> 0x6 | 0xC0,
  3540. codePoint & 0x3F | 0x80
  3541. )
  3542. } else if (codePoint < 0x10000) {
  3543. if ((units -= 3) < 0) break
  3544. bytes.push(
  3545. codePoint >> 0xC | 0xE0,
  3546. codePoint >> 0x6 & 0x3F | 0x80,
  3547. codePoint & 0x3F | 0x80
  3548. )
  3549. } else if (codePoint < 0x110000) {
  3550. if ((units -= 4) < 0) break
  3551. bytes.push(
  3552. codePoint >> 0x12 | 0xF0,
  3553. codePoint >> 0xC & 0x3F | 0x80,
  3554. codePoint >> 0x6 & 0x3F | 0x80,
  3555. codePoint & 0x3F | 0x80
  3556. )
  3557. } else {
  3558. throw new Error('Invalid code point')
  3559. }
  3560. }
  3561. return bytes
  3562. }
  3563. function asciiToBytes (str) {
  3564. var byteArray = []
  3565. for (var i = 0; i < str.length; ++i) {
  3566. // Node's code seems to be doing this and not & 0x7F..
  3567. byteArray.push(str.charCodeAt(i) & 0xFF)
  3568. }
  3569. return byteArray
  3570. }
  3571. function utf16leToBytes (str, units) {
  3572. var c, hi, lo
  3573. var byteArray = []
  3574. for (var i = 0; i < str.length; ++i) {
  3575. if ((units -= 2) < 0) break
  3576. c = str.charCodeAt(i)
  3577. hi = c >> 8
  3578. lo = c % 256
  3579. byteArray.push(lo)
  3580. byteArray.push(hi)
  3581. }
  3582. return byteArray
  3583. }
  3584. function base64ToBytes (str) {
  3585. return base64.toByteArray(base64clean(str))
  3586. }
  3587. function blitBuffer (src, dst, offset, length) {
  3588. for (var i = 0; i < length; ++i) {
  3589. if ((i + offset >= dst.length) || (i >= src.length)) break
  3590. dst[i + offset] = src[i]
  3591. }
  3592. return i
  3593. }
  3594. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3595. // the `instanceof` check but they should be treated as of that type.
  3596. // See: https://github.com/feross/buffer/issues/166
  3597. function isInstance (obj, type) {
  3598. return obj instanceof type ||
  3599. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3600. obj.constructor.name === type.name)
  3601. }
  3602. function numberIsNaN (obj) {
  3603. // For IE11 support
  3604. return obj !== obj // eslint-disable-line no-self-compare
  3605. }
  3606. },{"base64-js":10,"ieee754":79}],13:[function(require,module,exports){
  3607. // Copyright Joyent, Inc. and other Node contributors.
  3608. //
  3609. // Permission is hereby granted, free of charge, to any person obtaining a
  3610. // copy of this software and associated documentation files (the
  3611. // "Software"), to deal in the Software without restriction, including
  3612. // without limitation the rights to use, copy, modify, merge, publish,
  3613. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3614. // persons to whom the Software is furnished to do so, subject to the
  3615. // following conditions:
  3616. //
  3617. // The above copyright notice and this permission notice shall be included
  3618. // in all copies or substantial portions of the Software.
  3619. //
  3620. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3621. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3622. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3623. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3624. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3625. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3626. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3627. var objectCreate = Object.create || objectCreatePolyfill
  3628. var objectKeys = Object.keys || objectKeysPolyfill
  3629. var bind = Function.prototype.bind || functionBindPolyfill
  3630. function EventEmitter() {
  3631. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  3632. this._events = objectCreate(null);
  3633. this._eventsCount = 0;
  3634. }
  3635. this._maxListeners = this._maxListeners || undefined;
  3636. }
  3637. module.exports = EventEmitter;
  3638. // Backwards-compat with node 0.10.x
  3639. EventEmitter.EventEmitter = EventEmitter;
  3640. EventEmitter.prototype._events = undefined;
  3641. EventEmitter.prototype._maxListeners = undefined;
  3642. // By default EventEmitters will print a warning if more than 10 listeners are
  3643. // added to it. This is a useful default which helps finding memory leaks.
  3644. var defaultMaxListeners = 10;
  3645. var hasDefineProperty;
  3646. try {
  3647. var o = {};
  3648. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  3649. hasDefineProperty = o.x === 0;
  3650. } catch (err) { hasDefineProperty = false }
  3651. if (hasDefineProperty) {
  3652. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  3653. enumerable: true,
  3654. get: function() {
  3655. return defaultMaxListeners;
  3656. },
  3657. set: function(arg) {
  3658. // check whether the input is a positive number (whose value is zero or
  3659. // greater and not a NaN).
  3660. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  3661. throw new TypeError('"defaultMaxListeners" must be a positive number');
  3662. defaultMaxListeners = arg;
  3663. }
  3664. });
  3665. } else {
  3666. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  3667. }
  3668. // Obviously not all Emitters should be limited to 10. This function allows
  3669. // that to be increased. Set to zero for unlimited.
  3670. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  3671. if (typeof n !== 'number' || n < 0 || isNaN(n))
  3672. throw new TypeError('"n" argument must be a positive number');
  3673. this._maxListeners = n;
  3674. return this;
  3675. };
  3676. function $getMaxListeners(that) {
  3677. if (that._maxListeners === undefined)
  3678. return EventEmitter.defaultMaxListeners;
  3679. return that._maxListeners;
  3680. }
  3681. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  3682. return $getMaxListeners(this);
  3683. };
  3684. // These standalone emit* functions are used to optimize calling of event
  3685. // handlers for fast cases because emit() itself often has a variable number of
  3686. // arguments and can be deoptimized because of that. These functions always have
  3687. // the same number of arguments and thus do not get deoptimized, so the code
  3688. // inside them can execute faster.
  3689. function emitNone(handler, isFn, self) {
  3690. if (isFn)
  3691. handler.call(self);
  3692. else {
  3693. var len = handler.length;
  3694. var listeners = arrayClone(handler, len);
  3695. for (var i = 0; i < len; ++i)
  3696. listeners[i].call(self);
  3697. }
  3698. }
  3699. function emitOne(handler, isFn, self, arg1) {
  3700. if (isFn)
  3701. handler.call(self, arg1);
  3702. else {
  3703. var len = handler.length;
  3704. var listeners = arrayClone(handler, len);
  3705. for (var i = 0; i < len; ++i)
  3706. listeners[i].call(self, arg1);
  3707. }
  3708. }
  3709. function emitTwo(handler, isFn, self, arg1, arg2) {
  3710. if (isFn)
  3711. handler.call(self, arg1, arg2);
  3712. else {
  3713. var len = handler.length;
  3714. var listeners = arrayClone(handler, len);
  3715. for (var i = 0; i < len; ++i)
  3716. listeners[i].call(self, arg1, arg2);
  3717. }
  3718. }
  3719. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  3720. if (isFn)
  3721. handler.call(self, arg1, arg2, arg3);
  3722. else {
  3723. var len = handler.length;
  3724. var listeners = arrayClone(handler, len);
  3725. for (var i = 0; i < len; ++i)
  3726. listeners[i].call(self, arg1, arg2, arg3);
  3727. }
  3728. }
  3729. function emitMany(handler, isFn, self, args) {
  3730. if (isFn)
  3731. handler.apply(self, args);
  3732. else {
  3733. var len = handler.length;
  3734. var listeners = arrayClone(handler, len);
  3735. for (var i = 0; i < len; ++i)
  3736. listeners[i].apply(self, args);
  3737. }
  3738. }
  3739. EventEmitter.prototype.emit = function emit(type) {
  3740. var er, handler, len, args, i, events;
  3741. var doError = (type === 'error');
  3742. events = this._events;
  3743. if (events)
  3744. doError = (doError && events.error == null);
  3745. else if (!doError)
  3746. return false;
  3747. // If there is no 'error' event listener then throw.
  3748. if (doError) {
  3749. if (arguments.length > 1)
  3750. er = arguments[1];
  3751. if (er instanceof Error) {
  3752. throw er; // Unhandled 'error' event
  3753. } else {
  3754. // At least give some kind of context to the user
  3755. var err = new Error('Unhandled "error" event. (' + er + ')');
  3756. err.context = er;
  3757. throw err;
  3758. }
  3759. return false;
  3760. }
  3761. handler = events[type];
  3762. if (!handler)
  3763. return false;
  3764. var isFn = typeof handler === 'function';
  3765. len = arguments.length;
  3766. switch (len) {
  3767. // fast cases
  3768. case 1:
  3769. emitNone(handler, isFn, this);
  3770. break;
  3771. case 2:
  3772. emitOne(handler, isFn, this, arguments[1]);
  3773. break;
  3774. case 3:
  3775. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  3776. break;
  3777. case 4:
  3778. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  3779. break;
  3780. // slower
  3781. default:
  3782. args = new Array(len - 1);
  3783. for (i = 1; i < len; i++)
  3784. args[i - 1] = arguments[i];
  3785. emitMany(handler, isFn, this, args);
  3786. }
  3787. return true;
  3788. };
  3789. function _addListener(target, type, listener, prepend) {
  3790. var m;
  3791. var events;
  3792. var existing;
  3793. if (typeof listener !== 'function')
  3794. throw new TypeError('"listener" argument must be a function');
  3795. events = target._events;
  3796. if (!events) {
  3797. events = target._events = objectCreate(null);
  3798. target._eventsCount = 0;
  3799. } else {
  3800. // To avoid recursion in the case that type === "newListener"! Before
  3801. // adding it to the listeners, first emit "newListener".
  3802. if (events.newListener) {
  3803. target.emit('newListener', type,
  3804. listener.listener ? listener.listener : listener);
  3805. // Re-assign `events` because a newListener handler could have caused the
  3806. // this._events to be assigned to a new object
  3807. events = target._events;
  3808. }
  3809. existing = events[type];
  3810. }
  3811. if (!existing) {
  3812. // Optimize the case of one listener. Don't need the extra array object.
  3813. existing = events[type] = listener;
  3814. ++target._eventsCount;
  3815. } else {
  3816. if (typeof existing === 'function') {
  3817. // Adding the second element, need to change to array.
  3818. existing = events[type] =
  3819. prepend ? [listener, existing] : [existing, listener];
  3820. } else {
  3821. // If we've already got an array, just append.
  3822. if (prepend) {
  3823. existing.unshift(listener);
  3824. } else {
  3825. existing.push(listener);
  3826. }
  3827. }
  3828. // Check for listener leak
  3829. if (!existing.warned) {
  3830. m = $getMaxListeners(target);
  3831. if (m && m > 0 && existing.length > m) {
  3832. existing.warned = true;
  3833. var w = new Error('Possible EventEmitter memory leak detected. ' +
  3834. existing.length + ' "' + String(type) + '" listeners ' +
  3835. 'added. Use emitter.setMaxListeners() to ' +
  3836. 'increase limit.');
  3837. w.name = 'MaxListenersExceededWarning';
  3838. w.emitter = target;
  3839. w.type = type;
  3840. w.count = existing.length;
  3841. if (typeof console === 'object' && console.warn) {
  3842. console.warn('%s: %s', w.name, w.message);
  3843. }
  3844. }
  3845. }
  3846. }
  3847. return target;
  3848. }
  3849. EventEmitter.prototype.addListener = function addListener(type, listener) {
  3850. return _addListener(this, type, listener, false);
  3851. };
  3852. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  3853. EventEmitter.prototype.prependListener =
  3854. function prependListener(type, listener) {
  3855. return _addListener(this, type, listener, true);
  3856. };
  3857. function onceWrapper() {
  3858. if (!this.fired) {
  3859. this.target.removeListener(this.type, this.wrapFn);
  3860. this.fired = true;
  3861. switch (arguments.length) {
  3862. case 0:
  3863. return this.listener.call(this.target);
  3864. case 1:
  3865. return this.listener.call(this.target, arguments[0]);
  3866. case 2:
  3867. return this.listener.call(this.target, arguments[0], arguments[1]);
  3868. case 3:
  3869. return this.listener.call(this.target, arguments[0], arguments[1],
  3870. arguments[2]);
  3871. default:
  3872. var args = new Array(arguments.length);
  3873. for (var i = 0; i < args.length; ++i)
  3874. args[i] = arguments[i];
  3875. this.listener.apply(this.target, args);
  3876. }
  3877. }
  3878. }
  3879. function _onceWrap(target, type, listener) {
  3880. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  3881. var wrapped = bind.call(onceWrapper, state);
  3882. wrapped.listener = listener;
  3883. state.wrapFn = wrapped;
  3884. return wrapped;
  3885. }
  3886. EventEmitter.prototype.once = function once(type, listener) {
  3887. if (typeof listener !== 'function')
  3888. throw new TypeError('"listener" argument must be a function');
  3889. this.on(type, _onceWrap(this, type, listener));
  3890. return this;
  3891. };
  3892. EventEmitter.prototype.prependOnceListener =
  3893. function prependOnceListener(type, listener) {
  3894. if (typeof listener !== 'function')
  3895. throw new TypeError('"listener" argument must be a function');
  3896. this.prependListener(type, _onceWrap(this, type, listener));
  3897. return this;
  3898. };
  3899. // Emits a 'removeListener' event if and only if the listener was removed.
  3900. EventEmitter.prototype.removeListener =
  3901. function removeListener(type, listener) {
  3902. var list, events, position, i, originalListener;
  3903. if (typeof listener !== 'function')
  3904. throw new TypeError('"listener" argument must be a function');
  3905. events = this._events;
  3906. if (!events)
  3907. return this;
  3908. list = events[type];
  3909. if (!list)
  3910. return this;
  3911. if (list === listener || list.listener === listener) {
  3912. if (--this._eventsCount === 0)
  3913. this._events = objectCreate(null);
  3914. else {
  3915. delete events[type];
  3916. if (events.removeListener)
  3917. this.emit('removeListener', type, list.listener || listener);
  3918. }
  3919. } else if (typeof list !== 'function') {
  3920. position = -1;
  3921. for (i = list.length - 1; i >= 0; i--) {
  3922. if (list[i] === listener || list[i].listener === listener) {
  3923. originalListener = list[i].listener;
  3924. position = i;
  3925. break;
  3926. }
  3927. }
  3928. if (position < 0)
  3929. return this;
  3930. if (position === 0)
  3931. list.shift();
  3932. else
  3933. spliceOne(list, position);
  3934. if (list.length === 1)
  3935. events[type] = list[0];
  3936. if (events.removeListener)
  3937. this.emit('removeListener', type, originalListener || listener);
  3938. }
  3939. return this;
  3940. };
  3941. EventEmitter.prototype.removeAllListeners =
  3942. function removeAllListeners(type) {
  3943. var listeners, events, i;
  3944. events = this._events;
  3945. if (!events)
  3946. return this;
  3947. // not listening for removeListener, no need to emit
  3948. if (!events.removeListener) {
  3949. if (arguments.length === 0) {
  3950. this._events = objectCreate(null);
  3951. this._eventsCount = 0;
  3952. } else if (events[type]) {
  3953. if (--this._eventsCount === 0)
  3954. this._events = objectCreate(null);
  3955. else
  3956. delete events[type];
  3957. }
  3958. return this;
  3959. }
  3960. // emit removeListener for all listeners on all events
  3961. if (arguments.length === 0) {
  3962. var keys = objectKeys(events);
  3963. var key;
  3964. for (i = 0; i < keys.length; ++i) {
  3965. key = keys[i];
  3966. if (key === 'removeListener') continue;
  3967. this.removeAllListeners(key);
  3968. }
  3969. this.removeAllListeners('removeListener');
  3970. this._events = objectCreate(null);
  3971. this._eventsCount = 0;
  3972. return this;
  3973. }
  3974. listeners = events[type];
  3975. if (typeof listeners === 'function') {
  3976. this.removeListener(type, listeners);
  3977. } else if (listeners) {
  3978. // LIFO order
  3979. for (i = listeners.length - 1; i >= 0; i--) {
  3980. this.removeListener(type, listeners[i]);
  3981. }
  3982. }
  3983. return this;
  3984. };
  3985. function _listeners(target, type, unwrap) {
  3986. var events = target._events;
  3987. if (!events)
  3988. return [];
  3989. var evlistener = events[type];
  3990. if (!evlistener)
  3991. return [];
  3992. if (typeof evlistener === 'function')
  3993. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  3994. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  3995. }
  3996. EventEmitter.prototype.listeners = function listeners(type) {
  3997. return _listeners(this, type, true);
  3998. };
  3999. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4000. return _listeners(this, type, false);
  4001. };
  4002. EventEmitter.listenerCount = function(emitter, type) {
  4003. if (typeof emitter.listenerCount === 'function') {
  4004. return emitter.listenerCount(type);
  4005. } else {
  4006. return listenerCount.call(emitter, type);
  4007. }
  4008. };
  4009. EventEmitter.prototype.listenerCount = listenerCount;
  4010. function listenerCount(type) {
  4011. var events = this._events;
  4012. if (events) {
  4013. var evlistener = events[type];
  4014. if (typeof evlistener === 'function') {
  4015. return 1;
  4016. } else if (evlistener) {
  4017. return evlistener.length;
  4018. }
  4019. }
  4020. return 0;
  4021. }
  4022. EventEmitter.prototype.eventNames = function eventNames() {
  4023. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  4024. };
  4025. // About 1.5x faster than the two-arg version of Array#splice().
  4026. function spliceOne(list, index) {
  4027. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  4028. list[i] = list[k];
  4029. list.pop();
  4030. }
  4031. function arrayClone(arr, n) {
  4032. var copy = new Array(n);
  4033. for (var i = 0; i < n; ++i)
  4034. copy[i] = arr[i];
  4035. return copy;
  4036. }
  4037. function unwrapListeners(arr) {
  4038. var ret = new Array(arr.length);
  4039. for (var i = 0; i < ret.length; ++i) {
  4040. ret[i] = arr[i].listener || arr[i];
  4041. }
  4042. return ret;
  4043. }
  4044. function objectCreatePolyfill(proto) {
  4045. var F = function() {};
  4046. F.prototype = proto;
  4047. return new F;
  4048. }
  4049. function objectKeysPolyfill(obj) {
  4050. var keys = [];
  4051. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  4052. keys.push(k);
  4053. }
  4054. return k;
  4055. }
  4056. function functionBindPolyfill(context) {
  4057. var fn = this;
  4058. return function () {
  4059. return fn.apply(context, arguments);
  4060. };
  4061. }
  4062. },{}],14:[function(require,module,exports){
  4063. (function (Buffer){
  4064. // Copyright Joyent, Inc. and other Node contributors.
  4065. //
  4066. // Permission is hereby granted, free of charge, to any person obtaining a
  4067. // copy of this software and associated documentation files (the
  4068. // "Software"), to deal in the Software without restriction, including
  4069. // without limitation the rights to use, copy, modify, merge, publish,
  4070. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4071. // persons to whom the Software is furnished to do so, subject to the
  4072. // following conditions:
  4073. //
  4074. // The above copyright notice and this permission notice shall be included
  4075. // in all copies or substantial portions of the Software.
  4076. //
  4077. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4078. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4079. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4080. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4081. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4082. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4083. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4084. // NOTE: These type checking functions intentionally don't use `instanceof`
  4085. // because it is fragile and can be easily faked with `Object.create()`.
  4086. function isArray(arg) {
  4087. if (Array.isArray) {
  4088. return Array.isArray(arg);
  4089. }
  4090. return objectToString(arg) === '[object Array]';
  4091. }
  4092. exports.isArray = isArray;
  4093. function isBoolean(arg) {
  4094. return typeof arg === 'boolean';
  4095. }
  4096. exports.isBoolean = isBoolean;
  4097. function isNull(arg) {
  4098. return arg === null;
  4099. }
  4100. exports.isNull = isNull;
  4101. function isNullOrUndefined(arg) {
  4102. return arg == null;
  4103. }
  4104. exports.isNullOrUndefined = isNullOrUndefined;
  4105. function isNumber(arg) {
  4106. return typeof arg === 'number';
  4107. }
  4108. exports.isNumber = isNumber;
  4109. function isString(arg) {
  4110. return typeof arg === 'string';
  4111. }
  4112. exports.isString = isString;
  4113. function isSymbol(arg) {
  4114. return typeof arg === 'symbol';
  4115. }
  4116. exports.isSymbol = isSymbol;
  4117. function isUndefined(arg) {
  4118. return arg === void 0;
  4119. }
  4120. exports.isUndefined = isUndefined;
  4121. function isRegExp(re) {
  4122. return objectToString(re) === '[object RegExp]';
  4123. }
  4124. exports.isRegExp = isRegExp;
  4125. function isObject(arg) {
  4126. return typeof arg === 'object' && arg !== null;
  4127. }
  4128. exports.isObject = isObject;
  4129. function isDate(d) {
  4130. return objectToString(d) === '[object Date]';
  4131. }
  4132. exports.isDate = isDate;
  4133. function isError(e) {
  4134. return (objectToString(e) === '[object Error]' || e instanceof Error);
  4135. }
  4136. exports.isError = isError;
  4137. function isFunction(arg) {
  4138. return typeof arg === 'function';
  4139. }
  4140. exports.isFunction = isFunction;
  4141. function isPrimitive(arg) {
  4142. return arg === null ||
  4143. typeof arg === 'boolean' ||
  4144. typeof arg === 'number' ||
  4145. typeof arg === 'string' ||
  4146. typeof arg === 'symbol' || // ES6 symbol
  4147. typeof arg === 'undefined';
  4148. }
  4149. exports.isPrimitive = isPrimitive;
  4150. exports.isBuffer = Buffer.isBuffer;
  4151. function objectToString(o) {
  4152. return Object.prototype.toString.call(o);
  4153. }
  4154. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  4155. },{"../../is-buffer/index.js":81}],15:[function(require,module,exports){
  4156. 'use strict';
  4157. var copy = require('es5-ext/object/copy')
  4158. , normalizeOptions = require('es5-ext/object/normalize-options')
  4159. , ensureCallable = require('es5-ext/object/valid-callable')
  4160. , map = require('es5-ext/object/map')
  4161. , callable = require('es5-ext/object/valid-callable')
  4162. , validValue = require('es5-ext/object/valid-value')
  4163. , bind = Function.prototype.bind, defineProperty = Object.defineProperty
  4164. , hasOwnProperty = Object.prototype.hasOwnProperty
  4165. , define;
  4166. define = function (name, desc, options) {
  4167. var value = validValue(desc) && callable(desc.value), dgs;
  4168. dgs = copy(desc);
  4169. delete dgs.writable;
  4170. delete dgs.value;
  4171. dgs.get = function () {
  4172. if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
  4173. desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
  4174. defineProperty(this, name, desc);
  4175. return this[name];
  4176. };
  4177. return dgs;
  4178. };
  4179. module.exports = function (props/*, options*/) {
  4180. var options = normalizeOptions(arguments[1]);
  4181. if (options.resolveContext != null) ensureCallable(options.resolveContext);
  4182. return map(props, function (desc, name) { return define(name, desc, options); });
  4183. };
  4184. },{"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){
  4185. 'use strict';
  4186. var assign = require('es5-ext/object/assign')
  4187. , normalizeOpts = require('es5-ext/object/normalize-options')
  4188. , isCallable = require('es5-ext/object/is-callable')
  4189. , contains = require('es5-ext/string/#/contains')
  4190. , d;
  4191. d = module.exports = function (dscr, value/*, options*/) {
  4192. var c, e, w, options, desc;
  4193. if ((arguments.length < 2) || (typeof dscr !== 'string')) {
  4194. options = value;
  4195. value = dscr;
  4196. dscr = null;
  4197. } else {
  4198. options = arguments[2];
  4199. }
  4200. if (dscr == null) {
  4201. c = w = true;
  4202. e = false;
  4203. } else {
  4204. c = contains.call(dscr, 'c');
  4205. e = contains.call(dscr, 'e');
  4206. w = contains.call(dscr, 'w');
  4207. }
  4208. desc = { value: value, configurable: c, enumerable: e, writable: w };
  4209. return !options ? desc : assign(normalizeOpts(options), desc);
  4210. };
  4211. d.gs = function (dscr, get, set/*, options*/) {
  4212. var c, e, options, desc;
  4213. if (typeof dscr !== 'string') {
  4214. options = set;
  4215. set = get;
  4216. get = dscr;
  4217. dscr = null;
  4218. } else {
  4219. options = arguments[3];
  4220. }
  4221. if (get == null) {
  4222. get = undefined;
  4223. } else if (!isCallable(get)) {
  4224. options = get;
  4225. get = set = undefined;
  4226. } else if (set == null) {
  4227. set = undefined;
  4228. } else if (!isCallable(set)) {
  4229. options = set;
  4230. set = undefined;
  4231. }
  4232. if (dscr == null) {
  4233. c = true;
  4234. e = false;
  4235. } else {
  4236. c = contains.call(dscr, 'c');
  4237. e = contains.call(dscr, 'e');
  4238. }
  4239. desc = { get: get, set: set, configurable: c, enumerable: e };
  4240. return !options ? desc : assign(normalizeOpts(options), desc);
  4241. };
  4242. },{"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){
  4243. (function (process,Buffer){
  4244. var stream = require('readable-stream')
  4245. var eos = require('end-of-stream')
  4246. var inherits = require('inherits')
  4247. var shift = require('stream-shift')
  4248. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  4249. ? Buffer.from([0])
  4250. : new Buffer([0])
  4251. var onuncork = function(self, fn) {
  4252. if (self._corked) self.once('uncork', fn)
  4253. else fn()
  4254. }
  4255. var autoDestroy = function (self, err) {
  4256. if (self._autoDestroy) self.destroy(err)
  4257. }
  4258. var destroyer = function(self, end) {
  4259. return function(err) {
  4260. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  4261. else if (end && !self._ended) self.end()
  4262. }
  4263. }
  4264. var end = function(ws, fn) {
  4265. if (!ws) return fn()
  4266. if (ws._writableState && ws._writableState.finished) return fn()
  4267. if (ws._writableState) return ws.end(fn)
  4268. ws.end()
  4269. fn()
  4270. }
  4271. var toStreams2 = function(rs) {
  4272. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  4273. }
  4274. var Duplexify = function(writable, readable, opts) {
  4275. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  4276. stream.Duplex.call(this, opts)
  4277. this._writable = null
  4278. this._readable = null
  4279. this._readable2 = null
  4280. this._autoDestroy = !opts || opts.autoDestroy !== false
  4281. this._forwardDestroy = !opts || opts.destroy !== false
  4282. this._forwardEnd = !opts || opts.end !== false
  4283. this._corked = 1 // start corked
  4284. this._ondrain = null
  4285. this._drained = false
  4286. this._forwarding = false
  4287. this._unwrite = null
  4288. this._unread = null
  4289. this._ended = false
  4290. this.destroyed = false
  4291. if (writable) this.setWritable(writable)
  4292. if (readable) this.setReadable(readable)
  4293. }
  4294. inherits(Duplexify, stream.Duplex)
  4295. Duplexify.obj = function(writable, readable, opts) {
  4296. if (!opts) opts = {}
  4297. opts.objectMode = true
  4298. opts.highWaterMark = 16
  4299. return new Duplexify(writable, readable, opts)
  4300. }
  4301. Duplexify.prototype.cork = function() {
  4302. if (++this._corked === 1) this.emit('cork')
  4303. }
  4304. Duplexify.prototype.uncork = function() {
  4305. if (this._corked && --this._corked === 0) this.emit('uncork')
  4306. }
  4307. Duplexify.prototype.setWritable = function(writable) {
  4308. if (this._unwrite) this._unwrite()
  4309. if (this.destroyed) {
  4310. if (writable && writable.destroy) writable.destroy()
  4311. return
  4312. }
  4313. if (writable === null || writable === false) {
  4314. this.end()
  4315. return
  4316. }
  4317. var self = this
  4318. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  4319. var ondrain = function() {
  4320. var ondrain = self._ondrain
  4321. self._ondrain = null
  4322. if (ondrain) ondrain()
  4323. }
  4324. var clear = function() {
  4325. self._writable.removeListener('drain', ondrain)
  4326. unend()
  4327. }
  4328. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  4329. this._writable = writable
  4330. this._writable.on('drain', ondrain)
  4331. this._unwrite = clear
  4332. this.uncork() // always uncork setWritable
  4333. }
  4334. Duplexify.prototype.setReadable = function(readable) {
  4335. if (this._unread) this._unread()
  4336. if (this.destroyed) {
  4337. if (readable && readable.destroy) readable.destroy()
  4338. return
  4339. }
  4340. if (readable === null || readable === false) {
  4341. this.push(null)
  4342. this.resume()
  4343. return
  4344. }
  4345. var self = this
  4346. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  4347. var onreadable = function() {
  4348. self._forward()
  4349. }
  4350. var onend = function() {
  4351. self.push(null)
  4352. }
  4353. var clear = function() {
  4354. self._readable2.removeListener('readable', onreadable)
  4355. self._readable2.removeListener('end', onend)
  4356. unend()
  4357. }
  4358. this._drained = true
  4359. this._readable = readable
  4360. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  4361. this._readable2.on('readable', onreadable)
  4362. this._readable2.on('end', onend)
  4363. this._unread = clear
  4364. this._forward()
  4365. }
  4366. Duplexify.prototype._read = function() {
  4367. this._drained = true
  4368. this._forward()
  4369. }
  4370. Duplexify.prototype._forward = function() {
  4371. if (this._forwarding || !this._readable2 || !this._drained) return
  4372. this._forwarding = true
  4373. var data
  4374. while (this._drained && (data = shift(this._readable2)) !== null) {
  4375. if (this.destroyed) continue
  4376. this._drained = this.push(data)
  4377. }
  4378. this._forwarding = false
  4379. }
  4380. Duplexify.prototype.destroy = function(err) {
  4381. if (this.destroyed) return
  4382. this.destroyed = true
  4383. var self = this
  4384. process.nextTick(function() {
  4385. self._destroy(err)
  4386. })
  4387. }
  4388. Duplexify.prototype._destroy = function(err) {
  4389. if (err) {
  4390. var ondrain = this._ondrain
  4391. this._ondrain = null
  4392. if (ondrain) ondrain(err)
  4393. else this.emit('error', err)
  4394. }
  4395. if (this._forwardDestroy) {
  4396. if (this._readable && this._readable.destroy) this._readable.destroy()
  4397. if (this._writable && this._writable.destroy) this._writable.destroy()
  4398. }
  4399. console.log(`Duplexify.prototype._destroy`)
  4400. this.emit('close')
  4401. }
  4402. Duplexify.prototype._write = function(data, enc, cb) {
  4403. if (this.destroyed) return cb()
  4404. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  4405. if (data === SIGNAL_FLUSH) return this._finish(cb)
  4406. if (!this._writable) return cb()
  4407. if (this._writable.write(data) === false) this._ondrain = cb
  4408. else cb()
  4409. }
  4410. Duplexify.prototype._finish = function(cb) {
  4411. var self = this
  4412. this.emit('preend')
  4413. onuncork(this, function() {
  4414. end(self._forwardEnd && self._writable, function() {
  4415. // haxx to not emit prefinish twice
  4416. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  4417. self.emit('prefinish')
  4418. onuncork(self, cb)
  4419. })
  4420. })
  4421. }
  4422. Duplexify.prototype.end = function(data, enc, cb) {
  4423. if (typeof data === 'function') return this.end(null, null, data)
  4424. if (typeof enc === 'function') return this.end(data, null, enc)
  4425. this._ended = true
  4426. if (data) this.write(data)
  4427. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  4428. return stream.Writable.prototype.end.call(this, cb)
  4429. }
  4430. module.exports = Duplexify
  4431. }).call(this,require('_process'),require("buffer").Buffer)
  4432. },{"_process":92,"buffer":12,"end-of-stream":18,"inherits":80,"readable-stream":108,"stream-shift":111}],18:[function(require,module,exports){
  4433. var once = require('once');
  4434. var noop = function() {};
  4435. var isRequest = function(stream) {
  4436. return stream.setHeader && typeof stream.abort === 'function';
  4437. };
  4438. var isChildProcess = function(stream) {
  4439. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  4440. };
  4441. var eos = function(stream, opts, callback) {
  4442. if (typeof opts === 'function') return eos(stream, null, opts);
  4443. if (!opts) opts = {};
  4444. callback = once(callback || noop);
  4445. var ws = stream._writableState;
  4446. var rs = stream._readableState;
  4447. var readable = opts.readable || (opts.readable !== false && stream.readable);
  4448. var writable = opts.writable || (opts.writable !== false && stream.writable);
  4449. var onlegacyfinish = function() {
  4450. if (!stream.writable) onfinish();
  4451. };
  4452. var onfinish = function() {
  4453. writable = false;
  4454. if (!readable) callback.call(stream);
  4455. };
  4456. var onend = function() {
  4457. readable = false;
  4458. if (!writable) callback.call(stream);
  4459. };
  4460. var onexit = function(exitCode) {
  4461. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  4462. };
  4463. var onerror = function(err) {
  4464. callback.call(stream, err);
  4465. };
  4466. var onclose = function() {
  4467. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  4468. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  4469. };
  4470. var onrequest = function() {
  4471. stream.req.on('finish', onfinish);
  4472. };
  4473. if (isRequest(stream)) {
  4474. stream.on('complete', onfinish);
  4475. stream.on('abort', onclose);
  4476. if (stream.req) onrequest();
  4477. else stream.on('request', onrequest);
  4478. } else if (writable && !ws) { // legacy streams
  4479. stream.on('end', onlegacyfinish);
  4480. stream.on('close', onlegacyfinish);
  4481. }
  4482. if (isChildProcess(stream)) stream.on('exit', onexit);
  4483. stream.on('end', onend);
  4484. stream.on('finish', onfinish);
  4485. if (opts.error !== false) stream.on('error', onerror);
  4486. stream.on('close', onclose);
  4487. return function() {
  4488. stream.removeListener('complete', onfinish);
  4489. stream.removeListener('abort', onclose);
  4490. stream.removeListener('request', onrequest);
  4491. if (stream.req) stream.req.removeListener('finish', onfinish);
  4492. stream.removeListener('end', onlegacyfinish);
  4493. stream.removeListener('close', onlegacyfinish);
  4494. stream.removeListener('finish', onfinish);
  4495. stream.removeListener('exit', onexit);
  4496. stream.removeListener('end', onend);
  4497. stream.removeListener('error', onerror);
  4498. stream.removeListener('close', onclose);
  4499. };
  4500. };
  4501. module.exports = eos;
  4502. },{"once":90}],19:[function(require,module,exports){
  4503. // Inspired by Google Closure:
  4504. // http://closure-library.googlecode.com/svn/docs/
  4505. // closure_goog_array_array.js.html#goog.array.clear
  4506. "use strict";
  4507. var value = require("../../object/valid-value");
  4508. module.exports = function () {
  4509. value(this).length = 0;
  4510. return this;
  4511. };
  4512. },{"../../object/valid-value":55}],20:[function(require,module,exports){
  4513. "use strict";
  4514. var numberIsNaN = require("../../number/is-nan")
  4515. , toPosInt = require("../../number/to-pos-integer")
  4516. , value = require("../../object/valid-value")
  4517. , indexOf = Array.prototype.indexOf
  4518. , objHasOwnProperty = Object.prototype.hasOwnProperty
  4519. , abs = Math.abs
  4520. , floor = Math.floor;
  4521. module.exports = function (searchElement /*, fromIndex*/) {
  4522. var i, length, fromIndex, val;
  4523. if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
  4524. length = toPosInt(value(this).length);
  4525. fromIndex = arguments[1];
  4526. if (isNaN(fromIndex)) fromIndex = 0;
  4527. else if (fromIndex >= 0) fromIndex = floor(fromIndex);
  4528. else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
  4529. for (i = fromIndex; i < length; ++i) {
  4530. if (objHasOwnProperty.call(this, i)) {
  4531. val = this[i];
  4532. if (numberIsNaN(val)) return i; // Jslint: ignore
  4533. }
  4534. }
  4535. return -1;
  4536. };
  4537. },{"../../number/is-nan":30,"../../number/to-pos-integer":34,"../../object/valid-value":55}],21:[function(require,module,exports){
  4538. "use strict";
  4539. module.exports = require("./is-implemented")()
  4540. ? Array.from
  4541. : require("./shim");
  4542. },{"./is-implemented":22,"./shim":23}],22:[function(require,module,exports){
  4543. "use strict";
  4544. module.exports = function () {
  4545. var from = Array.from, arr, result;
  4546. if (typeof from !== "function") return false;
  4547. arr = ["raz", "dwa"];
  4548. result = from(arr);
  4549. return Boolean(result && (result !== arr) && (result[1] === "dwa"));
  4550. };
  4551. },{}],23:[function(require,module,exports){
  4552. "use strict";
  4553. var iteratorSymbol = require("es6-symbol").iterator
  4554. , isArguments = require("../../function/is-arguments")
  4555. , isFunction = require("../../function/is-function")
  4556. , toPosInt = require("../../number/to-pos-integer")
  4557. , callable = require("../../object/valid-callable")
  4558. , validValue = require("../../object/valid-value")
  4559. , isValue = require("../../object/is-value")
  4560. , isString = require("../../string/is-string")
  4561. , isArray = Array.isArray
  4562. , call = Function.prototype.call
  4563. , desc = { configurable: true, enumerable: true, writable: true, value: null }
  4564. , defineProperty = Object.defineProperty;
  4565. // eslint-disable-next-line complexity, max-lines-per-function
  4566. module.exports = function (arrayLike /*, mapFn, thisArg*/) {
  4567. var mapFn = arguments[1]
  4568. , thisArg = arguments[2]
  4569. , Context
  4570. , i
  4571. , j
  4572. , arr
  4573. , length
  4574. , code
  4575. , iterator
  4576. , result
  4577. , getIterator
  4578. , value;
  4579. arrayLike = Object(validValue(arrayLike));
  4580. if (isValue(mapFn)) callable(mapFn);
  4581. if (!this || this === Array || !isFunction(this)) {
  4582. // Result: Plain array
  4583. if (!mapFn) {
  4584. if (isArguments(arrayLike)) {
  4585. // Source: Arguments
  4586. length = arrayLike.length;
  4587. if (length !== 1) return Array.apply(null, arrayLike);
  4588. arr = new Array(1);
  4589. arr[0] = arrayLike[0];
  4590. return arr;
  4591. }
  4592. if (isArray(arrayLike)) {
  4593. // Source: Array
  4594. arr = new Array(length = arrayLike.length);
  4595. for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
  4596. return arr;
  4597. }
  4598. }
  4599. arr = [];
  4600. } else {
  4601. // Result: Non plain array
  4602. Context = this;
  4603. }
  4604. if (!isArray(arrayLike)) {
  4605. if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
  4606. // Source: Iterator
  4607. iterator = callable(getIterator).call(arrayLike);
  4608. if (Context) arr = new Context();
  4609. result = iterator.next();
  4610. i = 0;
  4611. while (!result.done) {
  4612. value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
  4613. if (Context) {
  4614. desc.value = value;
  4615. defineProperty(arr, i, desc);
  4616. } else {
  4617. arr[i] = value;
  4618. }
  4619. result = iterator.next();
  4620. ++i;
  4621. }
  4622. length = i;
  4623. } else if (isString(arrayLike)) {
  4624. // Source: String
  4625. length = arrayLike.length;
  4626. if (Context) arr = new Context();
  4627. for (i = 0, j = 0; i < length; ++i) {
  4628. value = arrayLike[i];
  4629. if (i + 1 < length) {
  4630. code = value.charCodeAt(0);
  4631. // eslint-disable-next-line max-depth
  4632. if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
  4633. }
  4634. value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
  4635. if (Context) {
  4636. desc.value = value;
  4637. defineProperty(arr, j, desc);
  4638. } else {
  4639. arr[j] = value;
  4640. }
  4641. ++j;
  4642. }
  4643. length = j;
  4644. }
  4645. }
  4646. if (length === undefined) {
  4647. // Source: array or array-like
  4648. length = toPosInt(arrayLike.length);
  4649. if (Context) arr = new Context(length);
  4650. for (i = 0; i < length; ++i) {
  4651. value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
  4652. if (Context) {
  4653. desc.value = value;
  4654. defineProperty(arr, i, desc);
  4655. } else {
  4656. arr[i] = value;
  4657. }
  4658. }
  4659. }
  4660. if (Context) {
  4661. desc.value = null;
  4662. arr.length = length;
  4663. }
  4664. return arr;
  4665. };
  4666. },{"../../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){
  4667. "use strict";
  4668. var objToString = Object.prototype.toString
  4669. , id = objToString.call(
  4670. (function () {
  4671. return arguments;
  4672. })()
  4673. );
  4674. module.exports = function (value) {
  4675. return objToString.call(value) === id;
  4676. };
  4677. },{}],25:[function(require,module,exports){
  4678. "use strict";
  4679. var objToString = Object.prototype.toString, id = objToString.call(require("./noop"));
  4680. module.exports = function (value) {
  4681. return typeof value === "function" && objToString.call(value) === id;
  4682. };
  4683. },{"./noop":26}],26:[function(require,module,exports){
  4684. "use strict";
  4685. // eslint-disable-next-line no-empty-function
  4686. module.exports = function () {};
  4687. },{}],27:[function(require,module,exports){
  4688. "use strict";
  4689. module.exports = require("./is-implemented")()
  4690. ? Math.sign
  4691. : require("./shim");
  4692. },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){
  4693. "use strict";
  4694. module.exports = function () {
  4695. var sign = Math.sign;
  4696. if (typeof sign !== "function") return false;
  4697. return (sign(10) === 1) && (sign(-20) === -1);
  4698. };
  4699. },{}],29:[function(require,module,exports){
  4700. "use strict";
  4701. module.exports = function (value) {
  4702. value = Number(value);
  4703. if (isNaN(value) || (value === 0)) return value;
  4704. return value > 0 ? 1 : -1;
  4705. };
  4706. },{}],30:[function(require,module,exports){
  4707. "use strict";
  4708. module.exports = require("./is-implemented")()
  4709. ? Number.isNaN
  4710. : require("./shim");
  4711. },{"./is-implemented":31,"./shim":32}],31:[function(require,module,exports){
  4712. "use strict";
  4713. module.exports = function () {
  4714. var numberIsNaN = Number.isNaN;
  4715. if (typeof numberIsNaN !== "function") return false;
  4716. return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
  4717. };
  4718. },{}],32:[function(require,module,exports){
  4719. "use strict";
  4720. module.exports = function (value) {
  4721. // eslint-disable-next-line no-self-compare
  4722. return value !== value;
  4723. };
  4724. },{}],33:[function(require,module,exports){
  4725. "use strict";
  4726. var sign = require("../math/sign")
  4727. , abs = Math.abs, floor = Math.floor;
  4728. module.exports = function (value) {
  4729. if (isNaN(value)) return 0;
  4730. value = Number(value);
  4731. if ((value === 0) || !isFinite(value)) return value;
  4732. return sign(value) * floor(abs(value));
  4733. };
  4734. },{"../math/sign":27}],34:[function(require,module,exports){
  4735. "use strict";
  4736. var toInteger = require("./to-integer")
  4737. , max = Math.max;
  4738. module.exports = function (value) {
  4739. return max(0, toInteger(value));
  4740. };
  4741. },{"./to-integer":33}],35:[function(require,module,exports){
  4742. // Internal method, used by iteration functions.
  4743. // Calls a function for each key-value pair found in object
  4744. // Optionally takes compareFn to iterate object in specific order
  4745. "use strict";
  4746. var callable = require("./valid-callable")
  4747. , value = require("./valid-value")
  4748. , bind = Function.prototype.bind
  4749. , call = Function.prototype.call
  4750. , keys = Object.keys
  4751. , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
  4752. module.exports = function (method, defVal) {
  4753. return function (obj, cb /*, thisArg, compareFn*/) {
  4754. var list, thisArg = arguments[2], compareFn = arguments[3];
  4755. obj = Object(value(obj));
  4756. callable(cb);
  4757. list = keys(obj);
  4758. if (compareFn) {
  4759. list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
  4760. }
  4761. if (typeof method !== "function") method = list[method];
  4762. return call.call(method, list, function (key, index) {
  4763. if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
  4764. return call.call(cb, thisArg, obj[key], key, obj, index);
  4765. });
  4766. };
  4767. };
  4768. },{"./valid-callable":54,"./valid-value":55}],36:[function(require,module,exports){
  4769. "use strict";
  4770. module.exports = require("./is-implemented")()
  4771. ? Object.assign
  4772. : require("./shim");
  4773. },{"./is-implemented":37,"./shim":38}],37:[function(require,module,exports){
  4774. "use strict";
  4775. module.exports = function () {
  4776. var assign = Object.assign, obj;
  4777. if (typeof assign !== "function") return false;
  4778. obj = { foo: "raz" };
  4779. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  4780. return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
  4781. };
  4782. },{}],38:[function(require,module,exports){
  4783. "use strict";
  4784. var keys = require("../keys")
  4785. , value = require("../valid-value")
  4786. , max = Math.max;
  4787. module.exports = function (dest, src /*, …srcn*/) {
  4788. var error, i, length = max(arguments.length, 2), assign;
  4789. dest = Object(value(dest));
  4790. assign = function (key) {
  4791. try {
  4792. dest[key] = src[key];
  4793. } catch (e) {
  4794. if (!error) error = e;
  4795. }
  4796. };
  4797. for (i = 1; i < length; ++i) {
  4798. src = arguments[i];
  4799. keys(src).forEach(assign);
  4800. }
  4801. if (error !== undefined) throw error;
  4802. return dest;
  4803. };
  4804. },{"../keys":45,"../valid-value":55}],39:[function(require,module,exports){
  4805. "use strict";
  4806. var aFrom = require("../array/from")
  4807. , assign = require("./assign")
  4808. , value = require("./valid-value");
  4809. module.exports = function (obj/*, propertyNames, options*/) {
  4810. var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
  4811. if (copy !== obj && !propertyNames) return copy;
  4812. var result = {};
  4813. if (propertyNames) {
  4814. aFrom(propertyNames, function (propertyName) {
  4815. if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
  4816. });
  4817. } else {
  4818. assign(result, obj);
  4819. }
  4820. return result;
  4821. };
  4822. },{"../array/from":21,"./assign":36,"./valid-value":55}],40:[function(require,module,exports){
  4823. // Workaround for http://code.google.com/p/v8/issues/detail?id=2804
  4824. "use strict";
  4825. var create = Object.create, shim;
  4826. if (!require("./set-prototype-of/is-implemented")()) {
  4827. shim = require("./set-prototype-of/shim");
  4828. }
  4829. module.exports = (function () {
  4830. var nullObject, polyProps, desc;
  4831. if (!shim) return create;
  4832. if (shim.level !== 1) return create;
  4833. nullObject = {};
  4834. polyProps = {};
  4835. desc = {
  4836. configurable: false,
  4837. enumerable: false,
  4838. writable: true,
  4839. value: undefined
  4840. };
  4841. Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
  4842. if (name === "__proto__") {
  4843. polyProps[name] = {
  4844. configurable: true,
  4845. enumerable: false,
  4846. writable: true,
  4847. value: undefined
  4848. };
  4849. return;
  4850. }
  4851. polyProps[name] = desc;
  4852. });
  4853. Object.defineProperties(nullObject, polyProps);
  4854. Object.defineProperty(shim, "nullPolyfill", {
  4855. configurable: false,
  4856. enumerable: false,
  4857. writable: false,
  4858. value: nullObject
  4859. });
  4860. return function (prototype, props) {
  4861. return create(prototype === null ? nullObject : prototype, props);
  4862. };
  4863. }());
  4864. },{"./set-prototype-of/is-implemented":52,"./set-prototype-of/shim":53}],41:[function(require,module,exports){
  4865. "use strict";
  4866. module.exports = require("./_iterate")("forEach");
  4867. },{"./_iterate":35}],42:[function(require,module,exports){
  4868. // Deprecated
  4869. "use strict";
  4870. module.exports = function (obj) {
  4871. return typeof obj === "function";
  4872. };
  4873. },{}],43:[function(require,module,exports){
  4874. "use strict";
  4875. var isValue = require("./is-value");
  4876. var map = { function: true, object: true };
  4877. module.exports = function (value) {
  4878. return (isValue(value) && map[typeof value]) || false;
  4879. };
  4880. },{"./is-value":44}],44:[function(require,module,exports){
  4881. "use strict";
  4882. var _undefined = require("../function/noop")(); // Support ES3 engines
  4883. module.exports = function (val) {
  4884. return (val !== _undefined) && (val !== null);
  4885. };
  4886. },{"../function/noop":26}],45:[function(require,module,exports){
  4887. "use strict";
  4888. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  4889. },{"./is-implemented":46,"./shim":47}],46:[function(require,module,exports){
  4890. "use strict";
  4891. module.exports = function () {
  4892. try {
  4893. Object.keys("primitive");
  4894. return true;
  4895. } catch (e) {
  4896. return false;
  4897. }
  4898. };
  4899. },{}],47:[function(require,module,exports){
  4900. "use strict";
  4901. var isValue = require("../is-value");
  4902. var keys = Object.keys;
  4903. module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
  4904. },{"../is-value":44}],48:[function(require,module,exports){
  4905. "use strict";
  4906. var callable = require("./valid-callable")
  4907. , forEach = require("./for-each")
  4908. , call = Function.prototype.call;
  4909. module.exports = function (obj, cb /*, thisArg*/) {
  4910. var result = {}, thisArg = arguments[2];
  4911. callable(cb);
  4912. forEach(obj, function (value, key, targetObj, index) {
  4913. result[key] = call.call(cb, thisArg, value, key, targetObj, index);
  4914. });
  4915. return result;
  4916. };
  4917. },{"./for-each":41,"./valid-callable":54}],49:[function(require,module,exports){
  4918. "use strict";
  4919. var isValue = require("./is-value");
  4920. var forEach = Array.prototype.forEach, create = Object.create;
  4921. var process = function (src, obj) {
  4922. var key;
  4923. for (key in src) obj[key] = src[key];
  4924. };
  4925. // eslint-disable-next-line no-unused-vars
  4926. module.exports = function (opts1 /*, …options*/) {
  4927. var result = create(null);
  4928. forEach.call(arguments, function (options) {
  4929. if (!isValue(options)) return;
  4930. process(Object(options), result);
  4931. });
  4932. return result;
  4933. };
  4934. },{"./is-value":44}],50:[function(require,module,exports){
  4935. "use strict";
  4936. var forEach = Array.prototype.forEach, create = Object.create;
  4937. // eslint-disable-next-line no-unused-vars
  4938. module.exports = function (arg /*, …args*/) {
  4939. var set = create(null);
  4940. forEach.call(arguments, function (name) {
  4941. set[name] = true;
  4942. });
  4943. return set;
  4944. };
  4945. },{}],51:[function(require,module,exports){
  4946. "use strict";
  4947. module.exports = require("./is-implemented")()
  4948. ? Object.setPrototypeOf
  4949. : require("./shim");
  4950. },{"./is-implemented":52,"./shim":53}],52:[function(require,module,exports){
  4951. "use strict";
  4952. var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
  4953. module.exports = function (/* CustomCreate*/) {
  4954. var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
  4955. if (typeof setPrototypeOf !== "function") return false;
  4956. return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
  4957. };
  4958. },{}],53:[function(require,module,exports){
  4959. /* eslint no-proto: "off" */
  4960. // Big thanks to @WebReflection for sorting this out
  4961. // https://gist.github.com/WebReflection/5593554
  4962. "use strict";
  4963. var isObject = require("../is-object")
  4964. , value = require("../valid-value")
  4965. , objIsPrototypeOf = Object.prototype.isPrototypeOf
  4966. , defineProperty = Object.defineProperty
  4967. , nullDesc = {
  4968. configurable: true,
  4969. enumerable: false,
  4970. writable: true,
  4971. value: undefined
  4972. }
  4973. , validate;
  4974. validate = function (obj, prototype) {
  4975. value(obj);
  4976. if (prototype === null || isObject(prototype)) return obj;
  4977. throw new TypeError("Prototype must be null or an object");
  4978. };
  4979. module.exports = (function (status) {
  4980. var fn, set;
  4981. if (!status) return null;
  4982. if (status.level === 2) {
  4983. if (status.set) {
  4984. set = status.set;
  4985. fn = function (obj, prototype) {
  4986. set.call(validate(obj, prototype), prototype);
  4987. return obj;
  4988. };
  4989. } else {
  4990. fn = function (obj, prototype) {
  4991. validate(obj, prototype).__proto__ = prototype;
  4992. return obj;
  4993. };
  4994. }
  4995. } else {
  4996. fn = function self(obj, prototype) {
  4997. var isNullBase;
  4998. validate(obj, prototype);
  4999. isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
  5000. if (isNullBase) delete self.nullPolyfill.__proto__;
  5001. if (prototype === null) prototype = self.nullPolyfill;
  5002. obj.__proto__ = prototype;
  5003. if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
  5004. return obj;
  5005. };
  5006. }
  5007. return Object.defineProperty(fn, "level", {
  5008. configurable: false,
  5009. enumerable: false,
  5010. writable: false,
  5011. value: status.level
  5012. });
  5013. }(
  5014. (function () {
  5015. var tmpObj1 = Object.create(null)
  5016. , tmpObj2 = {}
  5017. , set
  5018. , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
  5019. if (desc) {
  5020. try {
  5021. set = desc.set; // Opera crashes at this point
  5022. set.call(tmpObj1, tmpObj2);
  5023. } catch (ignore) {}
  5024. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
  5025. }
  5026. tmpObj1.__proto__ = tmpObj2;
  5027. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
  5028. tmpObj1 = {};
  5029. tmpObj1.__proto__ = tmpObj2;
  5030. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
  5031. return false;
  5032. })()
  5033. ));
  5034. require("../create");
  5035. },{"../create":40,"../is-object":43,"../valid-value":55}],54:[function(require,module,exports){
  5036. "use strict";
  5037. module.exports = function (fn) {
  5038. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  5039. return fn;
  5040. };
  5041. },{}],55:[function(require,module,exports){
  5042. "use strict";
  5043. var isValue = require("./is-value");
  5044. module.exports = function (value) {
  5045. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  5046. return value;
  5047. };
  5048. },{"./is-value":44}],56:[function(require,module,exports){
  5049. "use strict";
  5050. module.exports = require("./is-implemented")()
  5051. ? String.prototype.contains
  5052. : require("./shim");
  5053. },{"./is-implemented":57,"./shim":58}],57:[function(require,module,exports){
  5054. "use strict";
  5055. var str = "razdwatrzy";
  5056. module.exports = function () {
  5057. if (typeof str.contains !== "function") return false;
  5058. return (str.contains("dwa") === true) && (str.contains("foo") === false);
  5059. };
  5060. },{}],58:[function(require,module,exports){
  5061. "use strict";
  5062. var indexOf = String.prototype.indexOf;
  5063. module.exports = function (searchString/*, position*/) {
  5064. return indexOf.call(this, searchString, arguments[1]) > -1;
  5065. };
  5066. },{}],59:[function(require,module,exports){
  5067. "use strict";
  5068. var objToString = Object.prototype.toString, id = objToString.call("");
  5069. module.exports = function (value) {
  5070. return (
  5071. typeof value === "string" ||
  5072. (value &&
  5073. typeof value === "object" &&
  5074. (value instanceof String || objToString.call(value) === id)) ||
  5075. false
  5076. );
  5077. };
  5078. },{}],60:[function(require,module,exports){
  5079. "use strict";
  5080. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5081. , contains = require("es5-ext/string/#/contains")
  5082. , d = require("d")
  5083. , Symbol = require("es6-symbol")
  5084. , Iterator = require("./");
  5085. var defineProperty = Object.defineProperty, ArrayIterator;
  5086. ArrayIterator = module.exports = function (arr, kind) {
  5087. if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
  5088. Iterator.call(this, arr);
  5089. if (!kind) kind = "value";
  5090. else if (contains.call(kind, "key+value")) kind = "key+value";
  5091. else if (contains.call(kind, "key")) kind = "key";
  5092. else kind = "value";
  5093. defineProperty(this, "__kind__", d("", kind));
  5094. };
  5095. if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
  5096. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5097. delete ArrayIterator.prototype.constructor;
  5098. ArrayIterator.prototype = Object.create(Iterator.prototype, {
  5099. _resolve: d(function (i) {
  5100. if (this.__kind__ === "value") return this.__list__[i];
  5101. if (this.__kind__ === "key+value") return [i, this.__list__[i]];
  5102. return i;
  5103. })
  5104. });
  5105. defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
  5106. },{"./":63,"d":16,"es5-ext/object/set-prototype-of":51,"es5-ext/string/#/contains":56,"es6-symbol":73}],61:[function(require,module,exports){
  5107. "use strict";
  5108. var isArguments = require("es5-ext/function/is-arguments")
  5109. , callable = require("es5-ext/object/valid-callable")
  5110. , isString = require("es5-ext/string/is-string")
  5111. , get = require("./get");
  5112. var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
  5113. module.exports = function (iterable, cb /*, thisArg*/) {
  5114. var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
  5115. if (isArray(iterable) || isArguments(iterable)) mode = "array";
  5116. else if (isString(iterable)) mode = "string";
  5117. else iterable = get(iterable);
  5118. callable(cb);
  5119. doBreak = function () {
  5120. broken = true;
  5121. };
  5122. if (mode === "array") {
  5123. some.call(iterable, function (value) {
  5124. call.call(cb, thisArg, value, doBreak);
  5125. return broken;
  5126. });
  5127. return;
  5128. }
  5129. if (mode === "string") {
  5130. length = iterable.length;
  5131. for (i = 0; i < length; ++i) {
  5132. char = iterable[i];
  5133. if (i + 1 < length) {
  5134. code = char.charCodeAt(0);
  5135. if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
  5136. }
  5137. call.call(cb, thisArg, char, doBreak);
  5138. if (broken) break;
  5139. }
  5140. return;
  5141. }
  5142. result = iterable.next();
  5143. while (!result.done) {
  5144. call.call(cb, thisArg, result.value, doBreak);
  5145. if (broken) return;
  5146. result = iterable.next();
  5147. }
  5148. };
  5149. },{"./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){
  5150. "use strict";
  5151. var isArguments = require("es5-ext/function/is-arguments")
  5152. , isString = require("es5-ext/string/is-string")
  5153. , ArrayIterator = require("./array")
  5154. , StringIterator = require("./string")
  5155. , iterable = require("./valid-iterable")
  5156. , iteratorSymbol = require("es6-symbol").iterator;
  5157. module.exports = function (obj) {
  5158. if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
  5159. if (isArguments(obj)) return new ArrayIterator(obj);
  5160. if (isString(obj)) return new StringIterator(obj);
  5161. return new ArrayIterator(obj);
  5162. };
  5163. },{"./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){
  5164. "use strict";
  5165. var clear = require("es5-ext/array/#/clear")
  5166. , assign = require("es5-ext/object/assign")
  5167. , callable = require("es5-ext/object/valid-callable")
  5168. , value = require("es5-ext/object/valid-value")
  5169. , d = require("d")
  5170. , autoBind = require("d/auto-bind")
  5171. , Symbol = require("es6-symbol");
  5172. var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
  5173. module.exports = Iterator = function (list, context) {
  5174. if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
  5175. defineProperties(this, {
  5176. __list__: d("w", value(list)),
  5177. __context__: d("w", context),
  5178. __nextIndex__: d("w", 0)
  5179. });
  5180. if (!context) return;
  5181. callable(context.on);
  5182. context.on("_add", this._onAdd);
  5183. context.on("_delete", this._onDelete);
  5184. context.on("_clear", this._onClear);
  5185. };
  5186. // Internal %IteratorPrototype% doesn't expose its constructor
  5187. delete Iterator.prototype.constructor;
  5188. defineProperties(
  5189. Iterator.prototype,
  5190. assign(
  5191. {
  5192. _next: d(function () {
  5193. var i;
  5194. if (!this.__list__) return undefined;
  5195. if (this.__redo__) {
  5196. i = this.__redo__.shift();
  5197. if (i !== undefined) return i;
  5198. }
  5199. if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
  5200. this._unBind();
  5201. return undefined;
  5202. }),
  5203. next: d(function () {
  5204. return this._createResult(this._next());
  5205. }),
  5206. _createResult: d(function (i) {
  5207. if (i === undefined) return { done: true, value: undefined };
  5208. return { done: false, value: this._resolve(i) };
  5209. }),
  5210. _resolve: d(function (i) {
  5211. return this.__list__[i];
  5212. }),
  5213. _unBind: d(function () {
  5214. this.__list__ = null;
  5215. delete this.__redo__;
  5216. if (!this.__context__) return;
  5217. this.__context__.off("_add", this._onAdd);
  5218. this.__context__.off("_delete", this._onDelete);
  5219. this.__context__.off("_clear", this._onClear);
  5220. this.__context__ = null;
  5221. }),
  5222. toString: d(function () {
  5223. return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
  5224. })
  5225. },
  5226. autoBind({
  5227. _onAdd: d(function (index) {
  5228. if (index >= this.__nextIndex__) return;
  5229. ++this.__nextIndex__;
  5230. if (!this.__redo__) {
  5231. defineProperty(this, "__redo__", d("c", [index]));
  5232. return;
  5233. }
  5234. this.__redo__.forEach(function (redo, i) {
  5235. if (redo >= index) this.__redo__[i] = ++redo;
  5236. }, this);
  5237. this.__redo__.push(index);
  5238. }),
  5239. _onDelete: d(function (index) {
  5240. var i;
  5241. if (index >= this.__nextIndex__) return;
  5242. --this.__nextIndex__;
  5243. if (!this.__redo__) return;
  5244. i = this.__redo__.indexOf(index);
  5245. if (i !== -1) this.__redo__.splice(i, 1);
  5246. this.__redo__.forEach(function (redo, j) {
  5247. if (redo > index) this.__redo__[j] = --redo;
  5248. }, this);
  5249. }),
  5250. _onClear: d(function () {
  5251. if (this.__redo__) clear.call(this.__redo__);
  5252. this.__nextIndex__ = 0;
  5253. })
  5254. })
  5255. )
  5256. );
  5257. defineProperty(
  5258. Iterator.prototype,
  5259. Symbol.iterator,
  5260. d(function () {
  5261. return this;
  5262. })
  5263. );
  5264. },{"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){
  5265. "use strict";
  5266. var isArguments = require("es5-ext/function/is-arguments")
  5267. , isValue = require("es5-ext/object/is-value")
  5268. , isString = require("es5-ext/string/is-string");
  5269. var iteratorSymbol = require("es6-symbol").iterator
  5270. , isArray = Array.isArray;
  5271. module.exports = function (value) {
  5272. if (!isValue(value)) return false;
  5273. if (isArray(value)) return true;
  5274. if (isString(value)) return true;
  5275. if (isArguments(value)) return true;
  5276. return typeof value[iteratorSymbol] === "function";
  5277. };
  5278. },{"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){
  5279. // Thanks @mathiasbynens
  5280. // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
  5281. "use strict";
  5282. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5283. , d = require("d")
  5284. , Symbol = require("es6-symbol")
  5285. , Iterator = require("./");
  5286. var defineProperty = Object.defineProperty, StringIterator;
  5287. StringIterator = module.exports = function (str) {
  5288. if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
  5289. str = String(str);
  5290. Iterator.call(this, str);
  5291. defineProperty(this, "__length__", d("", str.length));
  5292. };
  5293. if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
  5294. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5295. delete StringIterator.prototype.constructor;
  5296. StringIterator.prototype = Object.create(Iterator.prototype, {
  5297. _next: d(function () {
  5298. if (!this.__list__) return undefined;
  5299. if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
  5300. this._unBind();
  5301. return undefined;
  5302. }),
  5303. _resolve: d(function (i) {
  5304. var char = this.__list__[i], code;
  5305. if (this.__nextIndex__ === this.__length__) return char;
  5306. code = char.charCodeAt(0);
  5307. if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
  5308. return char;
  5309. })
  5310. });
  5311. defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
  5312. },{"./":63,"d":16,"es5-ext/object/set-prototype-of":51,"es6-symbol":73}],66:[function(require,module,exports){
  5313. "use strict";
  5314. var isIterable = require("./is-iterable");
  5315. module.exports = function (value) {
  5316. if (!isIterable(value)) throw new TypeError(value + " is not iterable");
  5317. return value;
  5318. };
  5319. },{"./is-iterable":64}],67:[function(require,module,exports){
  5320. 'use strict';
  5321. module.exports = require('./is-implemented')() ? Map : require('./polyfill');
  5322. },{"./is-implemented":68,"./polyfill":72}],68:[function(require,module,exports){
  5323. 'use strict';
  5324. module.exports = function () {
  5325. var map, iterator, result;
  5326. if (typeof Map !== 'function') return false;
  5327. try {
  5328. // WebKit doesn't support arguments and crashes
  5329. map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
  5330. } catch (e) {
  5331. return false;
  5332. }
  5333. if (String(map) !== '[object Map]') return false;
  5334. if (map.size !== 3) return false;
  5335. if (typeof map.clear !== 'function') return false;
  5336. if (typeof map.delete !== 'function') return false;
  5337. if (typeof map.entries !== 'function') return false;
  5338. if (typeof map.forEach !== 'function') return false;
  5339. if (typeof map.get !== 'function') return false;
  5340. if (typeof map.has !== 'function') return false;
  5341. if (typeof map.keys !== 'function') return false;
  5342. if (typeof map.set !== 'function') return false;
  5343. if (typeof map.values !== 'function') return false;
  5344. iterator = map.entries();
  5345. result = iterator.next();
  5346. if (result.done !== false) return false;
  5347. if (!result.value) return false;
  5348. if (result.value[0] !== 'raz') return false;
  5349. if (result.value[1] !== 'one') return false;
  5350. return true;
  5351. };
  5352. },{}],69:[function(require,module,exports){
  5353. // Exports true if environment provides native `Map` implementation,
  5354. // whatever that is.
  5355. 'use strict';
  5356. module.exports = (function () {
  5357. if (typeof Map === 'undefined') return false;
  5358. return (Object.prototype.toString.call(new Map()) === '[object Map]');
  5359. }());
  5360. },{}],70:[function(require,module,exports){
  5361. 'use strict';
  5362. module.exports = require('es5-ext/object/primitive-set')('key',
  5363. 'value', 'key+value');
  5364. },{"es5-ext/object/primitive-set":50}],71:[function(require,module,exports){
  5365. 'use strict';
  5366. var setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5367. , d = require('d')
  5368. , Iterator = require('es6-iterator')
  5369. , toStringTagSymbol = require('es6-symbol').toStringTag
  5370. , kinds = require('./iterator-kinds')
  5371. , defineProperties = Object.defineProperties
  5372. , unBind = Iterator.prototype._unBind
  5373. , MapIterator;
  5374. MapIterator = module.exports = function (map, kind) {
  5375. if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
  5376. Iterator.call(this, map.__mapKeysData__, map);
  5377. if (!kind || !kinds[kind]) kind = 'key+value';
  5378. defineProperties(this, {
  5379. __kind__: d('', kind),
  5380. __values__: d('w', map.__mapValuesData__)
  5381. });
  5382. };
  5383. if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
  5384. MapIterator.prototype = Object.create(Iterator.prototype, {
  5385. constructor: d(MapIterator),
  5386. _resolve: d(function (i) {
  5387. if (this.__kind__ === 'value') return this.__values__[i];
  5388. if (this.__kind__ === 'key') return this.__list__[i];
  5389. return [this.__list__[i], this.__values__[i]];
  5390. }),
  5391. _unBind: d(function () {
  5392. this.__values__ = null;
  5393. unBind.call(this);
  5394. }),
  5395. toString: d(function () { return '[object Map Iterator]'; })
  5396. });
  5397. Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
  5398. d('c', 'Map Iterator'));
  5399. },{"./iterator-kinds":70,"d":16,"es5-ext/object/set-prototype-of":51,"es6-iterator":63,"es6-symbol":73}],72:[function(require,module,exports){
  5400. 'use strict';
  5401. var clear = require('es5-ext/array/#/clear')
  5402. , eIndexOf = require('es5-ext/array/#/e-index-of')
  5403. , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5404. , callable = require('es5-ext/object/valid-callable')
  5405. , validValue = require('es5-ext/object/valid-value')
  5406. , d = require('d')
  5407. , ee = require('event-emitter')
  5408. , Symbol = require('es6-symbol')
  5409. , iterator = require('es6-iterator/valid-iterable')
  5410. , forOf = require('es6-iterator/for-of')
  5411. , Iterator = require('./lib/iterator')
  5412. , isNative = require('./is-native-implemented')
  5413. , call = Function.prototype.call
  5414. , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf
  5415. , MapPoly;
  5416. module.exports = MapPoly = function (/*iterable*/) {
  5417. var iterable = arguments[0], keys, values, self;
  5418. if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\'');
  5419. if (isNative && setPrototypeOf && (Map !== MapPoly)) {
  5420. self = setPrototypeOf(new Map(), getPrototypeOf(this));
  5421. } else {
  5422. self = this;
  5423. }
  5424. if (iterable != null) iterator(iterable);
  5425. defineProperties(self, {
  5426. __mapKeysData__: d('c', keys = []),
  5427. __mapValuesData__: d('c', values = [])
  5428. });
  5429. if (!iterable) return self;
  5430. forOf(iterable, function (value) {
  5431. var key = validValue(value)[0];
  5432. value = value[1];
  5433. if (eIndexOf.call(keys, key) !== -1) return;
  5434. keys.push(key);
  5435. values.push(value);
  5436. }, self);
  5437. return self;
  5438. };
  5439. if (isNative) {
  5440. if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
  5441. MapPoly.prototype = Object.create(Map.prototype, {
  5442. constructor: d(MapPoly)
  5443. });
  5444. }
  5445. ee(defineProperties(MapPoly.prototype, {
  5446. clear: d(function () {
  5447. if (!this.__mapKeysData__.length) return;
  5448. clear.call(this.__mapKeysData__);
  5449. clear.call(this.__mapValuesData__);
  5450. this.emit('_clear');
  5451. }),
  5452. delete: d(function (key) {
  5453. var index = eIndexOf.call(this.__mapKeysData__, key);
  5454. if (index === -1) return false;
  5455. this.__mapKeysData__.splice(index, 1);
  5456. this.__mapValuesData__.splice(index, 1);
  5457. this.emit('_delete', index, key);
  5458. return true;
  5459. }),
  5460. entries: d(function () { return new Iterator(this, 'key+value'); }),
  5461. forEach: d(function (cb/*, thisArg*/) {
  5462. var thisArg = arguments[1], iterator, result;
  5463. callable(cb);
  5464. iterator = this.entries();
  5465. result = iterator._next();
  5466. while (result !== undefined) {
  5467. call.call(cb, thisArg, this.__mapValuesData__[result],
  5468. this.__mapKeysData__[result], this);
  5469. result = iterator._next();
  5470. }
  5471. }),
  5472. get: d(function (key) {
  5473. var index = eIndexOf.call(this.__mapKeysData__, key);
  5474. if (index === -1) return;
  5475. return this.__mapValuesData__[index];
  5476. }),
  5477. has: d(function (key) {
  5478. return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
  5479. }),
  5480. keys: d(function () { return new Iterator(this, 'key'); }),
  5481. set: d(function (key, value) {
  5482. var index = eIndexOf.call(this.__mapKeysData__, key), emit;
  5483. if (index === -1) {
  5484. index = this.__mapKeysData__.push(key) - 1;
  5485. emit = true;
  5486. }
  5487. this.__mapValuesData__[index] = value;
  5488. if (emit) this.emit('_add', index, key);
  5489. return this;
  5490. }),
  5491. size: d.gs(function () { return this.__mapKeysData__.length; }),
  5492. values: d(function () { return new Iterator(this, 'value'); }),
  5493. toString: d(function () { return '[object Map]'; })
  5494. }));
  5495. Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
  5496. return this.entries();
  5497. }));
  5498. Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
  5499. },{"./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){
  5500. 'use strict';
  5501. module.exports = require('./is-implemented')() ? Symbol : require('./polyfill');
  5502. },{"./is-implemented":74,"./polyfill":76}],74:[function(require,module,exports){
  5503. 'use strict';
  5504. var validTypes = { object: true, symbol: true };
  5505. module.exports = function () {
  5506. var symbol;
  5507. if (typeof Symbol !== 'function') return false;
  5508. symbol = Symbol('test symbol');
  5509. try { String(symbol); } catch (e) { return false; }
  5510. // Return 'true' also for polyfills
  5511. if (!validTypes[typeof Symbol.iterator]) return false;
  5512. if (!validTypes[typeof Symbol.toPrimitive]) return false;
  5513. if (!validTypes[typeof Symbol.toStringTag]) return false;
  5514. return true;
  5515. };
  5516. },{}],75:[function(require,module,exports){
  5517. 'use strict';
  5518. module.exports = function (x) {
  5519. if (!x) return false;
  5520. if (typeof x === 'symbol') return true;
  5521. if (!x.constructor) return false;
  5522. if (x.constructor.name !== 'Symbol') return false;
  5523. return (x[x.constructor.toStringTag] === 'Symbol');
  5524. };
  5525. },{}],76:[function(require,module,exports){
  5526. // ES2015 Symbol polyfill for environments that do not (or partially) support it
  5527. 'use strict';
  5528. var d = require('d')
  5529. , validateSymbol = require('./validate-symbol')
  5530. , create = Object.create, defineProperties = Object.defineProperties
  5531. , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  5532. , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null)
  5533. , isNativeSafe;
  5534. if (typeof Symbol === 'function') {
  5535. NativeSymbol = Symbol;
  5536. try {
  5537. String(NativeSymbol());
  5538. isNativeSafe = true;
  5539. } catch (ignore) {}
  5540. }
  5541. var generateName = (function () {
  5542. var created = create(null);
  5543. return function (desc) {
  5544. var postfix = 0, name, ie11BugWorkaround;
  5545. while (created[desc + (postfix || '')]) ++postfix;
  5546. desc += (postfix || '');
  5547. created[desc] = true;
  5548. name = '@@' + desc;
  5549. defineProperty(objPrototype, name, d.gs(null, function (value) {
  5550. // For IE11 issue see:
  5551. // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
  5552. // ie11-broken-getters-on-dom-objects
  5553. // https://github.com/medikoo/es6-symbol/issues/12
  5554. if (ie11BugWorkaround) return;
  5555. ie11BugWorkaround = true;
  5556. defineProperty(this, name, d(value));
  5557. ie11BugWorkaround = false;
  5558. }));
  5559. return name;
  5560. };
  5561. }());
  5562. // Internal constructor (not one exposed) for creating Symbol instances.
  5563. // This one is used to ensure that `someSymbol instanceof Symbol` always return false
  5564. HiddenSymbol = function Symbol(description) {
  5565. if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor');
  5566. return SymbolPolyfill(description);
  5567. };
  5568. // Exposed `Symbol` constructor
  5569. // (returns instances of HiddenSymbol)
  5570. module.exports = SymbolPolyfill = function Symbol(description) {
  5571. var symbol;
  5572. if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor');
  5573. if (isNativeSafe) return NativeSymbol(description);
  5574. symbol = create(HiddenSymbol.prototype);
  5575. description = (description === undefined ? '' : String(description));
  5576. return defineProperties(symbol, {
  5577. __description__: d('', description),
  5578. __name__: d('', generateName(description))
  5579. });
  5580. };
  5581. defineProperties(SymbolPolyfill, {
  5582. for: d(function (key) {
  5583. if (globalSymbols[key]) return globalSymbols[key];
  5584. return (globalSymbols[key] = SymbolPolyfill(String(key)));
  5585. }),
  5586. keyFor: d(function (s) {
  5587. var key;
  5588. validateSymbol(s);
  5589. for (key in globalSymbols) if (globalSymbols[key] === s) return key;
  5590. }),
  5591. // To ensure proper interoperability with other native functions (e.g. Array.from)
  5592. // fallback to eventual native implementation of given symbol
  5593. hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
  5594. isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
  5595. SymbolPolyfill('isConcatSpreadable')),
  5596. iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
  5597. match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
  5598. replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
  5599. search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
  5600. species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
  5601. split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
  5602. toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
  5603. toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
  5604. unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
  5605. });
  5606. // Internal tweaks for real symbol producer
  5607. defineProperties(HiddenSymbol.prototype, {
  5608. constructor: d(SymbolPolyfill),
  5609. toString: d('', function () { return this.__name__; })
  5610. });
  5611. // Proper implementation of methods exposed on Symbol.prototype
  5612. // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
  5613. defineProperties(SymbolPolyfill.prototype, {
  5614. toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
  5615. valueOf: d(function () { return validateSymbol(this); })
  5616. });
  5617. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () {
  5618. var symbol = validateSymbol(this);
  5619. if (typeof symbol === 'symbol') return symbol;
  5620. return symbol.toString();
  5621. }));
  5622. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));
  5623. // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
  5624. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
  5625. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
  5626. // Note: It's important to define `toPrimitive` as last one, as some implementations
  5627. // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
  5628. // And that may invoke error in definition flow:
  5629. // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
  5630. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
  5631. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
  5632. },{"./validate-symbol":77,"d":16}],77:[function(require,module,exports){
  5633. 'use strict';
  5634. var isSymbol = require('./is-symbol');
  5635. module.exports = function (value) {
  5636. if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
  5637. return value;
  5638. };
  5639. },{"./is-symbol":75}],78:[function(require,module,exports){
  5640. 'use strict';
  5641. var d = require('d')
  5642. , callable = require('es5-ext/object/valid-callable')
  5643. , apply = Function.prototype.apply, call = Function.prototype.call
  5644. , create = Object.create, defineProperty = Object.defineProperty
  5645. , defineProperties = Object.defineProperties
  5646. , hasOwnProperty = Object.prototype.hasOwnProperty
  5647. , descriptor = { configurable: true, enumerable: false, writable: true }
  5648. , on, once, off, emit, methods, descriptors, base;
  5649. on = function (type, listener) {
  5650. var data;
  5651. callable(listener);
  5652. if (!hasOwnProperty.call(this, '__ee__')) {
  5653. data = descriptor.value = create(null);
  5654. defineProperty(this, '__ee__', descriptor);
  5655. descriptor.value = null;
  5656. } else {
  5657. data = this.__ee__;
  5658. }
  5659. if (!data[type]) data[type] = listener;
  5660. else if (typeof data[type] === 'object') data[type].push(listener);
  5661. else data[type] = [data[type], listener];
  5662. return this;
  5663. };
  5664. once = function (type, listener) {
  5665. var once, self;
  5666. callable(listener);
  5667. self = this;
  5668. on.call(this, type, once = function () {
  5669. off.call(self, type, once);
  5670. apply.call(listener, this, arguments);
  5671. });
  5672. once.__eeOnceListener__ = listener;
  5673. return this;
  5674. };
  5675. off = function (type, listener) {
  5676. var data, listeners, candidate, i;
  5677. callable(listener);
  5678. if (!hasOwnProperty.call(this, '__ee__')) return this;
  5679. data = this.__ee__;
  5680. if (!data[type]) return this;
  5681. listeners = data[type];
  5682. if (typeof listeners === 'object') {
  5683. for (i = 0; (candidate = listeners[i]); ++i) {
  5684. if ((candidate === listener) ||
  5685. (candidate.__eeOnceListener__ === listener)) {
  5686. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  5687. else listeners.splice(i, 1);
  5688. }
  5689. }
  5690. } else {
  5691. if ((listeners === listener) ||
  5692. (listeners.__eeOnceListener__ === listener)) {
  5693. delete data[type];
  5694. }
  5695. }
  5696. return this;
  5697. };
  5698. emit = function (type) {
  5699. var i, l, listener, listeners, args;
  5700. if (!hasOwnProperty.call(this, '__ee__')) return;
  5701. listeners = this.__ee__[type];
  5702. if (!listeners) return;
  5703. if (typeof listeners === 'object') {
  5704. l = arguments.length;
  5705. args = new Array(l - 1);
  5706. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  5707. listeners = listeners.slice();
  5708. for (i = 0; (listener = listeners[i]); ++i) {
  5709. apply.call(listener, this, args);
  5710. }
  5711. } else {
  5712. switch (arguments.length) {
  5713. case 1:
  5714. call.call(listeners, this);
  5715. break;
  5716. case 2:
  5717. call.call(listeners, this, arguments[1]);
  5718. break;
  5719. case 3:
  5720. call.call(listeners, this, arguments[1], arguments[2]);
  5721. break;
  5722. default:
  5723. l = arguments.length;
  5724. args = new Array(l - 1);
  5725. for (i = 1; i < l; ++i) {
  5726. args[i - 1] = arguments[i];
  5727. }
  5728. apply.call(listeners, this, args);
  5729. }
  5730. }
  5731. };
  5732. methods = {
  5733. on: on,
  5734. once: once,
  5735. off: off,
  5736. emit: emit
  5737. };
  5738. descriptors = {
  5739. on: d(on),
  5740. once: d(once),
  5741. off: d(off),
  5742. emit: d(emit)
  5743. };
  5744. base = defineProperties({}, descriptors);
  5745. module.exports = exports = function (o) {
  5746. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  5747. };
  5748. exports.methods = methods;
  5749. },{"d":16,"es5-ext/object/valid-callable":54}],79:[function(require,module,exports){
  5750. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5751. var e, m
  5752. var eLen = (nBytes * 8) - mLen - 1
  5753. var eMax = (1 << eLen) - 1
  5754. var eBias = eMax >> 1
  5755. var nBits = -7
  5756. var i = isLE ? (nBytes - 1) : 0
  5757. var d = isLE ? -1 : 1
  5758. var s = buffer[offset + i]
  5759. i += d
  5760. e = s & ((1 << (-nBits)) - 1)
  5761. s >>= (-nBits)
  5762. nBits += eLen
  5763. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5764. m = e & ((1 << (-nBits)) - 1)
  5765. e >>= (-nBits)
  5766. nBits += mLen
  5767. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5768. if (e === 0) {
  5769. e = 1 - eBias
  5770. } else if (e === eMax) {
  5771. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5772. } else {
  5773. m = m + Math.pow(2, mLen)
  5774. e = e - eBias
  5775. }
  5776. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5777. }
  5778. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5779. var e, m, c
  5780. var eLen = (nBytes * 8) - mLen - 1
  5781. var eMax = (1 << eLen) - 1
  5782. var eBias = eMax >> 1
  5783. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5784. var i = isLE ? 0 : (nBytes - 1)
  5785. var d = isLE ? 1 : -1
  5786. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5787. value = Math.abs(value)
  5788. if (isNaN(value) || value === Infinity) {
  5789. m = isNaN(value) ? 1 : 0
  5790. e = eMax
  5791. } else {
  5792. e = Math.floor(Math.log(value) / Math.LN2)
  5793. if (value * (c = Math.pow(2, -e)) < 1) {
  5794. e--
  5795. c *= 2
  5796. }
  5797. if (e + eBias >= 1) {
  5798. value += rt / c
  5799. } else {
  5800. value += rt * Math.pow(2, 1 - eBias)
  5801. }
  5802. if (value * c >= 2) {
  5803. e++
  5804. c /= 2
  5805. }
  5806. if (e + eBias >= eMax) {
  5807. m = 0
  5808. e = eMax
  5809. } else if (e + eBias >= 1) {
  5810. m = ((value * c) - 1) * Math.pow(2, mLen)
  5811. e = e + eBias
  5812. } else {
  5813. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5814. e = 0
  5815. }
  5816. }
  5817. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5818. e = (e << mLen) | m
  5819. eLen += mLen
  5820. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5821. buffer[offset + i - d] |= s * 128
  5822. }
  5823. },{}],80:[function(require,module,exports){
  5824. if (typeof Object.create === 'function') {
  5825. // implementation from standard node.js 'util' module
  5826. module.exports = function inherits(ctor, superCtor) {
  5827. ctor.super_ = superCtor
  5828. ctor.prototype = Object.create(superCtor.prototype, {
  5829. constructor: {
  5830. value: ctor,
  5831. enumerable: false,
  5832. writable: true,
  5833. configurable: true
  5834. }
  5835. });
  5836. };
  5837. } else {
  5838. // old school shim for old browsers
  5839. module.exports = function inherits(ctor, superCtor) {
  5840. ctor.super_ = superCtor
  5841. var TempCtor = function () {}
  5842. TempCtor.prototype = superCtor.prototype
  5843. ctor.prototype = new TempCtor()
  5844. ctor.prototype.constructor = ctor
  5845. }
  5846. }
  5847. },{}],81:[function(require,module,exports){
  5848. /*!
  5849. * Determine if an object is a Buffer
  5850. *
  5851. * @author Feross Aboukhadijeh <https://feross.org>
  5852. * @license MIT
  5853. */
  5854. // The _isBuffer check is for Safari 5-7 support, because it's missing
  5855. // Object.prototype.constructor. Remove this eventually
  5856. module.exports = function (obj) {
  5857. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  5858. }
  5859. function isBuffer (obj) {
  5860. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  5861. }
  5862. // For Node v0.10 support. Remove this eventually.
  5863. function isSlowBuffer (obj) {
  5864. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  5865. }
  5866. },{}],82:[function(require,module,exports){
  5867. 'use strict'
  5868. var Buffer = require('safe-buffer').Buffer
  5869. /* Protocol - protocol constants */
  5870. var protocol = module.exports
  5871. /* Command code => mnemonic */
  5872. protocol.types = {
  5873. 0: 'reserved',
  5874. 1: 'connect',
  5875. 2: 'connack',
  5876. 3: 'publish',
  5877. 4: 'puback',
  5878. 5: 'pubrec',
  5879. 6: 'pubrel',
  5880. 7: 'pubcomp',
  5881. 8: 'subscribe',
  5882. 9: 'suback',
  5883. 10: 'unsubscribe',
  5884. 11: 'unsuback',
  5885. 12: 'pingreq',
  5886. 13: 'pingresp',
  5887. 14: 'disconnect',
  5888. 15: 'auth'
  5889. }
  5890. /* Mnemonic => Command code */
  5891. protocol.codes = {}
  5892. for (var k in protocol.types) {
  5893. var v = protocol.types[k]
  5894. protocol.codes[v] = k
  5895. }
  5896. /* Header */
  5897. protocol.CMD_SHIFT = 4
  5898. protocol.CMD_MASK = 0xF0
  5899. protocol.DUP_MASK = 0x08
  5900. protocol.QOS_MASK = 0x03
  5901. protocol.QOS_SHIFT = 1
  5902. protocol.RETAIN_MASK = 0x01
  5903. /* Length */
  5904. protocol.LENGTH_MASK = 0x7F
  5905. protocol.LENGTH_FIN_MASK = 0x80
  5906. /* Connack */
  5907. protocol.SESSIONPRESENT_MASK = 0x01
  5908. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  5909. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  5910. /* Connect */
  5911. protocol.USERNAME_MASK = 0x80
  5912. protocol.PASSWORD_MASK = 0x40
  5913. protocol.WILL_RETAIN_MASK = 0x20
  5914. protocol.WILL_QOS_MASK = 0x18
  5915. protocol.WILL_QOS_SHIFT = 3
  5916. protocol.WILL_FLAG_MASK = 0x04
  5917. protocol.CLEAN_SESSION_MASK = 0x02
  5918. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  5919. /* Properties */
  5920. protocol.properties = {
  5921. sessionExpiryInterval: 17,
  5922. willDelayInterval: 24,
  5923. receiveMaximum: 33,
  5924. maximumPacketSize: 39,
  5925. topicAliasMaximum: 34,
  5926. requestResponseInformation: 25,
  5927. requestProblemInformation: 23,
  5928. userProperties: 38,
  5929. authenticationMethod: 21,
  5930. authenticationData: 22,
  5931. payloadFormatIndicator: 1,
  5932. messageExpiryInterval: 2,
  5933. contentType: 3,
  5934. responseTopic: 8,
  5935. correlationData: 9,
  5936. maximumQoS: 36,
  5937. retainAvailable: 37,
  5938. assignedClientIdentifier: 18,
  5939. reasonString: 31,
  5940. wildcardSubscriptionAvailable: 40,
  5941. subscriptionIdentifiersAvailable: 41,
  5942. sharedSubscriptionAvailable: 42,
  5943. serverKeepAlive: 19,
  5944. responseInformation: 26,
  5945. serverReference: 28,
  5946. topicAlias: 35,
  5947. subscriptionIdentifier: 11
  5948. }
  5949. protocol.propertiesCodes = {}
  5950. for (var prop in protocol.properties) {
  5951. var id = protocol.properties[prop]
  5952. protocol.propertiesCodes[id] = prop
  5953. }
  5954. protocol.propertiesTypes = {
  5955. sessionExpiryInterval: 'int32',
  5956. willDelayInterval: 'int32',
  5957. receiveMaximum: 'int16',
  5958. maximumPacketSize: 'int32',
  5959. topicAliasMaximum: 'int16',
  5960. requestResponseInformation: 'byte',
  5961. requestProblemInformation: 'byte',
  5962. userProperties: 'pair',
  5963. authenticationMethod: 'string',
  5964. authenticationData: 'binary',
  5965. payloadFormatIndicator: 'byte',
  5966. messageExpiryInterval: 'int32',
  5967. contentType: 'string',
  5968. responseTopic: 'string',
  5969. correlationData: 'binary',
  5970. maximumQoS: 'int8',
  5971. retainAvailable: 'byte',
  5972. assignedClientIdentifier: 'string',
  5973. reasonString: 'string',
  5974. wildcardSubscriptionAvailable: 'byte',
  5975. subscriptionIdentifiersAvailable: 'byte',
  5976. sharedSubscriptionAvailable: 'byte',
  5977. serverKeepAlive: 'int32',
  5978. responseInformation: 'string',
  5979. serverReference: 'string',
  5980. topicAlias: 'int16',
  5981. subscriptionIdentifier: 'var'
  5982. }
  5983. function genHeader (type) {
  5984. return [0, 1, 2].map(function (qos) {
  5985. return [0, 1].map(function (dup) {
  5986. return [0, 1].map(function (retain) {
  5987. var buf = new Buffer(1)
  5988. buf.writeUInt8(
  5989. protocol.codes[type] << protocol.CMD_SHIFT |
  5990. (dup ? protocol.DUP_MASK : 0) |
  5991. qos << protocol.QOS_SHIFT | retain, 0, true)
  5992. return buf
  5993. })
  5994. })
  5995. })
  5996. }
  5997. /* Publish */
  5998. protocol.PUBLISH_HEADER = genHeader('publish')
  5999. /* Subscribe */
  6000. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  6001. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  6002. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  6003. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  6004. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  6005. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  6006. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  6007. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  6008. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  6009. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  6010. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  6011. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  6012. /* Unsubscribe */
  6013. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  6014. /* Confirmations */
  6015. protocol.ACKS = {
  6016. unsuback: genHeader('unsuback'),
  6017. puback: genHeader('puback'),
  6018. pubcomp: genHeader('pubcomp'),
  6019. pubrel: genHeader('pubrel'),
  6020. pubrec: genHeader('pubrec')
  6021. }
  6022. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  6023. /* Protocol versions */
  6024. protocol.VERSION3 = Buffer.from([3])
  6025. protocol.VERSION4 = Buffer.from([4])
  6026. protocol.VERSION5 = Buffer.from([5])
  6027. /* QoS */
  6028. protocol.QOS = [0, 1, 2].map(function (qos) {
  6029. return Buffer.from([qos])
  6030. })
  6031. /* Empty packets */
  6032. protocol.EMPTY = {
  6033. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  6034. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  6035. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  6036. }
  6037. },{"safe-buffer":110}],83:[function(require,module,exports){
  6038. 'use strict'
  6039. var Buffer = require('safe-buffer').Buffer
  6040. var writeToStream = require('./writeToStream')
  6041. var EE = require('events').EventEmitter
  6042. var inherits = require('inherits')
  6043. function generate (packet, opts) {
  6044. var stream = new Accumulator()
  6045. writeToStream(packet, stream, opts)
  6046. return stream.concat()
  6047. }
  6048. function Accumulator () {
  6049. this._array = new Array(20)
  6050. this._i = 0
  6051. }
  6052. inherits(Accumulator, EE)
  6053. Accumulator.prototype.write = function (chunk) {
  6054. this._array[this._i++] = chunk
  6055. return true
  6056. }
  6057. Accumulator.prototype.concat = function () {
  6058. var length = 0
  6059. var lengths = new Array(this._array.length)
  6060. var list = this._array
  6061. var pos = 0
  6062. var i
  6063. var result
  6064. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6065. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  6066. else lengths[i] = Buffer.byteLength(list[i])
  6067. length += lengths[i]
  6068. }
  6069. result = Buffer.allocUnsafe(length)
  6070. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6071. if (typeof list[i] !== 'string') {
  6072. list[i].copy(result, pos)
  6073. pos += lengths[i]
  6074. } else {
  6075. result.write(list[i], pos)
  6076. pos += lengths[i]
  6077. }
  6078. }
  6079. return result
  6080. }
  6081. module.exports = generate
  6082. },{"./writeToStream":89,"events":13,"inherits":80,"safe-buffer":110}],84:[function(require,module,exports){
  6083. 'use strict'
  6084. exports.parser = require('./parser')
  6085. exports.generate = require('./generate')
  6086. exports.writeToStream = require('./writeToStream')
  6087. },{"./generate":83,"./parser":88,"./writeToStream":89}],85:[function(require,module,exports){
  6088. var DuplexStream = require('readable-stream/duplex')
  6089. , util = require('util')
  6090. , Buffer = require('safe-buffer').Buffer
  6091. function BufferList (callback) {
  6092. if (!(this instanceof BufferList))
  6093. return new BufferList(callback)
  6094. this._bufs = []
  6095. this.length = 0
  6096. if (typeof callback == 'function') {
  6097. this._callback = callback
  6098. var piper = function piper (err) {
  6099. if (this._callback) {
  6100. this._callback(err)
  6101. this._callback = null
  6102. }
  6103. }.bind(this)
  6104. this.on('pipe', function onPipe (src) {
  6105. src.on('error', piper)
  6106. })
  6107. this.on('unpipe', function onUnpipe (src) {
  6108. src.removeListener('error', piper)
  6109. })
  6110. } else {
  6111. this.append(callback)
  6112. }
  6113. DuplexStream.call(this)
  6114. }
  6115. util.inherits(BufferList, DuplexStream)
  6116. BufferList.prototype._offset = function _offset (offset) {
  6117. var tot = 0, i = 0, _t
  6118. if (offset === 0) return [ 0, 0 ]
  6119. for (; i < this._bufs.length; i++) {
  6120. _t = tot + this._bufs[i].length
  6121. if (offset < _t || i == this._bufs.length - 1)
  6122. return [ i, offset - tot ]
  6123. tot = _t
  6124. }
  6125. }
  6126. BufferList.prototype.append = function append (buf) {
  6127. var i = 0
  6128. if (Buffer.isBuffer(buf)) {
  6129. this._appendBuffer(buf);
  6130. } else if (Array.isArray(buf)) {
  6131. for (; i < buf.length; i++)
  6132. this.append(buf[i])
  6133. } else if (buf instanceof BufferList) {
  6134. // unwrap argument into individual BufferLists
  6135. for (; i < buf._bufs.length; i++)
  6136. this.append(buf._bufs[i])
  6137. } else if (buf != null) {
  6138. // coerce number arguments to strings, since Buffer(number) does
  6139. // uninitialized memory allocation
  6140. if (typeof buf == 'number')
  6141. buf = buf.toString()
  6142. this._appendBuffer(Buffer.from(buf));
  6143. }
  6144. return this
  6145. }
  6146. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  6147. this._bufs.push(buf)
  6148. this.length += buf.length
  6149. }
  6150. BufferList.prototype._write = function _write (buf, encoding, callback) {
  6151. this._appendBuffer(buf)
  6152. if (typeof callback == 'function')
  6153. callback()
  6154. }
  6155. BufferList.prototype._read = function _read (size) {
  6156. if (!this.length)
  6157. return this.push(null)
  6158. size = Math.min(size, this.length)
  6159. this.push(this.slice(0, size))
  6160. this.consume(size)
  6161. }
  6162. BufferList.prototype.end = function end (chunk) {
  6163. DuplexStream.prototype.end.call(this, chunk)
  6164. if (this._callback) {
  6165. this._callback(null, this.slice())
  6166. this._callback = null
  6167. }
  6168. }
  6169. BufferList.prototype.get = function get (index) {
  6170. return this.slice(index, index + 1)[0]
  6171. }
  6172. BufferList.prototype.slice = function slice (start, end) {
  6173. if (typeof start == 'number' && start < 0)
  6174. start += this.length
  6175. if (typeof end == 'number' && end < 0)
  6176. end += this.length
  6177. return this.copy(null, 0, start, end)
  6178. }
  6179. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  6180. if (typeof srcStart != 'number' || srcStart < 0)
  6181. srcStart = 0
  6182. if (typeof srcEnd != 'number' || srcEnd > this.length)
  6183. srcEnd = this.length
  6184. if (srcStart >= this.length)
  6185. return dst || Buffer.alloc(0)
  6186. if (srcEnd <= 0)
  6187. return dst || Buffer.alloc(0)
  6188. var copy = !!dst
  6189. , off = this._offset(srcStart)
  6190. , len = srcEnd - srcStart
  6191. , bytes = len
  6192. , bufoff = (copy && dstStart) || 0
  6193. , start = off[1]
  6194. , l
  6195. , i
  6196. // copy/slice everything
  6197. if (srcStart === 0 && srcEnd == this.length) {
  6198. if (!copy) { // slice, but full concat if multiple buffers
  6199. return this._bufs.length === 1
  6200. ? this._bufs[0]
  6201. : Buffer.concat(this._bufs, this.length)
  6202. }
  6203. // copy, need to copy individual buffers
  6204. for (i = 0; i < this._bufs.length; i++) {
  6205. this._bufs[i].copy(dst, bufoff)
  6206. bufoff += this._bufs[i].length
  6207. }
  6208. return dst
  6209. }
  6210. // easy, cheap case where it's a subset of one of the buffers
  6211. if (bytes <= this._bufs[off[0]].length - start) {
  6212. return copy
  6213. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  6214. : this._bufs[off[0]].slice(start, start + bytes)
  6215. }
  6216. if (!copy) // a slice, we need something to copy in to
  6217. dst = Buffer.allocUnsafe(len)
  6218. for (i = off[0]; i < this._bufs.length; i++) {
  6219. l = this._bufs[i].length - start
  6220. if (bytes > l) {
  6221. this._bufs[i].copy(dst, bufoff, start)
  6222. } else {
  6223. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  6224. break
  6225. }
  6226. bufoff += l
  6227. bytes -= l
  6228. if (start)
  6229. start = 0
  6230. }
  6231. return dst
  6232. }
  6233. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  6234. start = start || 0
  6235. end = end || this.length
  6236. if (start < 0)
  6237. start += this.length
  6238. if (end < 0)
  6239. end += this.length
  6240. var startOffset = this._offset(start)
  6241. , endOffset = this._offset(end)
  6242. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  6243. if (endOffset[1] == 0)
  6244. buffers.pop()
  6245. else
  6246. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  6247. if (startOffset[1] != 0)
  6248. buffers[0] = buffers[0].slice(startOffset[1])
  6249. return new BufferList(buffers)
  6250. }
  6251. BufferList.prototype.toString = function toString (encoding, start, end) {
  6252. return this.slice(start, end).toString(encoding)
  6253. }
  6254. BufferList.prototype.consume = function consume (bytes) {
  6255. while (this._bufs.length) {
  6256. if (bytes >= this._bufs[0].length) {
  6257. bytes -= this._bufs[0].length
  6258. this.length -= this._bufs[0].length
  6259. this._bufs.shift()
  6260. } else {
  6261. this._bufs[0] = this._bufs[0].slice(bytes)
  6262. this.length -= bytes
  6263. break
  6264. }
  6265. }
  6266. return this
  6267. }
  6268. BufferList.prototype.duplicate = function duplicate () {
  6269. var i = 0
  6270. , copy = new BufferList()
  6271. for (; i < this._bufs.length; i++)
  6272. copy.append(this._bufs[i])
  6273. return copy
  6274. }
  6275. BufferList.prototype.destroy = function destroy () {
  6276. this._bufs.length = 0
  6277. this.length = 0
  6278. this.push(null)
  6279. }
  6280. ;(function () {
  6281. var methods = {
  6282. 'readDoubleBE' : 8
  6283. , 'readDoubleLE' : 8
  6284. , 'readFloatBE' : 4
  6285. , 'readFloatLE' : 4
  6286. , 'readInt32BE' : 4
  6287. , 'readInt32LE' : 4
  6288. , 'readUInt32BE' : 4
  6289. , 'readUInt32LE' : 4
  6290. , 'readInt16BE' : 2
  6291. , 'readInt16LE' : 2
  6292. , 'readUInt16BE' : 2
  6293. , 'readUInt16LE' : 2
  6294. , 'readInt8' : 1
  6295. , 'readUInt8' : 1
  6296. }
  6297. for (var m in methods) {
  6298. (function (m) {
  6299. BufferList.prototype[m] = function (offset) {
  6300. return this.slice(offset, offset + methods[m])[m](0)
  6301. }
  6302. }(m))
  6303. }
  6304. }())
  6305. module.exports = BufferList
  6306. },{"readable-stream/duplex":97,"safe-buffer":110,"util":117}],86:[function(require,module,exports){
  6307. 'use strict'
  6308. var Buffer = require('safe-buffer').Buffer
  6309. var max = 65536
  6310. var cache = {}
  6311. function generateBuffer (i) {
  6312. var buffer = Buffer.allocUnsafe(2)
  6313. buffer.writeUInt8(i >> 8, 0)
  6314. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  6315. return buffer
  6316. }
  6317. function generateCache () {
  6318. for (var i = 0; i < max; i++) {
  6319. cache[i] = generateBuffer(i)
  6320. }
  6321. }
  6322. /**
  6323. * calcVariableByteIntLength - calculate the variable byte integer
  6324. * length field
  6325. *
  6326. * @api private
  6327. */
  6328. function calcVariableByteIntLength (length) {
  6329. if (length >= 0 && length < 128) return 1
  6330. else if (length >= 128 && length < 16384) return 2
  6331. else if (length >= 16384 && length < 2097152) return 3
  6332. else if (length >= 2097152 && length < 268435456) return 4
  6333. else return 0
  6334. }
  6335. function genBufVariableByteInt (num) {
  6336. var digit = 0
  6337. var pos = 0
  6338. var length = calcVariableByteIntLength(num)
  6339. var buffer = Buffer.allocUnsafe(length)
  6340. do {
  6341. digit = num % 128 | 0
  6342. num = num / 128 | 0
  6343. if (num > 0) digit = digit | 0x80
  6344. buffer.writeUInt8(digit, pos++)
  6345. } while (num > 0)
  6346. return {
  6347. data: buffer,
  6348. length: length
  6349. }
  6350. }
  6351. function generate4ByteBuffer (num) {
  6352. var buffer = Buffer.allocUnsafe(4)
  6353. buffer.writeUInt32BE(num, 0)
  6354. return buffer
  6355. }
  6356. module.exports = {
  6357. cache: cache,
  6358. generateCache: generateCache,
  6359. generateNumber: generateBuffer,
  6360. genBufVariableByteInt: genBufVariableByteInt,
  6361. generate4ByteBuffer: generate4ByteBuffer
  6362. }
  6363. },{"safe-buffer":110}],87:[function(require,module,exports){
  6364. function Packet () {
  6365. this.cmd = null
  6366. this.retain = false
  6367. this.qos = 0
  6368. this.dup = false
  6369. this.length = -1
  6370. this.topic = null
  6371. this.payload = null
  6372. }
  6373. module.exports = Packet
  6374. },{}],88:[function(require,module,exports){
  6375. 'use strict'
  6376. var bl = require('bl')
  6377. var inherits = require('inherits')
  6378. var EE = require('events').EventEmitter
  6379. var Packet = require('./packet')
  6380. var constants = require('./constants')
  6381. function Parser (opt) {
  6382. if (!(this instanceof Parser)) return new Parser(opt)
  6383. this.settings = opt || {}
  6384. this._states = [
  6385. '_parseHeader',
  6386. '_parseLength',
  6387. '_parsePayload',
  6388. '_newPacket'
  6389. ]
  6390. this._resetState()
  6391. }
  6392. inherits(Parser, EE)
  6393. Parser.prototype._resetState = function () {
  6394. this.packet = new Packet()
  6395. this.error = null
  6396. this._list = bl()
  6397. this._stateCounter = 0
  6398. }
  6399. Parser.prototype.parse = function (buf) {
  6400. if (this.error) this._resetState()
  6401. this._list.append(buf)
  6402. while ((this.packet.length !== -1 || this._list.length > 0) &&
  6403. this[this._states[this._stateCounter]]() &&
  6404. !this.error) {
  6405. this._stateCounter++
  6406. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  6407. }
  6408. return this._list.length
  6409. }
  6410. Parser.prototype._parseHeader = function () {
  6411. // There is at least one byte in the buffer
  6412. var zero = this._list.readUInt8(0)
  6413. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  6414. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  6415. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  6416. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  6417. this._list.consume(1)
  6418. return true
  6419. }
  6420. Parser.prototype._parseLength = function () {
  6421. // There is at least one byte in the list
  6422. var result = this._parseVarByteNum(true)
  6423. if (result) {
  6424. this.packet.length = result.value
  6425. this._list.consume(result.bytes)
  6426. }
  6427. return !!result
  6428. }
  6429. Parser.prototype._parsePayload = function () {
  6430. var result = false
  6431. // Do we have a payload? Do we have enough data to complete the payload?
  6432. // PINGs have no payload
  6433. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  6434. this._pos = 0
  6435. switch (this.packet.cmd) {
  6436. case 'connect':
  6437. this._parseConnect()
  6438. break
  6439. case 'connack':
  6440. this._parseConnack()
  6441. break
  6442. case 'publish':
  6443. this._parsePublish()
  6444. break
  6445. case 'puback':
  6446. case 'pubrec':
  6447. case 'pubrel':
  6448. case 'pubcomp':
  6449. this._parseConfirmation()
  6450. break
  6451. case 'subscribe':
  6452. this._parseSubscribe()
  6453. break
  6454. case 'suback':
  6455. this._parseSuback()
  6456. break
  6457. case 'unsubscribe':
  6458. this._parseUnsubscribe()
  6459. break
  6460. case 'unsuback':
  6461. this._parseUnsuback()
  6462. break
  6463. case 'pingreq':
  6464. case 'pingresp':
  6465. // These are empty, nothing to do
  6466. break
  6467. case 'disconnect':
  6468. this._parseDisconnect()
  6469. break
  6470. case 'auth':
  6471. this._parseAuth()
  6472. break
  6473. default:
  6474. this._emitError(new Error('Not supported'))
  6475. }
  6476. result = true
  6477. }
  6478. return result
  6479. }
  6480. Parser.prototype._parseConnect = function () {
  6481. var protocolId // Protocol ID
  6482. var clientId // Client ID
  6483. var topic // Will topic
  6484. var payload // Will payload
  6485. var password // Password
  6486. var username // Username
  6487. var flags = {}
  6488. var packet = this.packet
  6489. // Parse protocolId
  6490. protocolId = this._parseString()
  6491. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  6492. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  6493. return this._emitError(new Error('Invalid protocolId'))
  6494. }
  6495. packet.protocolId = protocolId
  6496. // Parse constants version number
  6497. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  6498. packet.protocolVersion = this._list.readUInt8(this._pos)
  6499. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  6500. return this._emitError(new Error('Invalid protocol version'))
  6501. }
  6502. this._pos++
  6503. if (this._pos >= this._list.length) {
  6504. return this._emitError(new Error('Packet too short'))
  6505. }
  6506. // Parse connect flags
  6507. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  6508. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  6509. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  6510. if (flags.will) {
  6511. packet.will = {}
  6512. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  6513. packet.will.qos = (this._list.readUInt8(this._pos) &
  6514. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  6515. }
  6516. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  6517. this._pos++
  6518. // Parse keepalive
  6519. packet.keepalive = this._parseNum()
  6520. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  6521. // parse properties
  6522. if (packet.protocolVersion === 5) {
  6523. var properties = this._parseProperties()
  6524. if (Object.getOwnPropertyNames(properties).length) {
  6525. packet.properties = properties
  6526. }
  6527. }
  6528. // Parse clientId
  6529. clientId = this._parseString()
  6530. if (clientId === null) return this._emitError(new Error('Packet too short'))
  6531. packet.clientId = clientId
  6532. if (flags.will) {
  6533. if (packet.protocolVersion === 5) {
  6534. var willProperties = this._parseProperties()
  6535. if (Object.getOwnPropertyNames(willProperties).length) {
  6536. packet.will.properties = willProperties
  6537. }
  6538. }
  6539. // Parse will topic
  6540. topic = this._parseString()
  6541. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  6542. packet.will.topic = topic
  6543. // Parse will payload
  6544. payload = this._parseBuffer()
  6545. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  6546. packet.will.payload = payload
  6547. }
  6548. // Parse username
  6549. if (flags.username) {
  6550. username = this._parseString()
  6551. if (username === null) return this._emitError(new Error('Cannot parse username'))
  6552. packet.username = username
  6553. }
  6554. // Parse password
  6555. if (flags.password) {
  6556. password = this._parseBuffer()
  6557. if (password === null) return this._emitError(new Error('Cannot parse password'))
  6558. packet.password = password
  6559. }
  6560. // need for right parse auth packet and self set up
  6561. this.settings = packet
  6562. return packet
  6563. }
  6564. Parser.prototype._parseConnack = function () {
  6565. var packet = this.packet
  6566. if (this._list.length < 2) return null
  6567. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  6568. if (this.settings.protocolVersion === 5) {
  6569. packet.reasonCode = this._list.readUInt8(this._pos++)
  6570. } else {
  6571. packet.returnCode = this._list.readUInt8(this._pos++)
  6572. }
  6573. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  6574. // mqtt 5 properties
  6575. if (this.settings.protocolVersion === 5) {
  6576. var properties = this._parseProperties()
  6577. if (Object.getOwnPropertyNames(properties).length) {
  6578. packet.properties = properties
  6579. }
  6580. }
  6581. }
  6582. Parser.prototype._parsePublish = function () {
  6583. var packet = this.packet
  6584. packet.topic = this._parseString()
  6585. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  6586. // Parse messageId
  6587. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  6588. // Properties mqtt 5
  6589. if (this.settings.protocolVersion === 5) {
  6590. var properties = this._parseProperties()
  6591. if (Object.getOwnPropertyNames(properties).length) {
  6592. packet.properties = properties
  6593. }
  6594. }
  6595. packet.payload = this._list.slice(this._pos, packet.length)
  6596. }
  6597. Parser.prototype._parseSubscribe = function () {
  6598. var packet = this.packet
  6599. var topic
  6600. var options
  6601. var qos
  6602. var rh
  6603. var rap
  6604. var nl
  6605. var subscription
  6606. if (packet.qos !== 1) {
  6607. return this._emitError(new Error('Wrong subscribe header'))
  6608. }
  6609. packet.subscriptions = []
  6610. if (!this._parseMessageId()) { return }
  6611. // Properties mqtt 5
  6612. if (this.settings.protocolVersion === 5) {
  6613. var properties = this._parseProperties()
  6614. if (Object.getOwnPropertyNames(properties).length) {
  6615. packet.properties = properties
  6616. }
  6617. }
  6618. while (this._pos < packet.length) {
  6619. // Parse topic
  6620. topic = this._parseString()
  6621. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  6622. options = this._parseByte()
  6623. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  6624. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  6625. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  6626. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  6627. subscription = { topic: topic, qos: qos }
  6628. // mqtt 5 options
  6629. if (this.settings.protocolVersion === 5) {
  6630. subscription.nl = nl
  6631. subscription.rap = rap
  6632. subscription.rh = rh
  6633. }
  6634. // Push pair to subscriptions
  6635. packet.subscriptions.push(subscription)
  6636. }
  6637. }
  6638. Parser.prototype._parseSuback = function () {
  6639. var packet = this.packet
  6640. this.packet.granted = []
  6641. if (!this._parseMessageId()) { return }
  6642. // Properties mqtt 5
  6643. if (this.settings.protocolVersion === 5) {
  6644. var properties = this._parseProperties()
  6645. if (Object.getOwnPropertyNames(properties).length) {
  6646. packet.properties = properties
  6647. }
  6648. }
  6649. // Parse granted QoSes
  6650. while (this._pos < this.packet.length) {
  6651. this.packet.granted.push(this._list.readUInt8(this._pos++))
  6652. }
  6653. }
  6654. Parser.prototype._parseUnsubscribe = function () {
  6655. var packet = this.packet
  6656. packet.unsubscriptions = []
  6657. // Parse messageId
  6658. if (!this._parseMessageId()) { return }
  6659. // Properties mqtt 5
  6660. if (this.settings.protocolVersion === 5) {
  6661. var properties = this._parseProperties()
  6662. if (Object.getOwnPropertyNames(properties).length) {
  6663. packet.properties = properties
  6664. }
  6665. }
  6666. while (this._pos < packet.length) {
  6667. var topic
  6668. // Parse topic
  6669. topic = this._parseString()
  6670. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  6671. // Push topic to unsubscriptions
  6672. packet.unsubscriptions.push(topic)
  6673. }
  6674. }
  6675. Parser.prototype._parseUnsuback = function () {
  6676. var packet = this.packet
  6677. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  6678. // Properties mqtt 5
  6679. if (this.settings.protocolVersion === 5) {
  6680. var properties = this._parseProperties()
  6681. if (Object.getOwnPropertyNames(properties).length) {
  6682. packet.properties = properties
  6683. }
  6684. // Parse granted QoSes
  6685. packet.granted = []
  6686. while (this._pos < this.packet.length) {
  6687. this.packet.granted.push(this._list.readUInt8(this._pos++))
  6688. }
  6689. }
  6690. }
  6691. // parse packets like puback, pubrec, pubrel, pubcomp
  6692. Parser.prototype._parseConfirmation = function () {
  6693. var packet = this.packet
  6694. this._parseMessageId()
  6695. if (this.settings.protocolVersion === 5) {
  6696. if (packet.length > 2) {
  6697. // response code
  6698. packet.reasonCode = this._parseByte()
  6699. // properies mqtt 5
  6700. var properties = this._parseProperties()
  6701. if (Object.getOwnPropertyNames(properties).length) {
  6702. packet.properties = properties
  6703. }
  6704. }
  6705. }
  6706. return true
  6707. }
  6708. // parse disconnect packet
  6709. Parser.prototype._parseDisconnect = function () {
  6710. var packet = this.packet
  6711. if (this.settings.protocolVersion === 5) {
  6712. // response code
  6713. packet.reasonCode = this._parseByte()
  6714. // properies mqtt 5
  6715. var properties = this._parseProperties()
  6716. if (Object.getOwnPropertyNames(properties).length) {
  6717. packet.properties = properties
  6718. }
  6719. }
  6720. return true
  6721. }
  6722. // parse auth packet
  6723. Parser.prototype._parseAuth = function () {
  6724. var packet = this.packet
  6725. if (this.settings.protocolVersion !== 5) {
  6726. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  6727. }
  6728. // response code
  6729. packet.reasonCode = this._parseByte()
  6730. // properies mqtt 5
  6731. var properties = this._parseProperties()
  6732. if (Object.getOwnPropertyNames(properties).length) {
  6733. packet.properties = properties
  6734. }
  6735. return true
  6736. }
  6737. Parser.prototype._parseMessageId = function () {
  6738. var packet = this.packet
  6739. packet.messageId = this._parseNum()
  6740. if (packet.messageId === null) {
  6741. this._emitError(new Error('Cannot parse messageId'))
  6742. return false
  6743. }
  6744. return true
  6745. }
  6746. Parser.prototype._parseString = function (maybeBuffer) {
  6747. var length = this._parseNum()
  6748. var result
  6749. var end = length + this._pos
  6750. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  6751. result = this._list.toString('utf8', this._pos, end)
  6752. this._pos += length
  6753. return result
  6754. }
  6755. Parser.prototype._parseStringPair = function () {
  6756. return {
  6757. name: this._parseString(),
  6758. value: this._parseString()
  6759. }
  6760. }
  6761. Parser.prototype._parseBuffer = function () {
  6762. var length = this._parseNum()
  6763. var result
  6764. var end = length + this._pos
  6765. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  6766. result = this._list.slice(this._pos, end)
  6767. this._pos += length
  6768. return result
  6769. }
  6770. Parser.prototype._parseNum = function () {
  6771. if (this._list.length - this._pos < 2) return -1
  6772. var result = this._list.readUInt16BE(this._pos)
  6773. this._pos += 2
  6774. return result
  6775. }
  6776. Parser.prototype._parse4ByteNum = function () {
  6777. if (this._list.length - this._pos < 4) return -1
  6778. var result = this._list.readUInt32BE(this._pos)
  6779. this._pos += 4
  6780. return result
  6781. }
  6782. Parser.prototype._parseVarByteNum = function (fullInfoFlag) {
  6783. var bytes = 0
  6784. var mul = 1
  6785. var length = 0
  6786. var result = true
  6787. var current
  6788. var padding = this._pos ? this._pos : 0
  6789. while (bytes < 5) {
  6790. current = this._list.readUInt8(padding + bytes++)
  6791. length += mul * (current & constants.LENGTH_MASK)
  6792. mul *= 0x80
  6793. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  6794. if (this._list.length <= bytes) {
  6795. result = false
  6796. break
  6797. }
  6798. }
  6799. if (padding) {
  6800. this._pos += bytes
  6801. }
  6802. result = result
  6803. ? fullInfoFlag ? {
  6804. bytes: bytes,
  6805. value: length
  6806. } : length
  6807. : false
  6808. return result
  6809. }
  6810. Parser.prototype._parseByte = function () {
  6811. var result = this._list.readUInt8(this._pos)
  6812. this._pos++
  6813. return result
  6814. }
  6815. Parser.prototype._parseByType = function (type) {
  6816. switch (type) {
  6817. case 'byte': {
  6818. return this._parseByte() !== 0
  6819. }
  6820. case 'int8': {
  6821. return this._parseByte()
  6822. }
  6823. case 'int16': {
  6824. return this._parseNum()
  6825. }
  6826. case 'int32': {
  6827. return this._parse4ByteNum()
  6828. }
  6829. case 'var': {
  6830. return this._parseVarByteNum()
  6831. }
  6832. case 'string': {
  6833. return this._parseString()
  6834. }
  6835. case 'pair': {
  6836. return this._parseStringPair()
  6837. }
  6838. case 'binary': {
  6839. return this._parseBuffer()
  6840. }
  6841. }
  6842. }
  6843. Parser.prototype._parseProperties = function () {
  6844. var length = this._parseVarByteNum()
  6845. var start = this._pos
  6846. var end = start + length
  6847. var result = {}
  6848. while (this._pos < end) {
  6849. var type = this._parseByte()
  6850. var name = constants.propertiesCodes[type]
  6851. if (!name) {
  6852. this._emitError(new Error('Unknown property'))
  6853. return false
  6854. }
  6855. // user properties process
  6856. if (name === 'userProperties') {
  6857. if (!result[name]) {
  6858. result[name] = {}
  6859. }
  6860. var currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  6861. result[name][currentUserProperty.name] = currentUserProperty.value
  6862. continue
  6863. }
  6864. result[name] = this._parseByType(constants.propertiesTypes[name])
  6865. }
  6866. return result
  6867. }
  6868. Parser.prototype._newPacket = function () {
  6869. if (this.packet) {
  6870. this._list.consume(this.packet.length)
  6871. this.emit('packet', this.packet)
  6872. }
  6873. this.packet = new Packet()
  6874. this._pos = 0
  6875. return true
  6876. }
  6877. Parser.prototype._emitError = function (err) {
  6878. this.error = err
  6879. this.emit('error', err)
  6880. }
  6881. module.exports = Parser
  6882. },{"./constants":82,"./packet":87,"bl":85,"events":13,"inherits":80}],89:[function(require,module,exports){
  6883. 'use strict'
  6884. var protocol = require('./constants')
  6885. var Buffer = require('safe-buffer').Buffer
  6886. var empty = Buffer.allocUnsafe(0)
  6887. var zeroBuf = Buffer.from([0])
  6888. var numbers = require('./numbers')
  6889. var nextTick = require('process-nextick-args').nextTick
  6890. var numCache = numbers.cache
  6891. var generateNumber = numbers.generateNumber
  6892. var generateCache = numbers.generateCache
  6893. var genBufVariableByteInt = numbers.genBufVariableByteInt
  6894. var generate4ByteBuffer = numbers.generate4ByteBuffer
  6895. var writeNumber = writeNumberCached
  6896. var toGenerate = true
  6897. function generate (packet, stream, opts) {
  6898. if (stream.cork) {
  6899. stream.cork()
  6900. nextTick(uncork, stream)
  6901. }
  6902. if (toGenerate) {
  6903. toGenerate = false
  6904. generateCache()
  6905. }
  6906. switch (packet.cmd) {
  6907. case 'connect':
  6908. return connect(packet, stream, opts)
  6909. case 'connack':
  6910. return connack(packet, stream, opts)
  6911. case 'publish':
  6912. return publish(packet, stream, opts)
  6913. case 'puback':
  6914. case 'pubrec':
  6915. case 'pubrel':
  6916. case 'pubcomp':
  6917. return confirmation(packet, stream, opts)
  6918. case 'subscribe':
  6919. return subscribe(packet, stream, opts)
  6920. case 'suback':
  6921. return suback(packet, stream, opts)
  6922. case 'unsubscribe':
  6923. return unsubscribe(packet, stream, opts)
  6924. case 'unsuback':
  6925. return unsuback(packet, stream, opts)
  6926. case 'pingreq':
  6927. case 'pingresp':
  6928. return emptyPacket(packet, stream, opts)
  6929. case 'disconnect':
  6930. return disconnect(packet, stream, opts)
  6931. case 'auth':
  6932. return auth(packet, stream, opts)
  6933. default:
  6934. stream.emit('error', new Error('Unknown command'))
  6935. return false
  6936. }
  6937. }
  6938. /**
  6939. * Controls numbers cache.
  6940. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  6941. */
  6942. Object.defineProperty(generate, 'cacheNumbers', {
  6943. get: function () {
  6944. return writeNumber === writeNumberCached
  6945. },
  6946. set: function (value) {
  6947. if (value) {
  6948. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  6949. writeNumber = writeNumberCached
  6950. } else {
  6951. toGenerate = false
  6952. writeNumber = writeNumberGenerated
  6953. }
  6954. }
  6955. })
  6956. function uncork (stream) {
  6957. stream.uncork()
  6958. }
  6959. function connect (packet, stream, opts) {
  6960. var settings = packet || {}
  6961. var protocolId = settings.protocolId || 'MQTT'
  6962. var protocolVersion = settings.protocolVersion || 4
  6963. var will = settings.will
  6964. var clean = settings.clean
  6965. var keepalive = settings.keepalive || 0
  6966. var clientId = settings.clientId || ''
  6967. var username = settings.username
  6968. var password = settings.password
  6969. /* mqtt5 new oprions */
  6970. var properties = settings.properties
  6971. if (clean === undefined) clean = true
  6972. var length = 0
  6973. // Must be a string and non-falsy
  6974. if (!protocolId ||
  6975. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  6976. stream.emit('error', new Error('Invalid protocolId'))
  6977. return false
  6978. } else length += protocolId.length + 2
  6979. // Must be 3 or 4 or 5
  6980. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  6981. stream.emit('error', new Error('Invalid protocol version'))
  6982. return false
  6983. } else length += 1
  6984. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  6985. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  6986. (clientId || protocolVersion === 4) && (clientId || clean)) {
  6987. length += clientId.length + 2
  6988. } else {
  6989. if (protocolVersion < 4) {
  6990. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  6991. return false
  6992. }
  6993. if ((clean * 1) === 0) {
  6994. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  6995. return false
  6996. }
  6997. }
  6998. // Must be a two byte number
  6999. if (typeof keepalive !== 'number' ||
  7000. keepalive < 0 ||
  7001. keepalive > 65535 ||
  7002. keepalive % 1 !== 0) {
  7003. stream.emit('error', new Error('Invalid keepalive'))
  7004. return false
  7005. } else length += 2
  7006. // Connect flags
  7007. length += 1
  7008. // Properties
  7009. if (protocolVersion === 5) {
  7010. var propertiesData = getProperties(stream, properties)
  7011. length += propertiesData.length
  7012. }
  7013. // If will exists...
  7014. if (will) {
  7015. // It must be an object
  7016. if (typeof will !== 'object') {
  7017. stream.emit('error', new Error('Invalid will'))
  7018. return false
  7019. }
  7020. // It must have topic typeof string
  7021. if (!will.topic || typeof will.topic !== 'string') {
  7022. stream.emit('error', new Error('Invalid will topic'))
  7023. return false
  7024. } else {
  7025. length += Buffer.byteLength(will.topic) + 2
  7026. }
  7027. // Payload
  7028. if (will.payload) {
  7029. if (will.payload.length >= 0) {
  7030. if (typeof will.payload === 'string') {
  7031. length += Buffer.byteLength(will.payload) + 2
  7032. } else {
  7033. length += will.payload.length + 2
  7034. }
  7035. } else {
  7036. stream.emit('error', new Error('Invalid will payload'))
  7037. return false
  7038. }
  7039. // will properties
  7040. var willProperties = {}
  7041. if (protocolVersion === 5) {
  7042. willProperties = getProperties(stream, will.properties)
  7043. length += willProperties.length
  7044. }
  7045. }
  7046. }
  7047. // Username
  7048. var providedUsername = false
  7049. if (username != null) {
  7050. if (isStringOrBuffer(username)) {
  7051. providedUsername = true
  7052. length += Buffer.byteLength(username) + 2
  7053. } else {
  7054. stream.emit('error', new Error('Invalid username'))
  7055. return false
  7056. }
  7057. }
  7058. // Password
  7059. if (password != null) {
  7060. if (!providedUsername) {
  7061. stream.emit('error', new Error('Username is required to use password'))
  7062. return false
  7063. }
  7064. if (isStringOrBuffer(password)) {
  7065. length += byteLength(password) + 2
  7066. } else {
  7067. stream.emit('error', new Error('Invalid password'))
  7068. return false
  7069. }
  7070. }
  7071. // Generate header
  7072. stream.write(protocol.CONNECT_HEADER)
  7073. // Generate length
  7074. writeVarByteInt(stream, length)
  7075. // Generate protocol ID
  7076. writeStringOrBuffer(stream, protocolId)
  7077. stream.write(
  7078. protocolVersion === 4
  7079. ? protocol.VERSION4
  7080. : protocolVersion === 5
  7081. ? protocol.VERSION5
  7082. : protocol.VERSION3
  7083. )
  7084. // Connect flags
  7085. var flags = 0
  7086. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  7087. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  7088. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  7089. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  7090. flags |= will ? protocol.WILL_FLAG_MASK : 0
  7091. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  7092. stream.write(Buffer.from([flags]))
  7093. // Keepalive
  7094. writeNumber(stream, keepalive)
  7095. // Properties
  7096. if (protocolVersion === 5) {
  7097. propertiesData.write()
  7098. }
  7099. // Client ID
  7100. writeStringOrBuffer(stream, clientId)
  7101. // Will
  7102. if (will) {
  7103. if (protocolVersion === 5) {
  7104. willProperties.write()
  7105. }
  7106. writeString(stream, will.topic)
  7107. writeStringOrBuffer(stream, will.payload)
  7108. }
  7109. // Username and password
  7110. if (username != null) {
  7111. writeStringOrBuffer(stream, username)
  7112. }
  7113. if (password != null) {
  7114. writeStringOrBuffer(stream, password)
  7115. }
  7116. // This is a small packet that happens only once on a stream
  7117. // We assume the stream is always free to receive more data after this
  7118. return true
  7119. }
  7120. function connack (packet, stream, opts) {
  7121. var version = opts ? opts.protocolVersion : 4
  7122. var settings = packet || {}
  7123. var rc = version === 5 ? settings.reasonCode : settings.returnCode
  7124. var properties = settings.properties
  7125. var length = 2 // length of rc and sessionHeader
  7126. // Check return code
  7127. if (typeof rc !== 'number') {
  7128. stream.emit('error', new Error('Invalid return code'))
  7129. return false
  7130. }
  7131. // mqtt5 properties
  7132. var propertiesData = null
  7133. if (version === 5) {
  7134. propertiesData = getProperties(stream, properties)
  7135. length += propertiesData.length
  7136. }
  7137. stream.write(protocol.CONNACK_HEADER)
  7138. // length
  7139. writeVarByteInt(stream, length)
  7140. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  7141. stream.write(Buffer.from([rc]))
  7142. if (propertiesData != null) {
  7143. propertiesData.write()
  7144. }
  7145. return true
  7146. }
  7147. function publish (packet, stream, opts) {
  7148. var version = opts ? opts.protocolVersion : 4
  7149. var settings = packet || {}
  7150. var qos = settings.qos || 0
  7151. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  7152. var topic = settings.topic
  7153. var payload = settings.payload || empty
  7154. var id = settings.messageId
  7155. var properties = settings.properties
  7156. var length = 0
  7157. // Topic must be a non-empty string or Buffer
  7158. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  7159. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  7160. else {
  7161. stream.emit('error', new Error('Invalid topic'))
  7162. return false
  7163. }
  7164. // Get the payload length
  7165. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  7166. else length += payload.length
  7167. // Message ID must a number if qos > 0
  7168. if (qos && typeof id !== 'number') {
  7169. stream.emit('error', new Error('Invalid messageId'))
  7170. return false
  7171. } else if (qos) length += 2
  7172. // mqtt5 properties
  7173. var propertiesData = null
  7174. if (version === 5) {
  7175. propertiesData = getProperties(stream, properties)
  7176. length += propertiesData.length
  7177. }
  7178. // Header
  7179. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  7180. // Remaining length
  7181. writeVarByteInt(stream, length)
  7182. // Topic
  7183. writeNumber(stream, byteLength(topic))
  7184. stream.write(topic)
  7185. // Message ID
  7186. if (qos > 0) writeNumber(stream, id)
  7187. // Properties
  7188. if (propertiesData != null) {
  7189. propertiesData.write()
  7190. }
  7191. // Payload
  7192. return stream.write(payload)
  7193. }
  7194. /* Puback, pubrec, pubrel and pubcomp */
  7195. function confirmation (packet, stream, opts) {
  7196. var version = opts ? opts.protocolVersion : 4
  7197. var settings = packet || {}
  7198. var type = settings.cmd || 'puback'
  7199. var id = settings.messageId
  7200. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  7201. var qos = 0
  7202. var reasonCode = settings.reasonCode
  7203. var properties = settings.properties
  7204. var length = version === 5 ? 3 : 2
  7205. if (type === 'pubrel') qos = 1
  7206. // Check message ID
  7207. if (typeof id !== 'number') {
  7208. stream.emit('error', new Error('Invalid messageId'))
  7209. return false
  7210. }
  7211. // properies mqtt 5
  7212. var propertiesData = null
  7213. if (version === 5) {
  7214. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7215. if (!propertiesData) { return false }
  7216. length += propertiesData.length
  7217. }
  7218. // Header
  7219. stream.write(protocol.ACKS[type][qos][dup][0])
  7220. // Length
  7221. writeVarByteInt(stream, length)
  7222. // Message ID
  7223. writeNumber(stream, id)
  7224. // reason code in header
  7225. if (version === 5) {
  7226. stream.write(Buffer.from([reasonCode]))
  7227. }
  7228. // properies mqtt 5
  7229. if (propertiesData !== null) {
  7230. propertiesData.write()
  7231. }
  7232. return true
  7233. }
  7234. function subscribe (packet, stream, opts) {
  7235. var version = opts ? opts.protocolVersion : 4
  7236. var settings = packet || {}
  7237. var dup = settings.dup ? protocol.DUP_MASK : 0
  7238. var id = settings.messageId
  7239. var subs = settings.subscriptions
  7240. var properties = settings.properties
  7241. var length = 0
  7242. // Check message ID
  7243. if (typeof id !== 'number') {
  7244. stream.emit('error', new Error('Invalid messageId'))
  7245. return false
  7246. } else length += 2
  7247. // properies mqtt 5
  7248. var propertiesData = null
  7249. if (version === 5) {
  7250. propertiesData = getProperties(stream, properties)
  7251. length += propertiesData.length
  7252. }
  7253. // Check subscriptions
  7254. if (typeof subs === 'object' && subs.length) {
  7255. for (var i = 0; i < subs.length; i += 1) {
  7256. var itopic = subs[i].topic
  7257. var iqos = subs[i].qos
  7258. if (typeof itopic !== 'string') {
  7259. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  7260. return false
  7261. }
  7262. if (typeof iqos !== 'number') {
  7263. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  7264. return false
  7265. }
  7266. if (version === 5) {
  7267. var nl = subs[i].nl || false
  7268. if (typeof nl !== 'boolean') {
  7269. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  7270. return false
  7271. }
  7272. var rap = subs[i].rap || false
  7273. if (typeof rap !== 'boolean') {
  7274. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  7275. return false
  7276. }
  7277. var rh = subs[i].rh || 0
  7278. if (typeof rh !== 'number' || rh > 2) {
  7279. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  7280. return false
  7281. }
  7282. }
  7283. length += Buffer.byteLength(itopic) + 2 + 1
  7284. }
  7285. } else {
  7286. stream.emit('error', new Error('Invalid subscriptions'))
  7287. return false
  7288. }
  7289. // Generate header
  7290. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  7291. // Generate length
  7292. writeVarByteInt(stream, length)
  7293. // Generate message ID
  7294. writeNumber(stream, id)
  7295. // properies mqtt 5
  7296. if (propertiesData !== null) {
  7297. propertiesData.write()
  7298. }
  7299. var result = true
  7300. // Generate subs
  7301. for (var j = 0; j < subs.length; j++) {
  7302. var sub = subs[j]
  7303. var jtopic = sub.topic
  7304. var jqos = sub.qos
  7305. var jnl = +sub.nl
  7306. var jrap = +sub.rap
  7307. var jrh = sub.rh
  7308. var joptions
  7309. // Write topic string
  7310. writeString(stream, jtopic)
  7311. // options process
  7312. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  7313. if (version === 5) {
  7314. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  7315. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  7316. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  7317. }
  7318. // Write options
  7319. result = stream.write(Buffer.from([joptions]))
  7320. }
  7321. return result
  7322. }
  7323. function suback (packet, stream, opts) {
  7324. var version = opts ? opts.protocolVersion : 4
  7325. var settings = packet || {}
  7326. var id = settings.messageId
  7327. var granted = settings.granted
  7328. var properties = settings.properties
  7329. var length = 0
  7330. // Check message ID
  7331. if (typeof id !== 'number') {
  7332. stream.emit('error', new Error('Invalid messageId'))
  7333. return false
  7334. } else length += 2
  7335. // Check granted qos vector
  7336. if (typeof granted === 'object' && granted.length) {
  7337. for (var i = 0; i < granted.length; i += 1) {
  7338. if (typeof granted[i] !== 'number') {
  7339. stream.emit('error', new Error('Invalid qos vector'))
  7340. return false
  7341. }
  7342. length += 1
  7343. }
  7344. } else {
  7345. stream.emit('error', new Error('Invalid qos vector'))
  7346. return false
  7347. }
  7348. // properies mqtt 5
  7349. var propertiesData = null
  7350. if (version === 5) {
  7351. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7352. if (!propertiesData) { return false }
  7353. length += propertiesData.length
  7354. }
  7355. // header
  7356. stream.write(protocol.SUBACK_HEADER)
  7357. // Length
  7358. writeVarByteInt(stream, length)
  7359. // Message ID
  7360. writeNumber(stream, id)
  7361. // properies mqtt 5
  7362. if (propertiesData !== null) {
  7363. propertiesData.write()
  7364. }
  7365. return stream.write(Buffer.from(granted))
  7366. }
  7367. function unsubscribe (packet, stream, opts) {
  7368. var version = opts ? opts.protocolVersion : 4
  7369. var settings = packet || {}
  7370. var id = settings.messageId
  7371. var dup = settings.dup ? protocol.DUP_MASK : 0
  7372. var unsubs = settings.unsubscriptions
  7373. var properties = settings.properties
  7374. var length = 0
  7375. // Check message ID
  7376. if (typeof id !== 'number') {
  7377. stream.emit('error', new Error('Invalid messageId'))
  7378. return false
  7379. } else {
  7380. length += 2
  7381. }
  7382. // Check unsubs
  7383. if (typeof unsubs === 'object' && unsubs.length) {
  7384. for (var i = 0; i < unsubs.length; i += 1) {
  7385. if (typeof unsubs[i] !== 'string') {
  7386. stream.emit('error', new Error('Invalid unsubscriptions'))
  7387. return false
  7388. }
  7389. length += Buffer.byteLength(unsubs[i]) + 2
  7390. }
  7391. } else {
  7392. stream.emit('error', new Error('Invalid unsubscriptions'))
  7393. return false
  7394. }
  7395. // properies mqtt 5
  7396. var propertiesData = null
  7397. if (version === 5) {
  7398. propertiesData = getProperties(stream, properties)
  7399. length += propertiesData.length
  7400. }
  7401. // Header
  7402. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  7403. // Length
  7404. writeVarByteInt(stream, length)
  7405. // Message ID
  7406. writeNumber(stream, id)
  7407. // properies mqtt 5
  7408. if (propertiesData !== null) {
  7409. propertiesData.write()
  7410. }
  7411. // Unsubs
  7412. var result = true
  7413. for (var j = 0; j < unsubs.length; j++) {
  7414. result = writeString(stream, unsubs[j])
  7415. }
  7416. return result
  7417. }
  7418. function unsuback (packet, stream, opts) {
  7419. var version = opts ? opts.protocolVersion : 4
  7420. var settings = packet || {}
  7421. var id = settings.messageId
  7422. var dup = settings.dup ? protocol.DUP_MASK : 0
  7423. var granted = settings.granted
  7424. var properties = settings.properties
  7425. var type = settings.cmd
  7426. var qos = 0
  7427. var length = 2
  7428. // Check message ID
  7429. if (typeof id !== 'number') {
  7430. stream.emit('error', new Error('Invalid messageId'))
  7431. return false
  7432. }
  7433. // Check granted
  7434. if (version === 5) {
  7435. if (typeof granted === 'object' && granted.length) {
  7436. for (var i = 0; i < granted.length; i += 1) {
  7437. if (typeof granted[i] !== 'number') {
  7438. stream.emit('error', new Error('Invalid qos vector'))
  7439. return false
  7440. }
  7441. length += 1
  7442. }
  7443. } else {
  7444. stream.emit('error', new Error('Invalid qos vector'))
  7445. return false
  7446. }
  7447. }
  7448. // properies mqtt 5
  7449. var propertiesData = null
  7450. if (version === 5) {
  7451. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7452. if (!propertiesData) { return false }
  7453. length += propertiesData.length
  7454. }
  7455. // Header
  7456. stream.write(protocol.ACKS[type][qos][dup][0])
  7457. // Length
  7458. writeVarByteInt(stream, length)
  7459. // Message ID
  7460. writeNumber(stream, id)
  7461. // properies mqtt 5
  7462. if (propertiesData !== null) {
  7463. propertiesData.write()
  7464. }
  7465. // payload
  7466. if (version === 5) {
  7467. stream.write(Buffer.from(granted))
  7468. }
  7469. return true
  7470. }
  7471. function emptyPacket (packet, stream, opts) {
  7472. return stream.write(protocol.EMPTY[packet.cmd])
  7473. }
  7474. function disconnect (packet, stream, opts) {
  7475. var version = opts ? opts.protocolVersion : 4
  7476. var settings = packet || {}
  7477. var reasonCode = settings.reasonCode
  7478. var properties = settings.properties
  7479. var length = version === 5 ? 1 : 0
  7480. // properies mqtt 5
  7481. var propertiesData = null
  7482. if (version === 5) {
  7483. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7484. if (!propertiesData) { return false }
  7485. length += propertiesData.length
  7486. }
  7487. // Header
  7488. stream.write(Buffer.from([protocol.codes['disconnect'] << 4]))
  7489. // Length
  7490. writeVarByteInt(stream, length)
  7491. // reason code in header
  7492. if (version === 5) {
  7493. stream.write(Buffer.from([reasonCode]))
  7494. }
  7495. // properies mqtt 5
  7496. if (propertiesData !== null) {
  7497. propertiesData.write()
  7498. }
  7499. return true
  7500. }
  7501. function auth (packet, stream, opts) {
  7502. var version = opts ? opts.protocolVersion : 4
  7503. var settings = packet || {}
  7504. var reasonCode = settings.reasonCode
  7505. var properties = settings.properties
  7506. var length = version === 5 ? 1 : 0
  7507. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  7508. // properies mqtt 5
  7509. var propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7510. if (!propertiesData) { return false }
  7511. length += propertiesData.length
  7512. // Header
  7513. stream.write(Buffer.from([protocol.codes['auth'] << 4]))
  7514. // Length
  7515. writeVarByteInt(stream, length)
  7516. // reason code in header
  7517. stream.write(Buffer.from([reasonCode]))
  7518. // properies mqtt 5
  7519. if (propertiesData !== null) {
  7520. propertiesData.write()
  7521. }
  7522. return true
  7523. }
  7524. /**
  7525. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  7526. *
  7527. * @param <Buffer> buffer - destination
  7528. * @param <Number> pos - offset
  7529. * @param <Number> length - length (>0)
  7530. * @returns <Number> number of bytes written
  7531. *
  7532. * @api private
  7533. */
  7534. var varByteIntCache = {}
  7535. function writeVarByteInt (stream, num) {
  7536. var buffer = varByteIntCache[num]
  7537. if (!buffer) {
  7538. buffer = genBufVariableByteInt(num).data
  7539. if (num < 16384) varByteIntCache[num] = buffer
  7540. }
  7541. stream.write(buffer)
  7542. }
  7543. /**
  7544. * writeString - write a utf8 string to the buffer
  7545. *
  7546. * @param <Buffer> buffer - destination
  7547. * @param <Number> pos - offset
  7548. * @param <String> string - string to write
  7549. * @return <Number> number of bytes written
  7550. *
  7551. * @api private
  7552. */
  7553. function writeString (stream, string) {
  7554. var strlen = Buffer.byteLength(string)
  7555. writeNumber(stream, strlen)
  7556. stream.write(string, 'utf8')
  7557. }
  7558. /**
  7559. * writeStringPair - write a utf8 string pairs to the buffer
  7560. *
  7561. * @param <Buffer> buffer - destination
  7562. * @param <String> name - string name to write
  7563. * @param <String> value - string value to write
  7564. * @return <Number> number of bytes written
  7565. *
  7566. * @api private
  7567. */
  7568. function writeStringPair (stream, name, value) {
  7569. writeString(stream, name)
  7570. writeString(stream, value)
  7571. }
  7572. /**
  7573. * writeNumber - write a two byte number to the buffer
  7574. *
  7575. * @param <Buffer> buffer - destination
  7576. * @param <Number> pos - offset
  7577. * @param <String> number - number to write
  7578. * @return <Number> number of bytes written
  7579. *
  7580. * @api private
  7581. */
  7582. function writeNumberCached (stream, number) {
  7583. return stream.write(numCache[number])
  7584. }
  7585. function writeNumberGenerated (stream, number) {
  7586. return stream.write(generateNumber(number))
  7587. }
  7588. function write4ByteNumber (stream, number) {
  7589. return stream.write(generate4ByteBuffer(number))
  7590. }
  7591. /**
  7592. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  7593. *
  7594. * @param <Buffer> buffer - destination
  7595. * @param <Number> pos - offset
  7596. * @param <String> toWrite - String or Buffer
  7597. * @return <Number> number of bytes written
  7598. */
  7599. function writeStringOrBuffer (stream, toWrite) {
  7600. if (typeof toWrite === 'string') {
  7601. writeString(stream, toWrite)
  7602. } else if (toWrite) {
  7603. writeNumber(stream, toWrite.length)
  7604. stream.write(toWrite)
  7605. } else writeNumber(stream, 0)
  7606. }
  7607. function getProperties (stream, properties) {
  7608. /* connect properties */
  7609. if (typeof properties !== 'object' || properties.length != null) {
  7610. return {
  7611. length: 1,
  7612. write: function () {
  7613. writeProperties(stream, {}, 0)
  7614. }
  7615. }
  7616. }
  7617. var propertiesLength = 0
  7618. function getLengthProperty (name) {
  7619. var type = protocol.propertiesTypes[name]
  7620. var value = properties[name]
  7621. var length = 0
  7622. switch (type) {
  7623. case 'byte': {
  7624. if (typeof value !== 'boolean') {
  7625. stream.emit('error', new Error('Invalid ' + name))
  7626. return false
  7627. }
  7628. length += 1 + 1
  7629. break
  7630. }
  7631. case 'int8': {
  7632. if (typeof value !== 'number') {
  7633. stream.emit('error', new Error('Invalid ' + name))
  7634. return false
  7635. }
  7636. length += 1 + 1
  7637. break
  7638. }
  7639. case 'binary': {
  7640. if (value && value === null) {
  7641. stream.emit('error', new Error('Invalid ' + name))
  7642. return false
  7643. }
  7644. length += 1 + Buffer.byteLength(value) + 2
  7645. break
  7646. }
  7647. case 'int16': {
  7648. if (typeof value !== 'number') {
  7649. stream.emit('error', new Error('Invalid ' + name))
  7650. return false
  7651. }
  7652. length += 1 + 2
  7653. break
  7654. }
  7655. case 'int32': {
  7656. if (typeof value !== 'number') {
  7657. stream.emit('error', new Error('Invalid ' + name))
  7658. return false
  7659. }
  7660. length += 1 + 4
  7661. break
  7662. }
  7663. case 'var': {
  7664. if (typeof value !== 'number') {
  7665. stream.emit('error', new Error('Invalid ' + name))
  7666. return false
  7667. }
  7668. length += 1 + genBufVariableByteInt(value).length
  7669. break
  7670. }
  7671. case 'string': {
  7672. if (typeof value !== 'string') {
  7673. stream.emit('error', new Error('Invalid ' + name))
  7674. return false
  7675. }
  7676. length += 1 + 2 + Buffer.byteLength(value.toString())
  7677. break
  7678. }
  7679. case 'pair': {
  7680. if (typeof value !== 'object') {
  7681. stream.emit('error', new Error('Invalid ' + name))
  7682. return false
  7683. }
  7684. length += Object.getOwnPropertyNames(value).reduce(function (result, name) {
  7685. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  7686. return result
  7687. }, 0)
  7688. break
  7689. }
  7690. default: {
  7691. stream.emit('error', new Error('Invalid property ' + name))
  7692. return false
  7693. }
  7694. }
  7695. return length
  7696. }
  7697. if (properties) {
  7698. for (var propName in properties) {
  7699. var propLength = getLengthProperty(propName)
  7700. if (!propLength) return false
  7701. propertiesLength += propLength
  7702. }
  7703. }
  7704. var propertiesLengthLength = genBufVariableByteInt(propertiesLength).length
  7705. return {
  7706. length: propertiesLengthLength + propertiesLength,
  7707. write: function () {
  7708. writeProperties(stream, properties, propertiesLength)
  7709. }
  7710. }
  7711. }
  7712. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  7713. var mayEmptyProps = ['reasonString', 'userProperties']
  7714. var maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  7715. var propertiesData = getProperties(stream, properties)
  7716. if (maximumPacketSize) {
  7717. while (length + propertiesData.length > maximumPacketSize) {
  7718. var currentMayEmptyProp = mayEmptyProps.shift()
  7719. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  7720. delete properties[currentMayEmptyProp]
  7721. propertiesData = getProperties(stream, properties)
  7722. } else {
  7723. return false
  7724. }
  7725. }
  7726. }
  7727. return propertiesData
  7728. }
  7729. function writeProperties (stream, properties, propertiesLength) {
  7730. /* write properties to stream */
  7731. writeVarByteInt(stream, propertiesLength)
  7732. for (var propName in properties) {
  7733. if (properties.hasOwnProperty(propName) && properties[propName] !== null) {
  7734. var value = properties[propName]
  7735. var type = protocol.propertiesTypes[propName]
  7736. switch (type) {
  7737. case 'byte': {
  7738. stream.write(Buffer.from([protocol.properties[propName]]))
  7739. stream.write(Buffer.from([+value]))
  7740. break
  7741. }
  7742. case 'int8': {
  7743. stream.write(Buffer.from([protocol.properties[propName]]))
  7744. stream.write(Buffer.from([value]))
  7745. break
  7746. }
  7747. case 'binary': {
  7748. stream.write(Buffer.from([protocol.properties[propName]]))
  7749. writeStringOrBuffer(stream, value)
  7750. break
  7751. }
  7752. case 'int16': {
  7753. stream.write(Buffer.from([protocol.properties[propName]]))
  7754. writeNumber(stream, value)
  7755. break
  7756. }
  7757. case 'int32': {
  7758. stream.write(Buffer.from([protocol.properties[propName]]))
  7759. write4ByteNumber(stream, value)
  7760. break
  7761. }
  7762. case 'var': {
  7763. stream.write(Buffer.from([protocol.properties[propName]]))
  7764. writeVarByteInt(stream, value)
  7765. break
  7766. }
  7767. case 'string': {
  7768. stream.write(Buffer.from([protocol.properties[propName]]))
  7769. writeString(stream, value)
  7770. break
  7771. }
  7772. case 'pair': {
  7773. Object.getOwnPropertyNames(value).forEach(function (name) {
  7774. stream.write(Buffer.from([protocol.properties[propName]]))
  7775. writeStringPair(stream, name.toString(), value[name].toString())
  7776. })
  7777. break
  7778. }
  7779. default: {
  7780. stream.emit('error', new Error('Invalid property ' + propName))
  7781. return false
  7782. }
  7783. }
  7784. }
  7785. }
  7786. }
  7787. function byteLength (bufOrString) {
  7788. if (!bufOrString) return 0
  7789. else if (bufOrString instanceof Buffer) return bufOrString.length
  7790. else return Buffer.byteLength(bufOrString)
  7791. }
  7792. function isStringOrBuffer (field) {
  7793. return typeof field === 'string' || field instanceof Buffer
  7794. }
  7795. module.exports = generate
  7796. },{"./constants":82,"./numbers":86,"process-nextick-args":91,"safe-buffer":110}],90:[function(require,module,exports){
  7797. var wrappy = require('wrappy')
  7798. module.exports = wrappy(once)
  7799. module.exports.strict = wrappy(onceStrict)
  7800. once.proto = once(function () {
  7801. Object.defineProperty(Function.prototype, 'once', {
  7802. value: function () {
  7803. return once(this)
  7804. },
  7805. configurable: true
  7806. })
  7807. Object.defineProperty(Function.prototype, 'onceStrict', {
  7808. value: function () {
  7809. return onceStrict(this)
  7810. },
  7811. configurable: true
  7812. })
  7813. })
  7814. function once (fn) {
  7815. var f = function () {
  7816. if (f.called) return f.value
  7817. f.called = true
  7818. return f.value = fn.apply(this, arguments)
  7819. }
  7820. f.called = false
  7821. return f
  7822. }
  7823. function onceStrict (fn) {
  7824. var f = function () {
  7825. if (f.called)
  7826. throw new Error(f.onceError)
  7827. f.called = true
  7828. return f.value = fn.apply(this, arguments)
  7829. }
  7830. var name = fn.name || 'Function wrapped with `once`'
  7831. f.onceError = name + " shouldn't be called more than once"
  7832. f.called = false
  7833. return f
  7834. }
  7835. },{"wrappy":120}],91:[function(require,module,exports){
  7836. (function (process){
  7837. 'use strict';
  7838. if (!process.version ||
  7839. process.version.indexOf('v0.') === 0 ||
  7840. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  7841. module.exports = { nextTick: nextTick };
  7842. } else {
  7843. module.exports = process
  7844. }
  7845. function nextTick(fn, arg1, arg2, arg3) {
  7846. if (typeof fn !== 'function') {
  7847. throw new TypeError('"callback" argument must be a function');
  7848. }
  7849. var len = arguments.length;
  7850. var args, i;
  7851. switch (len) {
  7852. case 0:
  7853. case 1:
  7854. return process.nextTick(fn);
  7855. case 2:
  7856. return process.nextTick(function afterTickOne() {
  7857. fn.call(null, arg1);
  7858. });
  7859. case 3:
  7860. return process.nextTick(function afterTickTwo() {
  7861. fn.call(null, arg1, arg2);
  7862. });
  7863. case 4:
  7864. return process.nextTick(function afterTickThree() {
  7865. fn.call(null, arg1, arg2, arg3);
  7866. });
  7867. default:
  7868. args = new Array(len - 1);
  7869. i = 0;
  7870. while (i < args.length) {
  7871. args[i++] = arguments[i];
  7872. }
  7873. return process.nextTick(function afterTick() {
  7874. fn.apply(null, args);
  7875. });
  7876. }
  7877. }
  7878. }).call(this,require('_process'))
  7879. },{"_process":92}],92:[function(require,module,exports){
  7880. // shim for using process in browser
  7881. var process = module.exports = {};
  7882. // cached from whatever global is present so that test runners that stub it
  7883. // don't break things. But we need to wrap it in a try catch in case it is
  7884. // wrapped in strict mode code which doesn't define any globals. It's inside a
  7885. // function because try/catches deoptimize in certain engines.
  7886. var cachedSetTimeout;
  7887. var cachedClearTimeout;
  7888. function defaultSetTimout() {
  7889. throw new Error('setTimeout has not been defined');
  7890. }
  7891. function defaultClearTimeout () {
  7892. throw new Error('clearTimeout has not been defined');
  7893. }
  7894. (function () {
  7895. try {
  7896. if (typeof setTimeout === 'function') {
  7897. cachedSetTimeout = setTimeout;
  7898. } else {
  7899. cachedSetTimeout = defaultSetTimout;
  7900. }
  7901. } catch (e) {
  7902. cachedSetTimeout = defaultSetTimout;
  7903. }
  7904. try {
  7905. if (typeof clearTimeout === 'function') {
  7906. cachedClearTimeout = clearTimeout;
  7907. } else {
  7908. cachedClearTimeout = defaultClearTimeout;
  7909. }
  7910. } catch (e) {
  7911. cachedClearTimeout = defaultClearTimeout;
  7912. }
  7913. } ())
  7914. function runTimeout(fun) {
  7915. if (cachedSetTimeout === setTimeout) {
  7916. //normal enviroments in sane situations
  7917. return setTimeout(fun, 0);
  7918. }
  7919. // if setTimeout wasn't available but was latter defined
  7920. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  7921. cachedSetTimeout = setTimeout;
  7922. return setTimeout(fun, 0);
  7923. }
  7924. try {
  7925. // when when somebody has screwed with setTimeout but no I.E. maddness
  7926. return cachedSetTimeout(fun, 0);
  7927. } catch(e){
  7928. try {
  7929. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7930. return cachedSetTimeout.call(null, fun, 0);
  7931. } catch(e){
  7932. // 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
  7933. return cachedSetTimeout.call(this, fun, 0);
  7934. }
  7935. }
  7936. }
  7937. function runClearTimeout(marker) {
  7938. if (cachedClearTimeout === clearTimeout) {
  7939. //normal enviroments in sane situations
  7940. return clearTimeout(marker);
  7941. }
  7942. // if clearTimeout wasn't available but was latter defined
  7943. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  7944. cachedClearTimeout = clearTimeout;
  7945. return clearTimeout(marker);
  7946. }
  7947. try {
  7948. // when when somebody has screwed with setTimeout but no I.E. maddness
  7949. return cachedClearTimeout(marker);
  7950. } catch (e){
  7951. try {
  7952. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7953. return cachedClearTimeout.call(null, marker);
  7954. } catch (e){
  7955. // 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.
  7956. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  7957. return cachedClearTimeout.call(this, marker);
  7958. }
  7959. }
  7960. }
  7961. var queue = [];
  7962. var draining = false;
  7963. var currentQueue;
  7964. var queueIndex = -1;
  7965. function cleanUpNextTick() {
  7966. if (!draining || !currentQueue) {
  7967. return;
  7968. }
  7969. draining = false;
  7970. if (currentQueue.length) {
  7971. queue = currentQueue.concat(queue);
  7972. } else {
  7973. queueIndex = -1;
  7974. }
  7975. if (queue.length) {
  7976. drainQueue();
  7977. }
  7978. }
  7979. function drainQueue() {
  7980. if (draining) {
  7981. return;
  7982. }
  7983. var timeout = runTimeout(cleanUpNextTick);
  7984. draining = true;
  7985. var len = queue.length;
  7986. while(len) {
  7987. currentQueue = queue;
  7988. queue = [];
  7989. while (++queueIndex < len) {
  7990. if (currentQueue) {
  7991. currentQueue[queueIndex].run();
  7992. }
  7993. }
  7994. queueIndex = -1;
  7995. len = queue.length;
  7996. }
  7997. currentQueue = null;
  7998. draining = false;
  7999. runClearTimeout(timeout);
  8000. }
  8001. process.nextTick = function (fun) {
  8002. var args = new Array(arguments.length - 1);
  8003. if (arguments.length > 1) {
  8004. for (var i = 1; i < arguments.length; i++) {
  8005. args[i - 1] = arguments[i];
  8006. }
  8007. }
  8008. queue.push(new Item(fun, args));
  8009. if (queue.length === 1 && !draining) {
  8010. runTimeout(drainQueue);
  8011. }
  8012. };
  8013. // v8 likes predictible objects
  8014. function Item(fun, array) {
  8015. this.fun = fun;
  8016. this.array = array;
  8017. }
  8018. Item.prototype.run = function () {
  8019. this.fun.apply(null, this.array);
  8020. };
  8021. process.title = 'browser';
  8022. process.browser = true;
  8023. process.env = {};
  8024. process.argv = [];
  8025. process.version = ''; // empty string to avoid regexp issues
  8026. process.versions = {};
  8027. function noop() {}
  8028. process.on = noop;
  8029. process.addListener = noop;
  8030. process.once = noop;
  8031. process.off = noop;
  8032. process.removeListener = noop;
  8033. process.removeAllListeners = noop;
  8034. process.emit = noop;
  8035. process.prependListener = noop;
  8036. process.prependOnceListener = noop;
  8037. process.listeners = function (name) { return [] }
  8038. process.binding = function (name) {
  8039. throw new Error('process.binding is not supported');
  8040. };
  8041. process.cwd = function () { return '/' };
  8042. process.chdir = function (dir) {
  8043. throw new Error('process.chdir is not supported');
  8044. };
  8045. process.umask = function() { return 0; };
  8046. },{}],93:[function(require,module,exports){
  8047. (function (global){
  8048. /*! https://mths.be/punycode v1.4.1 by @mathias */
  8049. ;(function(root) {
  8050. /** Detect free variables */
  8051. var freeExports = typeof exports == 'object' && exports &&
  8052. !exports.nodeType && exports;
  8053. var freeModule = typeof module == 'object' && module &&
  8054. !module.nodeType && module;
  8055. var freeGlobal = typeof global == 'object' && global;
  8056. if (
  8057. freeGlobal.global === freeGlobal ||
  8058. freeGlobal.window === freeGlobal ||
  8059. freeGlobal.self === freeGlobal
  8060. ) {
  8061. root = freeGlobal;
  8062. }
  8063. /**
  8064. * The `punycode` object.
  8065. * @name punycode
  8066. * @type Object
  8067. */
  8068. var punycode,
  8069. /** Highest positive signed 32-bit float value */
  8070. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  8071. /** Bootstring parameters */
  8072. base = 36,
  8073. tMin = 1,
  8074. tMax = 26,
  8075. skew = 38,
  8076. damp = 700,
  8077. initialBias = 72,
  8078. initialN = 128, // 0x80
  8079. delimiter = '-', // '\x2D'
  8080. /** Regular expressions */
  8081. regexPunycode = /^xn--/,
  8082. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  8083. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  8084. /** Error messages */
  8085. errors = {
  8086. 'overflow': 'Overflow: input needs wider integers to process',
  8087. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  8088. 'invalid-input': 'Invalid input'
  8089. },
  8090. /** Convenience shortcuts */
  8091. baseMinusTMin = base - tMin,
  8092. floor = Math.floor,
  8093. stringFromCharCode = String.fromCharCode,
  8094. /** Temporary variable */
  8095. key;
  8096. /*--------------------------------------------------------------------------*/
  8097. /**
  8098. * A generic error utility function.
  8099. * @private
  8100. * @param {String} type The error type.
  8101. * @returns {Error} Throws a `RangeError` with the applicable error message.
  8102. */
  8103. function error(type) {
  8104. throw new RangeError(errors[type]);
  8105. }
  8106. /**
  8107. * A generic `Array#map` utility function.
  8108. * @private
  8109. * @param {Array} array The array to iterate over.
  8110. * @param {Function} callback The function that gets called for every array
  8111. * item.
  8112. * @returns {Array} A new array of values returned by the callback function.
  8113. */
  8114. function map(array, fn) {
  8115. var length = array.length;
  8116. var result = [];
  8117. while (length--) {
  8118. result[length] = fn(array[length]);
  8119. }
  8120. return result;
  8121. }
  8122. /**
  8123. * A simple `Array#map`-like wrapper to work with domain name strings or email
  8124. * addresses.
  8125. * @private
  8126. * @param {String} domain The domain name or email address.
  8127. * @param {Function} callback The function that gets called for every
  8128. * character.
  8129. * @returns {Array} A new string of characters returned by the callback
  8130. * function.
  8131. */
  8132. function mapDomain(string, fn) {
  8133. var parts = string.split('@');
  8134. var result = '';
  8135. if (parts.length > 1) {
  8136. // In email addresses, only the domain name should be punycoded. Leave
  8137. // the local part (i.e. everything up to `@`) intact.
  8138. result = parts[0] + '@';
  8139. string = parts[1];
  8140. }
  8141. // Avoid `split(regex)` for IE8 compatibility. See #17.
  8142. string = string.replace(regexSeparators, '\x2E');
  8143. var labels = string.split('.');
  8144. var encoded = map(labels, fn).join('.');
  8145. return result + encoded;
  8146. }
  8147. /**
  8148. * Creates an array containing the numeric code points of each Unicode
  8149. * character in the string. While JavaScript uses UCS-2 internally,
  8150. * this function will convert a pair of surrogate halves (each of which
  8151. * UCS-2 exposes as separate characters) into a single code point,
  8152. * matching UTF-16.
  8153. * @see `punycode.ucs2.encode`
  8154. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8155. * @memberOf punycode.ucs2
  8156. * @name decode
  8157. * @param {String} string The Unicode input string (UCS-2).
  8158. * @returns {Array} The new array of code points.
  8159. */
  8160. function ucs2decode(string) {
  8161. var output = [],
  8162. counter = 0,
  8163. length = string.length,
  8164. value,
  8165. extra;
  8166. while (counter < length) {
  8167. value = string.charCodeAt(counter++);
  8168. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  8169. // high surrogate, and there is a next character
  8170. extra = string.charCodeAt(counter++);
  8171. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  8172. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  8173. } else {
  8174. // unmatched surrogate; only append this code unit, in case the next
  8175. // code unit is the high surrogate of a surrogate pair
  8176. output.push(value);
  8177. counter--;
  8178. }
  8179. } else {
  8180. output.push(value);
  8181. }
  8182. }
  8183. return output;
  8184. }
  8185. /**
  8186. * Creates a string based on an array of numeric code points.
  8187. * @see `punycode.ucs2.decode`
  8188. * @memberOf punycode.ucs2
  8189. * @name encode
  8190. * @param {Array} codePoints The array of numeric code points.
  8191. * @returns {String} The new Unicode string (UCS-2).
  8192. */
  8193. function ucs2encode(array) {
  8194. return map(array, function(value) {
  8195. var output = '';
  8196. if (value > 0xFFFF) {
  8197. value -= 0x10000;
  8198. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  8199. value = 0xDC00 | value & 0x3FF;
  8200. }
  8201. output += stringFromCharCode(value);
  8202. return output;
  8203. }).join('');
  8204. }
  8205. /**
  8206. * Converts a basic code point into a digit/integer.
  8207. * @see `digitToBasic()`
  8208. * @private
  8209. * @param {Number} codePoint The basic numeric code point value.
  8210. * @returns {Number} The numeric value of a basic code point (for use in
  8211. * representing integers) in the range `0` to `base - 1`, or `base` if
  8212. * the code point does not represent a value.
  8213. */
  8214. function basicToDigit(codePoint) {
  8215. if (codePoint - 48 < 10) {
  8216. return codePoint - 22;
  8217. }
  8218. if (codePoint - 65 < 26) {
  8219. return codePoint - 65;
  8220. }
  8221. if (codePoint - 97 < 26) {
  8222. return codePoint - 97;
  8223. }
  8224. return base;
  8225. }
  8226. /**
  8227. * Converts a digit/integer into a basic code point.
  8228. * @see `basicToDigit()`
  8229. * @private
  8230. * @param {Number} digit The numeric value of a basic code point.
  8231. * @returns {Number} The basic code point whose value (when used for
  8232. * representing integers) is `digit`, which needs to be in the range
  8233. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  8234. * used; else, the lowercase form is used. The behavior is undefined
  8235. * if `flag` is non-zero and `digit` has no uppercase form.
  8236. */
  8237. function digitToBasic(digit, flag) {
  8238. // 0..25 map to ASCII a..z or A..Z
  8239. // 26..35 map to ASCII 0..9
  8240. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  8241. }
  8242. /**
  8243. * Bias adaptation function as per section 3.4 of RFC 3492.
  8244. * https://tools.ietf.org/html/rfc3492#section-3.4
  8245. * @private
  8246. */
  8247. function adapt(delta, numPoints, firstTime) {
  8248. var k = 0;
  8249. delta = firstTime ? floor(delta / damp) : delta >> 1;
  8250. delta += floor(delta / numPoints);
  8251. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  8252. delta = floor(delta / baseMinusTMin);
  8253. }
  8254. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  8255. }
  8256. /**
  8257. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  8258. * symbols.
  8259. * @memberOf punycode
  8260. * @param {String} input The Punycode string of ASCII-only symbols.
  8261. * @returns {String} The resulting string of Unicode symbols.
  8262. */
  8263. function decode(input) {
  8264. // Don't use UCS-2
  8265. var output = [],
  8266. inputLength = input.length,
  8267. out,
  8268. i = 0,
  8269. n = initialN,
  8270. bias = initialBias,
  8271. basic,
  8272. j,
  8273. index,
  8274. oldi,
  8275. w,
  8276. k,
  8277. digit,
  8278. t,
  8279. /** Cached calculation results */
  8280. baseMinusT;
  8281. // Handle the basic code points: let `basic` be the number of input code
  8282. // points before the last delimiter, or `0` if there is none, then copy
  8283. // the first basic code points to the output.
  8284. basic = input.lastIndexOf(delimiter);
  8285. if (basic < 0) {
  8286. basic = 0;
  8287. }
  8288. for (j = 0; j < basic; ++j) {
  8289. // if it's not a basic code point
  8290. if (input.charCodeAt(j) >= 0x80) {
  8291. error('not-basic');
  8292. }
  8293. output.push(input.charCodeAt(j));
  8294. }
  8295. // Main decoding loop: start just after the last delimiter if any basic code
  8296. // points were copied; start at the beginning otherwise.
  8297. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  8298. // `index` is the index of the next character to be consumed.
  8299. // Decode a generalized variable-length integer into `delta`,
  8300. // which gets added to `i`. The overflow checking is easier
  8301. // if we increase `i` as we go, then subtract off its starting
  8302. // value at the end to obtain `delta`.
  8303. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  8304. if (index >= inputLength) {
  8305. error('invalid-input');
  8306. }
  8307. digit = basicToDigit(input.charCodeAt(index++));
  8308. if (digit >= base || digit > floor((maxInt - i) / w)) {
  8309. error('overflow');
  8310. }
  8311. i += digit * w;
  8312. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  8313. if (digit < t) {
  8314. break;
  8315. }
  8316. baseMinusT = base - t;
  8317. if (w > floor(maxInt / baseMinusT)) {
  8318. error('overflow');
  8319. }
  8320. w *= baseMinusT;
  8321. }
  8322. out = output.length + 1;
  8323. bias = adapt(i - oldi, out, oldi == 0);
  8324. // `i` was supposed to wrap around from `out` to `0`,
  8325. // incrementing `n` each time, so we'll fix that now:
  8326. if (floor(i / out) > maxInt - n) {
  8327. error('overflow');
  8328. }
  8329. n += floor(i / out);
  8330. i %= out;
  8331. // Insert `n` at position `i` of the output
  8332. output.splice(i++, 0, n);
  8333. }
  8334. return ucs2encode(output);
  8335. }
  8336. /**
  8337. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  8338. * Punycode string of ASCII-only symbols.
  8339. * @memberOf punycode
  8340. * @param {String} input The string of Unicode symbols.
  8341. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  8342. */
  8343. function encode(input) {
  8344. var n,
  8345. delta,
  8346. handledCPCount,
  8347. basicLength,
  8348. bias,
  8349. j,
  8350. m,
  8351. q,
  8352. k,
  8353. t,
  8354. currentValue,
  8355. output = [],
  8356. /** `inputLength` will hold the number of code points in `input`. */
  8357. inputLength,
  8358. /** Cached calculation results */
  8359. handledCPCountPlusOne,
  8360. baseMinusT,
  8361. qMinusT;
  8362. // Convert the input in UCS-2 to Unicode
  8363. input = ucs2decode(input);
  8364. // Cache the length
  8365. inputLength = input.length;
  8366. // Initialize the state
  8367. n = initialN;
  8368. delta = 0;
  8369. bias = initialBias;
  8370. // Handle the basic code points
  8371. for (j = 0; j < inputLength; ++j) {
  8372. currentValue = input[j];
  8373. if (currentValue < 0x80) {
  8374. output.push(stringFromCharCode(currentValue));
  8375. }
  8376. }
  8377. handledCPCount = basicLength = output.length;
  8378. // `handledCPCount` is the number of code points that have been handled;
  8379. // `basicLength` is the number of basic code points.
  8380. // Finish the basic string - if it is not empty - with a delimiter
  8381. if (basicLength) {
  8382. output.push(delimiter);
  8383. }
  8384. // Main encoding loop:
  8385. while (handledCPCount < inputLength) {
  8386. // All non-basic code points < n have been handled already. Find the next
  8387. // larger one:
  8388. for (m = maxInt, j = 0; j < inputLength; ++j) {
  8389. currentValue = input[j];
  8390. if (currentValue >= n && currentValue < m) {
  8391. m = currentValue;
  8392. }
  8393. }
  8394. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  8395. // but guard against overflow
  8396. handledCPCountPlusOne = handledCPCount + 1;
  8397. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  8398. error('overflow');
  8399. }
  8400. delta += (m - n) * handledCPCountPlusOne;
  8401. n = m;
  8402. for (j = 0; j < inputLength; ++j) {
  8403. currentValue = input[j];
  8404. if (currentValue < n && ++delta > maxInt) {
  8405. error('overflow');
  8406. }
  8407. if (currentValue == n) {
  8408. // Represent delta as a generalized variable-length integer
  8409. for (q = delta, k = base; /* no condition */; k += base) {
  8410. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  8411. if (q < t) {
  8412. break;
  8413. }
  8414. qMinusT = q - t;
  8415. baseMinusT = base - t;
  8416. output.push(
  8417. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  8418. );
  8419. q = floor(qMinusT / baseMinusT);
  8420. }
  8421. output.push(stringFromCharCode(digitToBasic(q, 0)));
  8422. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  8423. delta = 0;
  8424. ++handledCPCount;
  8425. }
  8426. }
  8427. ++delta;
  8428. ++n;
  8429. }
  8430. return output.join('');
  8431. }
  8432. /**
  8433. * Converts a Punycode string representing a domain name or an email address
  8434. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  8435. * it doesn't matter if you call it on a string that has already been
  8436. * converted to Unicode.
  8437. * @memberOf punycode
  8438. * @param {String} input The Punycoded domain name or email address to
  8439. * convert to Unicode.
  8440. * @returns {String} The Unicode representation of the given Punycode
  8441. * string.
  8442. */
  8443. function toUnicode(input) {
  8444. return mapDomain(input, function(string) {
  8445. return regexPunycode.test(string)
  8446. ? decode(string.slice(4).toLowerCase())
  8447. : string;
  8448. });
  8449. }
  8450. /**
  8451. * Converts a Unicode string representing a domain name or an email address to
  8452. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  8453. * i.e. it doesn't matter if you call it with a domain that's already in
  8454. * ASCII.
  8455. * @memberOf punycode
  8456. * @param {String} input The domain name or email address to convert, as a
  8457. * Unicode string.
  8458. * @returns {String} The Punycode representation of the given domain name or
  8459. * email address.
  8460. */
  8461. function toASCII(input) {
  8462. return mapDomain(input, function(string) {
  8463. return regexNonASCII.test(string)
  8464. ? 'xn--' + encode(string)
  8465. : string;
  8466. });
  8467. }
  8468. /*--------------------------------------------------------------------------*/
  8469. /** Define the public API */
  8470. punycode = {
  8471. /**
  8472. * A string representing the current Punycode.js version number.
  8473. * @memberOf punycode
  8474. * @type String
  8475. */
  8476. 'version': '1.4.1',
  8477. /**
  8478. * An object of methods to convert from JavaScript's internal character
  8479. * representation (UCS-2) to Unicode code points, and back.
  8480. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8481. * @memberOf punycode
  8482. * @type Object
  8483. */
  8484. 'ucs2': {
  8485. 'decode': ucs2decode,
  8486. 'encode': ucs2encode
  8487. },
  8488. 'decode': decode,
  8489. 'encode': encode,
  8490. 'toASCII': toASCII,
  8491. 'toUnicode': toUnicode
  8492. };
  8493. /** Expose `punycode` */
  8494. // Some AMD build optimizers, like r.js, check for specific condition patterns
  8495. // like the following:
  8496. if (
  8497. typeof define == 'function' &&
  8498. typeof define.amd == 'object' &&
  8499. define.amd
  8500. ) {
  8501. define('punycode', function() {
  8502. return punycode;
  8503. });
  8504. } else if (freeExports && freeModule) {
  8505. if (module.exports == freeExports) {
  8506. // in Node.js, io.js, or RingoJS v0.8.0+
  8507. freeModule.exports = punycode;
  8508. } else {
  8509. // in Narwhal or RingoJS v0.7.0-
  8510. for (key in punycode) {
  8511. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  8512. }
  8513. }
  8514. } else {
  8515. // in Rhino or a web browser
  8516. root.punycode = punycode;
  8517. }
  8518. }(this));
  8519. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8520. },{}],94:[function(require,module,exports){
  8521. // Copyright Joyent, Inc. and other Node contributors.
  8522. //
  8523. // Permission is hereby granted, free of charge, to any person obtaining a
  8524. // copy of this software and associated documentation files (the
  8525. // "Software"), to deal in the Software without restriction, including
  8526. // without limitation the rights to use, copy, modify, merge, publish,
  8527. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8528. // persons to whom the Software is furnished to do so, subject to the
  8529. // following conditions:
  8530. //
  8531. // The above copyright notice and this permission notice shall be included
  8532. // in all copies or substantial portions of the Software.
  8533. //
  8534. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8535. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8536. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8537. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8538. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8539. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8540. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8541. 'use strict';
  8542. // If obj.hasOwnProperty has been overridden, then calling
  8543. // obj.hasOwnProperty(prop) will break.
  8544. // See: https://github.com/joyent/node/issues/1707
  8545. function hasOwnProperty(obj, prop) {
  8546. return Object.prototype.hasOwnProperty.call(obj, prop);
  8547. }
  8548. module.exports = function(qs, sep, eq, options) {
  8549. sep = sep || '&';
  8550. eq = eq || '=';
  8551. var obj = {};
  8552. if (typeof qs !== 'string' || qs.length === 0) {
  8553. return obj;
  8554. }
  8555. var regexp = /\+/g;
  8556. qs = qs.split(sep);
  8557. var maxKeys = 1000;
  8558. if (options && typeof options.maxKeys === 'number') {
  8559. maxKeys = options.maxKeys;
  8560. }
  8561. var len = qs.length;
  8562. // maxKeys <= 0 means that we should not limit keys count
  8563. if (maxKeys > 0 && len > maxKeys) {
  8564. len = maxKeys;
  8565. }
  8566. for (var i = 0; i < len; ++i) {
  8567. var x = qs[i].replace(regexp, '%20'),
  8568. idx = x.indexOf(eq),
  8569. kstr, vstr, k, v;
  8570. if (idx >= 0) {
  8571. kstr = x.substr(0, idx);
  8572. vstr = x.substr(idx + 1);
  8573. } else {
  8574. kstr = x;
  8575. vstr = '';
  8576. }
  8577. k = decodeURIComponent(kstr);
  8578. v = decodeURIComponent(vstr);
  8579. if (!hasOwnProperty(obj, k)) {
  8580. obj[k] = v;
  8581. } else if (isArray(obj[k])) {
  8582. obj[k].push(v);
  8583. } else {
  8584. obj[k] = [obj[k], v];
  8585. }
  8586. }
  8587. return obj;
  8588. };
  8589. var isArray = Array.isArray || function (xs) {
  8590. return Object.prototype.toString.call(xs) === '[object Array]';
  8591. };
  8592. },{}],95:[function(require,module,exports){
  8593. // Copyright Joyent, Inc. and other Node contributors.
  8594. //
  8595. // Permission is hereby granted, free of charge, to any person obtaining a
  8596. // copy of this software and associated documentation files (the
  8597. // "Software"), to deal in the Software without restriction, including
  8598. // without limitation the rights to use, copy, modify, merge, publish,
  8599. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8600. // persons to whom the Software is furnished to do so, subject to the
  8601. // following conditions:
  8602. //
  8603. // The above copyright notice and this permission notice shall be included
  8604. // in all copies or substantial portions of the Software.
  8605. //
  8606. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8607. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8608. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8609. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8610. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8611. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8612. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8613. 'use strict';
  8614. var stringifyPrimitive = function(v) {
  8615. switch (typeof v) {
  8616. case 'string':
  8617. return v;
  8618. case 'boolean':
  8619. return v ? 'true' : 'false';
  8620. case 'number':
  8621. return isFinite(v) ? v : '';
  8622. default:
  8623. return '';
  8624. }
  8625. };
  8626. module.exports = function(obj, sep, eq, name) {
  8627. sep = sep || '&';
  8628. eq = eq || '=';
  8629. if (obj === null) {
  8630. obj = undefined;
  8631. }
  8632. if (typeof obj === 'object') {
  8633. return map(objectKeys(obj), function(k) {
  8634. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  8635. if (isArray(obj[k])) {
  8636. return map(obj[k], function(v) {
  8637. return ks + encodeURIComponent(stringifyPrimitive(v));
  8638. }).join(sep);
  8639. } else {
  8640. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  8641. }
  8642. }).join(sep);
  8643. }
  8644. if (!name) return '';
  8645. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  8646. encodeURIComponent(stringifyPrimitive(obj));
  8647. };
  8648. var isArray = Array.isArray || function (xs) {
  8649. return Object.prototype.toString.call(xs) === '[object Array]';
  8650. };
  8651. function map (xs, f) {
  8652. if (xs.map) return xs.map(f);
  8653. var res = [];
  8654. for (var i = 0; i < xs.length; i++) {
  8655. res.push(f(xs[i], i));
  8656. }
  8657. return res;
  8658. }
  8659. var objectKeys = Object.keys || function (obj) {
  8660. var res = [];
  8661. for (var key in obj) {
  8662. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  8663. }
  8664. return res;
  8665. };
  8666. },{}],96:[function(require,module,exports){
  8667. 'use strict';
  8668. exports.decode = exports.parse = require('./decode');
  8669. exports.encode = exports.stringify = require('./encode');
  8670. },{"./decode":94,"./encode":95}],97:[function(require,module,exports){
  8671. module.exports = require('./lib/_stream_duplex.js');
  8672. },{"./lib/_stream_duplex.js":98}],98:[function(require,module,exports){
  8673. // Copyright Joyent, Inc. and other Node contributors.
  8674. //
  8675. // Permission is hereby granted, free of charge, to any person obtaining a
  8676. // copy of this software and associated documentation files (the
  8677. // "Software"), to deal in the Software without restriction, including
  8678. // without limitation the rights to use, copy, modify, merge, publish,
  8679. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8680. // persons to whom the Software is furnished to do so, subject to the
  8681. // following conditions:
  8682. //
  8683. // The above copyright notice and this permission notice shall be included
  8684. // in all copies or substantial portions of the Software.
  8685. //
  8686. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8687. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8688. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8689. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8690. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8691. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8692. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8693. // a duplex stream is just a stream that is both readable and writable.
  8694. // Since JS doesn't have multiple prototypal inheritance, this class
  8695. // prototypally inherits from Readable, and then parasitically from
  8696. // Writable.
  8697. 'use strict';
  8698. /*<replacement>*/
  8699. var pna = require('process-nextick-args');
  8700. /*</replacement>*/
  8701. /*<replacement>*/
  8702. var objectKeys = Object.keys || function (obj) {
  8703. var keys = [];
  8704. for (var key in obj) {
  8705. keys.push(key);
  8706. }return keys;
  8707. };
  8708. /*</replacement>*/
  8709. module.exports = Duplex;
  8710. /*<replacement>*/
  8711. var util = require('core-util-is');
  8712. util.inherits = require('inherits');
  8713. /*</replacement>*/
  8714. var Readable = require('./_stream_readable');
  8715. var Writable = require('./_stream_writable');
  8716. util.inherits(Duplex, Readable);
  8717. {
  8718. // avoid scope creep, the keys array can then be collected
  8719. var keys = objectKeys(Writable.prototype);
  8720. for (var v = 0; v < keys.length; v++) {
  8721. var method = keys[v];
  8722. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  8723. }
  8724. }
  8725. function Duplex(options) {
  8726. if (!(this instanceof Duplex)) return new Duplex(options);
  8727. Readable.call(this, options);
  8728. Writable.call(this, options);
  8729. if (options && options.readable === false) this.readable = false;
  8730. if (options && options.writable === false) this.writable = false;
  8731. this.allowHalfOpen = true;
  8732. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  8733. this.once('end', onend);
  8734. }
  8735. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  8736. // making it explicit this property is not enumerable
  8737. // because otherwise some prototype manipulation in
  8738. // userland will fail
  8739. enumerable: false,
  8740. get: function () {
  8741. return this._writableState.highWaterMark;
  8742. }
  8743. });
  8744. // the no-half-open enforcer
  8745. function onend() {
  8746. // if we allow half-open state, or if the writable side ended,
  8747. // then we're ok.
  8748. if (this.allowHalfOpen || this._writableState.ended) return;
  8749. // no more data can be written.
  8750. // But allow more writes to happen in this tick.
  8751. pna.nextTick(onEndNT, this);
  8752. }
  8753. function onEndNT(self) {
  8754. self.end();
  8755. }
  8756. Object.defineProperty(Duplex.prototype, 'destroyed', {
  8757. get: function () {
  8758. if (this._readableState === undefined || this._writableState === undefined) {
  8759. return false;
  8760. }
  8761. return this._readableState.destroyed && this._writableState.destroyed;
  8762. },
  8763. set: function (value) {
  8764. // we ignore the value if the stream
  8765. // has not been initialized yet
  8766. if (this._readableState === undefined || this._writableState === undefined) {
  8767. return;
  8768. }
  8769. // backward compatibility, the user is explicitly
  8770. // managing destroyed
  8771. this._readableState.destroyed = value;
  8772. this._writableState.destroyed = value;
  8773. }
  8774. });
  8775. Duplex.prototype._destroy = function (err, cb) {
  8776. this.push(null);
  8777. this.end();
  8778. pna.nextTick(cb, err);
  8779. };
  8780. },{"./_stream_readable":100,"./_stream_writable":102,"core-util-is":14,"inherits":80,"process-nextick-args":91}],99:[function(require,module,exports){
  8781. // Copyright Joyent, Inc. and other Node contributors.
  8782. //
  8783. // Permission is hereby granted, free of charge, to any person obtaining a
  8784. // copy of this software and associated documentation files (the
  8785. // "Software"), to deal in the Software without restriction, including
  8786. // without limitation the rights to use, copy, modify, merge, publish,
  8787. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8788. // persons to whom the Software is furnished to do so, subject to the
  8789. // following conditions:
  8790. //
  8791. // The above copyright notice and this permission notice shall be included
  8792. // in all copies or substantial portions of the Software.
  8793. //
  8794. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8795. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8796. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8797. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8798. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8799. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8800. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8801. // a passthrough stream.
  8802. // basically just the most minimal sort of Transform stream.
  8803. // Every written chunk gets output as-is.
  8804. 'use strict';
  8805. module.exports = PassThrough;
  8806. var Transform = require('./_stream_transform');
  8807. /*<replacement>*/
  8808. var util = require('core-util-is');
  8809. util.inherits = require('inherits');
  8810. /*</replacement>*/
  8811. util.inherits(PassThrough, Transform);
  8812. function PassThrough(options) {
  8813. if (!(this instanceof PassThrough)) return new PassThrough(options);
  8814. Transform.call(this, options);
  8815. }
  8816. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  8817. cb(null, chunk);
  8818. };
  8819. },{"./_stream_transform":101,"core-util-is":14,"inherits":80}],100:[function(require,module,exports){
  8820. (function (process,global){
  8821. // Copyright Joyent, Inc. and other Node contributors.
  8822. //
  8823. // Permission is hereby granted, free of charge, to any person obtaining a
  8824. // copy of this software and associated documentation files (the
  8825. // "Software"), to deal in the Software without restriction, including
  8826. // without limitation the rights to use, copy, modify, merge, publish,
  8827. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8828. // persons to whom the Software is furnished to do so, subject to the
  8829. // following conditions:
  8830. //
  8831. // The above copyright notice and this permission notice shall be included
  8832. // in all copies or substantial portions of the Software.
  8833. //
  8834. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8835. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8836. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8837. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8838. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8839. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8840. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8841. 'use strict';
  8842. /*<replacement>*/
  8843. var pna = require('process-nextick-args');
  8844. /*</replacement>*/
  8845. module.exports = Readable;
  8846. /*<replacement>*/
  8847. var isArray = require('isarray');
  8848. /*</replacement>*/
  8849. /*<replacement>*/
  8850. var Duplex;
  8851. /*</replacement>*/
  8852. Readable.ReadableState = ReadableState;
  8853. /*<replacement>*/
  8854. var EE = require('events').EventEmitter;
  8855. var EElistenerCount = function (emitter, type) {
  8856. return emitter.listeners(type).length;
  8857. };
  8858. /*</replacement>*/
  8859. /*<replacement>*/
  8860. var Stream = require('./internal/streams/stream');
  8861. /*</replacement>*/
  8862. /*<replacement>*/
  8863. var Buffer = require('safe-buffer').Buffer;
  8864. var OurUint8Array = global.Uint8Array || function () {};
  8865. function _uint8ArrayToBuffer(chunk) {
  8866. return Buffer.from(chunk);
  8867. }
  8868. function _isUint8Array(obj) {
  8869. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  8870. }
  8871. /*</replacement>*/
  8872. /*<replacement>*/
  8873. var util = require('core-util-is');
  8874. util.inherits = require('inherits');
  8875. /*</replacement>*/
  8876. /*<replacement>*/
  8877. var debugUtil = require('util');
  8878. var debug = void 0;
  8879. if (debugUtil && debugUtil.debuglog) {
  8880. debug = debugUtil.debuglog('stream');
  8881. } else {
  8882. debug = function () {};
  8883. }
  8884. /*</replacement>*/
  8885. var BufferList = require('./internal/streams/BufferList');
  8886. var destroyImpl = require('./internal/streams/destroy');
  8887. var StringDecoder;
  8888. util.inherits(Readable, Stream);
  8889. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  8890. function prependListener(emitter, event, fn) {
  8891. // Sadly this is not cacheable as some libraries bundle their own
  8892. // event emitter implementation with them.
  8893. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  8894. // This is a hack to make sure that our error handler is attached before any
  8895. // userland ones. NEVER DO THIS. This is here only because this code needs
  8896. // to continue to work with older versions of Node.js that do not include
  8897. // the prependListener() method. The goal is to eventually remove this hack.
  8898. 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]];
  8899. }
  8900. function ReadableState(options, stream) {
  8901. Duplex = Duplex || require('./_stream_duplex');
  8902. options = options || {};
  8903. // Duplex streams are both readable and writable, but share
  8904. // the same options object.
  8905. // However, some cases require setting options to different
  8906. // values for the readable and the writable sides of the duplex stream.
  8907. // These options can be provided separately as readableXXX and writableXXX.
  8908. var isDuplex = stream instanceof Duplex;
  8909. // object stream flag. Used to make read(n) ignore n and to
  8910. // make all the buffer merging and length checks go away
  8911. this.objectMode = !!options.objectMode;
  8912. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  8913. // the point at which it stops calling _read() to fill the buffer
  8914. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  8915. var hwm = options.highWaterMark;
  8916. var readableHwm = options.readableHighWaterMark;
  8917. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  8918. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  8919. // cast to ints.
  8920. this.highWaterMark = Math.floor(this.highWaterMark);
  8921. // A linked list is used to store data chunks instead of an array because the
  8922. // linked list can remove elements from the beginning faster than
  8923. // array.shift()
  8924. this.buffer = new BufferList();
  8925. this.length = 0;
  8926. this.pipes = null;
  8927. this.pipesCount = 0;
  8928. this.flowing = null;
  8929. this.ended = false;
  8930. this.endEmitted = false;
  8931. this.reading = false;
  8932. // a flag to be able to tell if the event 'readable'/'data' is emitted
  8933. // immediately, or on a later tick. We set this to true at first, because
  8934. // any actions that shouldn't happen until "later" should generally also
  8935. // not happen before the first read call.
  8936. this.sync = true;
  8937. // whenever we return null, then we set a flag to say
  8938. // that we're awaiting a 'readable' event emission.
  8939. this.needReadable = false;
  8940. this.emittedReadable = false;
  8941. this.readableListening = false;
  8942. this.resumeScheduled = false;
  8943. // has it been destroyed
  8944. this.destroyed = false;
  8945. // Crypto is kind of old and crusty. Historically, its default string
  8946. // encoding is 'binary' so we have to make this configurable.
  8947. // Everything else in the universe uses 'utf8', though.
  8948. this.defaultEncoding = options.defaultEncoding || 'utf8';
  8949. // the number of writers that are awaiting a drain event in .pipe()s
  8950. this.awaitDrain = 0;
  8951. // if true, a maybeReadMore has been scheduled
  8952. this.readingMore = false;
  8953. this.decoder = null;
  8954. this.encoding = null;
  8955. if (options.encoding) {
  8956. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  8957. this.decoder = new StringDecoder(options.encoding);
  8958. this.encoding = options.encoding;
  8959. }
  8960. }
  8961. function Readable(options) {
  8962. Duplex = Duplex || require('./_stream_duplex');
  8963. if (!(this instanceof Readable)) return new Readable(options);
  8964. this._readableState = new ReadableState(options, this);
  8965. // legacy
  8966. this.readable = true;
  8967. if (options) {
  8968. if (typeof options.read === 'function') this._read = options.read;
  8969. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  8970. }
  8971. Stream.call(this);
  8972. }
  8973. Object.defineProperty(Readable.prototype, 'destroyed', {
  8974. get: function () {
  8975. if (this._readableState === undefined) {
  8976. return false;
  8977. }
  8978. return this._readableState.destroyed;
  8979. },
  8980. set: function (value) {
  8981. // we ignore the value if the stream
  8982. // has not been initialized yet
  8983. if (!this._readableState) {
  8984. return;
  8985. }
  8986. // backward compatibility, the user is explicitly
  8987. // managing destroyed
  8988. this._readableState.destroyed = value;
  8989. }
  8990. });
  8991. Readable.prototype.destroy = destroyImpl.destroy;
  8992. Readable.prototype._undestroy = destroyImpl.undestroy;
  8993. Readable.prototype._destroy = function (err, cb) {
  8994. this.push(null);
  8995. cb(err);
  8996. };
  8997. // Manually shove something into the read() buffer.
  8998. // This returns true if the highWaterMark has not been hit yet,
  8999. // similar to how Writable.write() returns true if you should
  9000. // write() some more.
  9001. Readable.prototype.push = function (chunk, encoding) {
  9002. var state = this._readableState;
  9003. var skipChunkCheck;
  9004. if (!state.objectMode) {
  9005. if (typeof chunk === 'string') {
  9006. encoding = encoding || state.defaultEncoding;
  9007. if (encoding !== state.encoding) {
  9008. chunk = Buffer.from(chunk, encoding);
  9009. encoding = '';
  9010. }
  9011. skipChunkCheck = true;
  9012. }
  9013. } else {
  9014. skipChunkCheck = true;
  9015. }
  9016. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  9017. };
  9018. // Unshift should *always* be something directly out of read()
  9019. Readable.prototype.unshift = function (chunk) {
  9020. return readableAddChunk(this, chunk, null, true, false);
  9021. };
  9022. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  9023. var state = stream._readableState;
  9024. if (chunk === null) {
  9025. state.reading = false;
  9026. onEofChunk(stream, state);
  9027. } else {
  9028. var er;
  9029. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  9030. if (er) {
  9031. stream.emit('error', er);
  9032. } else if (state.objectMode || chunk && chunk.length > 0) {
  9033. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  9034. chunk = _uint8ArrayToBuffer(chunk);
  9035. }
  9036. if (addToFront) {
  9037. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  9038. } else if (state.ended) {
  9039. stream.emit('error', new Error('stream.push() after EOF'));
  9040. } else {
  9041. state.reading = false;
  9042. if (state.decoder && !encoding) {
  9043. chunk = state.decoder.write(chunk);
  9044. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  9045. } else {
  9046. addChunk(stream, state, chunk, false);
  9047. }
  9048. }
  9049. } else if (!addToFront) {
  9050. state.reading = false;
  9051. }
  9052. }
  9053. return needMoreData(state);
  9054. }
  9055. function addChunk(stream, state, chunk, addToFront) {
  9056. if (state.flowing && state.length === 0 && !state.sync) {
  9057. stream.emit('data', chunk);
  9058. stream.read(0);
  9059. } else {
  9060. // update the buffer info.
  9061. state.length += state.objectMode ? 1 : chunk.length;
  9062. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  9063. if (state.needReadable) emitReadable(stream);
  9064. }
  9065. maybeReadMore(stream, state);
  9066. }
  9067. function chunkInvalid(state, chunk) {
  9068. var er;
  9069. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  9070. er = new TypeError('Invalid non-string/buffer chunk');
  9071. }
  9072. return er;
  9073. }
  9074. // if it's past the high water mark, we can push in some more.
  9075. // Also, if we have no data yet, we can stand some
  9076. // more bytes. This is to work around cases where hwm=0,
  9077. // such as the repl. Also, if the push() triggered a
  9078. // readable event, and the user called read(largeNumber) such that
  9079. // needReadable was set, then we ought to push more, so that another
  9080. // 'readable' event will be triggered.
  9081. function needMoreData(state) {
  9082. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  9083. }
  9084. Readable.prototype.isPaused = function () {
  9085. return this._readableState.flowing === false;
  9086. };
  9087. // backwards compatibility.
  9088. Readable.prototype.setEncoding = function (enc) {
  9089. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9090. this._readableState.decoder = new StringDecoder(enc);
  9091. this._readableState.encoding = enc;
  9092. return this;
  9093. };
  9094. // Don't raise the hwm > 8MB
  9095. var MAX_HWM = 0x800000;
  9096. function computeNewHighWaterMark(n) {
  9097. if (n >= MAX_HWM) {
  9098. n = MAX_HWM;
  9099. } else {
  9100. // Get the next highest power of 2 to prevent increasing hwm excessively in
  9101. // tiny amounts
  9102. n--;
  9103. n |= n >>> 1;
  9104. n |= n >>> 2;
  9105. n |= n >>> 4;
  9106. n |= n >>> 8;
  9107. n |= n >>> 16;
  9108. n++;
  9109. }
  9110. return n;
  9111. }
  9112. // This function is designed to be inlinable, so please take care when making
  9113. // changes to the function body.
  9114. function howMuchToRead(n, state) {
  9115. if (n <= 0 || state.length === 0 && state.ended) return 0;
  9116. if (state.objectMode) return 1;
  9117. if (n !== n) {
  9118. // Only flow one buffer at a time
  9119. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  9120. }
  9121. // If we're asking for more than the current hwm, then raise the hwm.
  9122. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  9123. if (n <= state.length) return n;
  9124. // Don't have enough
  9125. if (!state.ended) {
  9126. state.needReadable = true;
  9127. return 0;
  9128. }
  9129. return state.length;
  9130. }
  9131. // you can override either this method, or the async _read(n) below.
  9132. Readable.prototype.read = function (n) {
  9133. debug('read', n);
  9134. n = parseInt(n, 10);
  9135. var state = this._readableState;
  9136. var nOrig = n;
  9137. if (n !== 0) state.emittedReadable = false;
  9138. // if we're doing read(0) to trigger a readable event, but we
  9139. // already have a bunch of data in the buffer, then just trigger
  9140. // the 'readable' event and move on.
  9141. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  9142. debug('read: emitReadable', state.length, state.ended);
  9143. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  9144. return null;
  9145. }
  9146. n = howMuchToRead(n, state);
  9147. // if we've ended, and we're now clear, then finish it up.
  9148. if (n === 0 && state.ended) {
  9149. if (state.length === 0) endReadable(this);
  9150. return null;
  9151. }
  9152. // All the actual chunk generation logic needs to be
  9153. // *below* the call to _read. The reason is that in certain
  9154. // synthetic stream cases, such as passthrough streams, _read
  9155. // may be a completely synchronous operation which may change
  9156. // the state of the read buffer, providing enough data when
  9157. // before there was *not* enough.
  9158. //
  9159. // So, the steps are:
  9160. // 1. Figure out what the state of things will be after we do
  9161. // a read from the buffer.
  9162. //
  9163. // 2. If that resulting state will trigger a _read, then call _read.
  9164. // Note that this may be asynchronous, or synchronous. Yes, it is
  9165. // deeply ugly to write APIs this way, but that still doesn't mean
  9166. // that the Readable class should behave improperly, as streams are
  9167. // designed to be sync/async agnostic.
  9168. // Take note if the _read call is sync or async (ie, if the read call
  9169. // has returned yet), so that we know whether or not it's safe to emit
  9170. // 'readable' etc.
  9171. //
  9172. // 3. Actually pull the requested chunks out of the buffer and return.
  9173. // if we need a readable event, then we need to do some reading.
  9174. var doRead = state.needReadable;
  9175. debug('need readable', doRead);
  9176. // if we currently have less than the highWaterMark, then also read some
  9177. if (state.length === 0 || state.length - n < state.highWaterMark) {
  9178. doRead = true;
  9179. debug('length less than watermark', doRead);
  9180. }
  9181. // however, if we've ended, then there's no point, and if we're already
  9182. // reading, then it's unnecessary.
  9183. if (state.ended || state.reading) {
  9184. doRead = false;
  9185. debug('reading or ended', doRead);
  9186. } else if (doRead) {
  9187. debug('do read');
  9188. state.reading = true;
  9189. state.sync = true;
  9190. // if the length is currently zero, then we *need* a readable event.
  9191. if (state.length === 0) state.needReadable = true;
  9192. // call internal read method
  9193. this._read(state.highWaterMark);
  9194. state.sync = false;
  9195. // If _read pushed data synchronously, then `reading` will be false,
  9196. // and we need to re-evaluate how much data we can return to the user.
  9197. if (!state.reading) n = howMuchToRead(nOrig, state);
  9198. }
  9199. var ret;
  9200. if (n > 0) ret = fromList(n, state);else ret = null;
  9201. if (ret === null) {
  9202. state.needReadable = true;
  9203. n = 0;
  9204. } else {
  9205. state.length -= n;
  9206. }
  9207. if (state.length === 0) {
  9208. // If we have nothing in the buffer, then we want to know
  9209. // as soon as we *do* get something into the buffer.
  9210. if (!state.ended) state.needReadable = true;
  9211. // If we tried to read() past the EOF, then emit end on the next tick.
  9212. if (nOrig !== n && state.ended) endReadable(this);
  9213. }
  9214. if (ret !== null) this.emit('data', ret);
  9215. return ret;
  9216. };
  9217. function onEofChunk(stream, state) {
  9218. if (state.ended) return;
  9219. if (state.decoder) {
  9220. var chunk = state.decoder.end();
  9221. if (chunk && chunk.length) {
  9222. state.buffer.push(chunk);
  9223. state.length += state.objectMode ? 1 : chunk.length;
  9224. }
  9225. }
  9226. state.ended = true;
  9227. // emit 'readable' now to make sure it gets picked up.
  9228. emitReadable(stream);
  9229. }
  9230. // Don't emit readable right away in sync mode, because this can trigger
  9231. // another read() call => stack overflow. This way, it might trigger
  9232. // a nextTick recursion warning, but that's not so bad.
  9233. function emitReadable(stream) {
  9234. var state = stream._readableState;
  9235. state.needReadable = false;
  9236. if (!state.emittedReadable) {
  9237. debug('emitReadable', state.flowing);
  9238. state.emittedReadable = true;
  9239. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  9240. }
  9241. }
  9242. function emitReadable_(stream) {
  9243. debug('emit readable');
  9244. stream.emit('readable');
  9245. flow(stream);
  9246. }
  9247. // at this point, the user has presumably seen the 'readable' event,
  9248. // and called read() to consume some data. that may have triggered
  9249. // in turn another _read(n) call, in which case reading = true if
  9250. // it's in progress.
  9251. // However, if we're not ended, or reading, and the length < hwm,
  9252. // then go ahead and try to read some more preemptively.
  9253. function maybeReadMore(stream, state) {
  9254. if (!state.readingMore) {
  9255. state.readingMore = true;
  9256. pna.nextTick(maybeReadMore_, stream, state);
  9257. }
  9258. }
  9259. function maybeReadMore_(stream, state) {
  9260. var len = state.length;
  9261. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  9262. debug('maybeReadMore read 0');
  9263. stream.read(0);
  9264. if (len === state.length)
  9265. // didn't get any data, stop spinning.
  9266. break;else len = state.length;
  9267. }
  9268. state.readingMore = false;
  9269. }
  9270. // abstract method. to be overridden in specific implementation classes.
  9271. // call cb(er, data) where data is <= n in length.
  9272. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  9273. // arbitrary, and perhaps not very meaningful.
  9274. Readable.prototype._read = function (n) {
  9275. this.emit('error', new Error('_read() is not implemented'));
  9276. };
  9277. Readable.prototype.pipe = function (dest, pipeOpts) {
  9278. var src = this;
  9279. var state = this._readableState;
  9280. switch (state.pipesCount) {
  9281. case 0:
  9282. state.pipes = dest;
  9283. break;
  9284. case 1:
  9285. state.pipes = [state.pipes, dest];
  9286. break;
  9287. default:
  9288. state.pipes.push(dest);
  9289. break;
  9290. }
  9291. state.pipesCount += 1;
  9292. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  9293. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  9294. var endFn = doEnd ? onend : unpipe;
  9295. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  9296. dest.on('unpipe', onunpipe);
  9297. function onunpipe(readable, unpipeInfo) {
  9298. debug('onunpipe');
  9299. if (readable === src) {
  9300. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  9301. unpipeInfo.hasUnpiped = true;
  9302. cleanup();
  9303. }
  9304. }
  9305. }
  9306. function onend() {
  9307. debug('onend');
  9308. dest.end();
  9309. }
  9310. // when the dest drains, it reduces the awaitDrain counter
  9311. // on the source. This would be more elegant with a .once()
  9312. // handler in flow(), but adding and removing repeatedly is
  9313. // too slow.
  9314. var ondrain = pipeOnDrain(src);
  9315. dest.on('drain', ondrain);
  9316. var cleanedUp = false;
  9317. function cleanup() {
  9318. debug('cleanup');
  9319. // cleanup event handlers once the pipe is broken
  9320. dest.removeListener('close', onclose);
  9321. dest.removeListener('finish', onfinish);
  9322. dest.removeListener('drain', ondrain);
  9323. dest.removeListener('error', onerror);
  9324. dest.removeListener('unpipe', onunpipe);
  9325. src.removeListener('end', onend);
  9326. src.removeListener('end', unpipe);
  9327. src.removeListener('data', ondata);
  9328. cleanedUp = true;
  9329. // if the reader is waiting for a drain event from this
  9330. // specific writer, then it would cause it to never start
  9331. // flowing again.
  9332. // So, if this is awaiting a drain, then we just call it now.
  9333. // If we don't know, then assume that we are waiting for one.
  9334. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  9335. }
  9336. // If the user pushes more data while we're writing to dest then we'll end up
  9337. // in ondata again. However, we only want to increase awaitDrain once because
  9338. // dest will only emit one 'drain' event for the multiple writes.
  9339. // => Introduce a guard on increasing awaitDrain.
  9340. var increasedAwaitDrain = false;
  9341. src.on('data', ondata);
  9342. function ondata(chunk) {
  9343. debug('ondata');
  9344. increasedAwaitDrain = false;
  9345. var ret = dest.write(chunk);
  9346. if (false === ret && !increasedAwaitDrain) {
  9347. // If the user unpiped during `dest.write()`, it is possible
  9348. // to get stuck in a permanently paused state if that write
  9349. // also returned false.
  9350. // => Check whether `dest` is still a piping destination.
  9351. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  9352. debug('false write response, pause', src._readableState.awaitDrain);
  9353. src._readableState.awaitDrain++;
  9354. increasedAwaitDrain = true;
  9355. }
  9356. src.pause();
  9357. }
  9358. }
  9359. // if the dest has an error, then stop piping into it.
  9360. // however, don't suppress the throwing behavior for this.
  9361. function onerror(er) {
  9362. debug('onerror', er);
  9363. unpipe();
  9364. dest.removeListener('error', onerror);
  9365. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  9366. }
  9367. // Make sure our error handler is attached before userland ones.
  9368. prependListener(dest, 'error', onerror);
  9369. // Both close and finish should trigger unpipe, but only once.
  9370. function onclose() {
  9371. dest.removeListener('finish', onfinish);
  9372. unpipe();
  9373. }
  9374. dest.once('close', onclose);
  9375. function onfinish() {
  9376. debug('onfinish');
  9377. dest.removeListener('close', onclose);
  9378. unpipe();
  9379. }
  9380. dest.once('finish', onfinish);
  9381. function unpipe() {
  9382. debug('unpipe');
  9383. src.unpipe(dest);
  9384. }
  9385. // tell the dest that it's being piped to
  9386. dest.emit('pipe', src);
  9387. // start the flow if it hasn't been started already.
  9388. if (!state.flowing) {
  9389. debug('pipe resume');
  9390. src.resume();
  9391. }
  9392. return dest;
  9393. };
  9394. function pipeOnDrain(src) {
  9395. return function () {
  9396. var state = src._readableState;
  9397. debug('pipeOnDrain', state.awaitDrain);
  9398. if (state.awaitDrain) state.awaitDrain--;
  9399. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  9400. state.flowing = true;
  9401. flow(src);
  9402. }
  9403. };
  9404. }
  9405. Readable.prototype.unpipe = function (dest) {
  9406. var state = this._readableState;
  9407. var unpipeInfo = { hasUnpiped: false };
  9408. // if we're not piping anywhere, then do nothing.
  9409. if (state.pipesCount === 0) return this;
  9410. // just one destination. most common case.
  9411. if (state.pipesCount === 1) {
  9412. // passed in one, but it's not the right one.
  9413. if (dest && dest !== state.pipes) return this;
  9414. if (!dest) dest = state.pipes;
  9415. // got a match.
  9416. state.pipes = null;
  9417. state.pipesCount = 0;
  9418. state.flowing = false;
  9419. if (dest) dest.emit('unpipe', this, unpipeInfo);
  9420. return this;
  9421. }
  9422. // slow case. multiple pipe destinations.
  9423. if (!dest) {
  9424. // remove all.
  9425. var dests = state.pipes;
  9426. var len = state.pipesCount;
  9427. state.pipes = null;
  9428. state.pipesCount = 0;
  9429. state.flowing = false;
  9430. for (var i = 0; i < len; i++) {
  9431. dests[i].emit('unpipe', this, unpipeInfo);
  9432. }return this;
  9433. }
  9434. // try to find the right one.
  9435. var index = indexOf(state.pipes, dest);
  9436. if (index === -1) return this;
  9437. state.pipes.splice(index, 1);
  9438. state.pipesCount -= 1;
  9439. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  9440. dest.emit('unpipe', this, unpipeInfo);
  9441. return this;
  9442. };
  9443. // set up data events if they are asked for
  9444. // Ensure readable listeners eventually get something
  9445. Readable.prototype.on = function (ev, fn) {
  9446. var res = Stream.prototype.on.call(this, ev, fn);
  9447. if (ev === 'data') {
  9448. // Start flowing on next tick if stream isn't explicitly paused
  9449. if (this._readableState.flowing !== false) this.resume();
  9450. } else if (ev === 'readable') {
  9451. var state = this._readableState;
  9452. if (!state.endEmitted && !state.readableListening) {
  9453. state.readableListening = state.needReadable = true;
  9454. state.emittedReadable = false;
  9455. if (!state.reading) {
  9456. pna.nextTick(nReadingNextTick, this);
  9457. } else if (state.length) {
  9458. emitReadable(this);
  9459. }
  9460. }
  9461. }
  9462. return res;
  9463. };
  9464. Readable.prototype.addListener = Readable.prototype.on;
  9465. function nReadingNextTick(self) {
  9466. debug('readable nexttick read 0');
  9467. self.read(0);
  9468. }
  9469. // pause() and resume() are remnants of the legacy readable stream API
  9470. // If the user uses them, then switch into old mode.
  9471. Readable.prototype.resume = function () {
  9472. var state = this._readableState;
  9473. if (!state.flowing) {
  9474. debug('resume');
  9475. state.flowing = true;
  9476. resume(this, state);
  9477. }
  9478. return this;
  9479. };
  9480. function resume(stream, state) {
  9481. if (!state.resumeScheduled) {
  9482. state.resumeScheduled = true;
  9483. pna.nextTick(resume_, stream, state);
  9484. }
  9485. }
  9486. function resume_(stream, state) {
  9487. if (!state.reading) {
  9488. debug('resume read 0');
  9489. stream.read(0);
  9490. }
  9491. state.resumeScheduled = false;
  9492. state.awaitDrain = 0;
  9493. stream.emit('resume');
  9494. flow(stream);
  9495. if (state.flowing && !state.reading) stream.read(0);
  9496. }
  9497. Readable.prototype.pause = function () {
  9498. debug('call pause flowing=%j', this._readableState.flowing);
  9499. if (false !== this._readableState.flowing) {
  9500. debug('pause');
  9501. this._readableState.flowing = false;
  9502. this.emit('pause');
  9503. }
  9504. return this;
  9505. };
  9506. function flow(stream) {
  9507. var state = stream._readableState;
  9508. debug('flow', state.flowing);
  9509. while (state.flowing && stream.read() !== null) {}
  9510. }
  9511. // wrap an old-style stream as the async data source.
  9512. // This is *not* part of the readable stream interface.
  9513. // It is an ugly unfortunate mess of history.
  9514. Readable.prototype.wrap = function (stream) {
  9515. var _this = this;
  9516. var state = this._readableState;
  9517. var paused = false;
  9518. stream.on('end', function () {
  9519. debug('wrapped end');
  9520. if (state.decoder && !state.ended) {
  9521. var chunk = state.decoder.end();
  9522. if (chunk && chunk.length) _this.push(chunk);
  9523. }
  9524. _this.push(null);
  9525. });
  9526. stream.on('data', function (chunk) {
  9527. debug('wrapped data');
  9528. if (state.decoder) chunk = state.decoder.write(chunk);
  9529. // don't skip over falsy values in objectMode
  9530. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  9531. var ret = _this.push(chunk);
  9532. if (!ret) {
  9533. paused = true;
  9534. stream.pause();
  9535. }
  9536. });
  9537. // proxy all the other methods.
  9538. // important when wrapping filters and duplexes.
  9539. for (var i in stream) {
  9540. if (this[i] === undefined && typeof stream[i] === 'function') {
  9541. this[i] = function (method) {
  9542. return function () {
  9543. return stream[method].apply(stream, arguments);
  9544. };
  9545. }(i);
  9546. }
  9547. }
  9548. // proxy certain important events.
  9549. for (var n = 0; n < kProxyEvents.length; n++) {
  9550. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  9551. }
  9552. // when we try to consume some more bytes, simply unpause the
  9553. // underlying stream.
  9554. this._read = function (n) {
  9555. debug('wrapped _read', n);
  9556. if (paused) {
  9557. paused = false;
  9558. stream.resume();
  9559. }
  9560. };
  9561. return this;
  9562. };
  9563. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  9564. // making it explicit this property is not enumerable
  9565. // because otherwise some prototype manipulation in
  9566. // userland will fail
  9567. enumerable: false,
  9568. get: function () {
  9569. return this._readableState.highWaterMark;
  9570. }
  9571. });
  9572. // exposed for testing purposes only.
  9573. Readable._fromList = fromList;
  9574. // Pluck off n bytes from an array of buffers.
  9575. // Length is the combined lengths of all the buffers in the list.
  9576. // This function is designed to be inlinable, so please take care when making
  9577. // changes to the function body.
  9578. function fromList(n, state) {
  9579. // nothing buffered
  9580. if (state.length === 0) return null;
  9581. var ret;
  9582. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  9583. // read it all, truncate the list
  9584. 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);
  9585. state.buffer.clear();
  9586. } else {
  9587. // read part of list
  9588. ret = fromListPartial(n, state.buffer, state.decoder);
  9589. }
  9590. return ret;
  9591. }
  9592. // Extracts only enough buffered data to satisfy the amount requested.
  9593. // This function is designed to be inlinable, so please take care when making
  9594. // changes to the function body.
  9595. function fromListPartial(n, list, hasStrings) {
  9596. var ret;
  9597. if (n < list.head.data.length) {
  9598. // slice is the same for buffers and strings
  9599. ret = list.head.data.slice(0, n);
  9600. list.head.data = list.head.data.slice(n);
  9601. } else if (n === list.head.data.length) {
  9602. // first chunk is a perfect match
  9603. ret = list.shift();
  9604. } else {
  9605. // result spans more than one buffer
  9606. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  9607. }
  9608. return ret;
  9609. }
  9610. // Copies a specified amount of characters from the list of buffered data
  9611. // chunks.
  9612. // This function is designed to be inlinable, so please take care when making
  9613. // changes to the function body.
  9614. function copyFromBufferString(n, list) {
  9615. var p = list.head;
  9616. var c = 1;
  9617. var ret = p.data;
  9618. n -= ret.length;
  9619. while (p = p.next) {
  9620. var str = p.data;
  9621. var nb = n > str.length ? str.length : n;
  9622. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  9623. n -= nb;
  9624. if (n === 0) {
  9625. if (nb === str.length) {
  9626. ++c;
  9627. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9628. } else {
  9629. list.head = p;
  9630. p.data = str.slice(nb);
  9631. }
  9632. break;
  9633. }
  9634. ++c;
  9635. }
  9636. list.length -= c;
  9637. return ret;
  9638. }
  9639. // Copies a specified amount of bytes from the list of buffered data chunks.
  9640. // This function is designed to be inlinable, so please take care when making
  9641. // changes to the function body.
  9642. function copyFromBuffer(n, list) {
  9643. var ret = Buffer.allocUnsafe(n);
  9644. var p = list.head;
  9645. var c = 1;
  9646. p.data.copy(ret);
  9647. n -= p.data.length;
  9648. while (p = p.next) {
  9649. var buf = p.data;
  9650. var nb = n > buf.length ? buf.length : n;
  9651. buf.copy(ret, ret.length - n, 0, nb);
  9652. n -= nb;
  9653. if (n === 0) {
  9654. if (nb === buf.length) {
  9655. ++c;
  9656. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9657. } else {
  9658. list.head = p;
  9659. p.data = buf.slice(nb);
  9660. }
  9661. break;
  9662. }
  9663. ++c;
  9664. }
  9665. list.length -= c;
  9666. return ret;
  9667. }
  9668. function endReadable(stream) {
  9669. var state = stream._readableState;
  9670. // If we get here before consuming all the bytes, then that is a
  9671. // bug in node. Should never happen.
  9672. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  9673. if (!state.endEmitted) {
  9674. state.ended = true;
  9675. pna.nextTick(endReadableNT, state, stream);
  9676. }
  9677. }
  9678. function endReadableNT(state, stream) {
  9679. // Check that we didn't get one last unshift.
  9680. if (!state.endEmitted && state.length === 0) {
  9681. state.endEmitted = true;
  9682. stream.readable = false;
  9683. stream.emit('end');
  9684. }
  9685. }
  9686. function indexOf(xs, x) {
  9687. for (var i = 0, l = xs.length; i < l; i++) {
  9688. if (xs[i] === x) return i;
  9689. }
  9690. return -1;
  9691. }
  9692. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9693. },{"./_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){
  9694. // Copyright Joyent, Inc. and other Node contributors.
  9695. //
  9696. // Permission is hereby granted, free of charge, to any person obtaining a
  9697. // copy of this software and associated documentation files (the
  9698. // "Software"), to deal in the Software without restriction, including
  9699. // without limitation the rights to use, copy, modify, merge, publish,
  9700. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9701. // persons to whom the Software is furnished to do so, subject to the
  9702. // following conditions:
  9703. //
  9704. // The above copyright notice and this permission notice shall be included
  9705. // in all copies or substantial portions of the Software.
  9706. //
  9707. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9708. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9709. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9710. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9711. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9712. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9713. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9714. // a transform stream is a readable/writable stream where you do
  9715. // something with the data. Sometimes it's called a "filter",
  9716. // but that's not a great name for it, since that implies a thing where
  9717. // some bits pass through, and others are simply ignored. (That would
  9718. // be a valid example of a transform, of course.)
  9719. //
  9720. // While the output is causally related to the input, it's not a
  9721. // necessarily symmetric or synchronous transformation. For example,
  9722. // a zlib stream might take multiple plain-text writes(), and then
  9723. // emit a single compressed chunk some time in the future.
  9724. //
  9725. // Here's how this works:
  9726. //
  9727. // The Transform stream has all the aspects of the readable and writable
  9728. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  9729. // internally, and returns false if there's a lot of pending writes
  9730. // buffered up. When you call read(), that calls _read(n) until
  9731. // there's enough pending readable data buffered up.
  9732. //
  9733. // In a transform stream, the written data is placed in a buffer. When
  9734. // _read(n) is called, it transforms the queued up data, calling the
  9735. // buffered _write cb's as it consumes chunks. If consuming a single
  9736. // written chunk would result in multiple output chunks, then the first
  9737. // outputted bit calls the readcb, and subsequent chunks just go into
  9738. // the read buffer, and will cause it to emit 'readable' if necessary.
  9739. //
  9740. // This way, back-pressure is actually determined by the reading side,
  9741. // since _read has to be called to start processing a new chunk. However,
  9742. // a pathological inflate type of transform can cause excessive buffering
  9743. // here. For example, imagine a stream where every byte of input is
  9744. // interpreted as an integer from 0-255, and then results in that many
  9745. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  9746. // 1kb of data being output. In this case, you could write a very small
  9747. // amount of input, and end up with a very large amount of output. In
  9748. // such a pathological inflating mechanism, there'd be no way to tell
  9749. // the system to stop doing the transform. A single 4MB write could
  9750. // cause the system to run out of memory.
  9751. //
  9752. // However, even in such a pathological case, only a single written chunk
  9753. // would be consumed, and then the rest would wait (un-transformed) until
  9754. // the results of the previous transformed chunk were consumed.
  9755. 'use strict';
  9756. module.exports = Transform;
  9757. var Duplex = require('./_stream_duplex');
  9758. /*<replacement>*/
  9759. var util = require('core-util-is');
  9760. util.inherits = require('inherits');
  9761. /*</replacement>*/
  9762. util.inherits(Transform, Duplex);
  9763. function afterTransform(er, data) {
  9764. var ts = this._transformState;
  9765. ts.transforming = false;
  9766. var cb = ts.writecb;
  9767. if (!cb) {
  9768. return this.emit('error', new Error('write callback called multiple times'));
  9769. }
  9770. ts.writechunk = null;
  9771. ts.writecb = null;
  9772. if (data != null) // single equals check for both `null` and `undefined`
  9773. this.push(data);
  9774. cb(er);
  9775. var rs = this._readableState;
  9776. rs.reading = false;
  9777. if (rs.needReadable || rs.length < rs.highWaterMark) {
  9778. this._read(rs.highWaterMark);
  9779. }
  9780. }
  9781. function Transform(options) {
  9782. if (!(this instanceof Transform)) return new Transform(options);
  9783. Duplex.call(this, options);
  9784. this._transformState = {
  9785. afterTransform: afterTransform.bind(this),
  9786. needTransform: false,
  9787. transforming: false,
  9788. writecb: null,
  9789. writechunk: null,
  9790. writeencoding: null
  9791. };
  9792. // start out asking for a readable event once data is transformed.
  9793. this._readableState.needReadable = true;
  9794. // we have implemented the _read method, and done the other things
  9795. // that Readable wants before the first _read call, so unset the
  9796. // sync guard flag.
  9797. this._readableState.sync = false;
  9798. if (options) {
  9799. if (typeof options.transform === 'function') this._transform = options.transform;
  9800. if (typeof options.flush === 'function') this._flush = options.flush;
  9801. }
  9802. // When the writable side finishes, then flush out anything remaining.
  9803. this.on('prefinish', prefinish);
  9804. }
  9805. function prefinish() {
  9806. var _this = this;
  9807. if (typeof this._flush === 'function') {
  9808. this._flush(function (er, data) {
  9809. done(_this, er, data);
  9810. });
  9811. } else {
  9812. done(this, null, null);
  9813. }
  9814. }
  9815. Transform.prototype.push = function (chunk, encoding) {
  9816. this._transformState.needTransform = false;
  9817. return Duplex.prototype.push.call(this, chunk, encoding);
  9818. };
  9819. // This is the part where you do stuff!
  9820. // override this function in implementation classes.
  9821. // 'chunk' is an input chunk.
  9822. //
  9823. // Call `push(newChunk)` to pass along transformed output
  9824. // to the readable side. You may call 'push' zero or more times.
  9825. //
  9826. // Call `cb(err)` when you are done with this chunk. If you pass
  9827. // an error, then that'll put the hurt on the whole operation. If you
  9828. // never call cb(), then you'll never get another chunk.
  9829. Transform.prototype._transform = function (chunk, encoding, cb) {
  9830. throw new Error('_transform() is not implemented');
  9831. };
  9832. Transform.prototype._write = function (chunk, encoding, cb) {
  9833. var ts = this._transformState;
  9834. ts.writecb = cb;
  9835. ts.writechunk = chunk;
  9836. ts.writeencoding = encoding;
  9837. if (!ts.transforming) {
  9838. var rs = this._readableState;
  9839. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  9840. }
  9841. };
  9842. // Doesn't matter what the args are here.
  9843. // _transform does all the work.
  9844. // That we got here means that the readable side wants more data.
  9845. Transform.prototype._read = function (n) {
  9846. var ts = this._transformState;
  9847. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  9848. ts.transforming = true;
  9849. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  9850. } else {
  9851. // mark that we need a transform, so that any data that comes in
  9852. // will get processed, now that we've asked for it.
  9853. ts.needTransform = true;
  9854. }
  9855. };
  9856. Transform.prototype._destroy = function (err, cb) {
  9857. var _this2 = this;
  9858. Duplex.prototype._destroy.call(this, err, function (err2) {
  9859. cb(err2);
  9860. console.log(`.call(this, err, function (err2) {`)
  9861. _this2.emit('close');
  9862. });
  9863. };
  9864. function done(stream, er, data) {
  9865. if (er) return stream.emit('error', er);
  9866. if (data != null) // single equals check for both `null` and `undefined`
  9867. stream.push(data);
  9868. // if there's nothing in the write buffer, then that means
  9869. // that nothing more will ever be provided
  9870. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  9871. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  9872. return stream.push(null);
  9873. }
  9874. },{"./_stream_duplex":98,"core-util-is":14,"inherits":80}],102:[function(require,module,exports){
  9875. (function (process,global,setImmediate){
  9876. // Copyright Joyent, Inc. and other Node contributors.
  9877. //
  9878. // Permission is hereby granted, free of charge, to any person obtaining a
  9879. // copy of this software and associated documentation files (the
  9880. // "Software"), to deal in the Software without restriction, including
  9881. // without limitation the rights to use, copy, modify, merge, publish,
  9882. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9883. // persons to whom the Software is furnished to do so, subject to the
  9884. // following conditions:
  9885. //
  9886. // The above copyright notice and this permission notice shall be included
  9887. // in all copies or substantial portions of the Software.
  9888. //
  9889. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9890. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9891. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9892. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9893. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9894. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9895. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9896. // A bit simpler than readable streams.
  9897. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  9898. // the drain event emission and buffering.
  9899. 'use strict';
  9900. /*<replacement>*/
  9901. var pna = require('process-nextick-args');
  9902. /*</replacement>*/
  9903. module.exports = Writable;
  9904. /* <replacement> */
  9905. function WriteReq(chunk, encoding, cb) {
  9906. this.chunk = chunk;
  9907. this.encoding = encoding;
  9908. this.callback = cb;
  9909. this.next = null;
  9910. }
  9911. // It seems a linked list but it is not
  9912. // there will be only 2 of these for each stream
  9913. function CorkedRequest(state) {
  9914. var _this = this;
  9915. this.next = null;
  9916. this.entry = null;
  9917. this.finish = function () {
  9918. onCorkedFinish(_this, state);
  9919. };
  9920. }
  9921. /* </replacement> */
  9922. /*<replacement>*/
  9923. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  9924. /*</replacement>*/
  9925. /*<replacement>*/
  9926. var Duplex;
  9927. /*</replacement>*/
  9928. Writable.WritableState = WritableState;
  9929. /*<replacement>*/
  9930. var util = require('core-util-is');
  9931. util.inherits = require('inherits');
  9932. /*</replacement>*/
  9933. /*<replacement>*/
  9934. var internalUtil = {
  9935. deprecate: require('util-deprecate')
  9936. };
  9937. /*</replacement>*/
  9938. /*<replacement>*/
  9939. var Stream = require('./internal/streams/stream');
  9940. /*</replacement>*/
  9941. /*<replacement>*/
  9942. var Buffer = require('safe-buffer').Buffer;
  9943. var OurUint8Array = global.Uint8Array || function () {};
  9944. function _uint8ArrayToBuffer(chunk) {
  9945. return Buffer.from(chunk);
  9946. }
  9947. function _isUint8Array(obj) {
  9948. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  9949. }
  9950. /*</replacement>*/
  9951. var destroyImpl = require('./internal/streams/destroy');
  9952. util.inherits(Writable, Stream);
  9953. function nop() {}
  9954. function WritableState(options, stream) {
  9955. Duplex = Duplex || require('./_stream_duplex');
  9956. options = options || {};
  9957. // Duplex streams are both readable and writable, but share
  9958. // the same options object.
  9959. // However, some cases require setting options to different
  9960. // values for the readable and the writable sides of the duplex stream.
  9961. // These options can be provided separately as readableXXX and writableXXX.
  9962. var isDuplex = stream instanceof Duplex;
  9963. // object stream flag to indicate whether or not this stream
  9964. // contains buffers or objects.
  9965. this.objectMode = !!options.objectMode;
  9966. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  9967. // the point at which write() starts returning false
  9968. // Note: 0 is a valid value, means that we always return false if
  9969. // the entire buffer is not flushed immediately on write()
  9970. var hwm = options.highWaterMark;
  9971. var writableHwm = options.writableHighWaterMark;
  9972. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  9973. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  9974. // cast to ints.
  9975. this.highWaterMark = Math.floor(this.highWaterMark);
  9976. // if _final has been called
  9977. this.finalCalled = false;
  9978. // drain event flag.
  9979. this.needDrain = false;
  9980. // at the start of calling end()
  9981. this.ending = false;
  9982. // when end() has been called, and returned
  9983. this.ended = false;
  9984. // when 'finish' is emitted
  9985. this.finished = false;
  9986. // has it been destroyed
  9987. this.destroyed = false;
  9988. // should we decode strings into buffers before passing to _write?
  9989. // this is here so that some node-core streams can optimize string
  9990. // handling at a lower level.
  9991. var noDecode = options.decodeStrings === false;
  9992. this.decodeStrings = !noDecode;
  9993. // Crypto is kind of old and crusty. Historically, its default string
  9994. // encoding is 'binary' so we have to make this configurable.
  9995. // Everything else in the universe uses 'utf8', though.
  9996. this.defaultEncoding = options.defaultEncoding || 'utf8';
  9997. // not an actual buffer we keep track of, but a measurement
  9998. // of how much we're waiting to get pushed to some underlying
  9999. // socket or file.
  10000. this.length = 0;
  10001. // a flag to see when we're in the middle of a write.
  10002. this.writing = false;
  10003. // when true all writes will be buffered until .uncork() call
  10004. this.corked = 0;
  10005. // a flag to be able to tell if the onwrite cb is called immediately,
  10006. // or on a later tick. We set this to true at first, because any
  10007. // actions that shouldn't happen until "later" should generally also
  10008. // not happen before the first write call.
  10009. this.sync = true;
  10010. // a flag to know if we're processing previously buffered items, which
  10011. // may call the _write() callback in the same tick, so that we don't
  10012. // end up in an overlapped onwrite situation.
  10013. this.bufferProcessing = false;
  10014. // the callback that's passed to _write(chunk,cb)
  10015. this.onwrite = function (er) {
  10016. onwrite(stream, er);
  10017. };
  10018. // the callback that the user supplies to write(chunk,encoding,cb)
  10019. this.writecb = null;
  10020. // the amount that is being written when _write is called.
  10021. this.writelen = 0;
  10022. this.bufferedRequest = null;
  10023. this.lastBufferedRequest = null;
  10024. // number of pending user-supplied write callbacks
  10025. // this must be 0 before 'finish' can be emitted
  10026. this.pendingcb = 0;
  10027. // emit prefinish if the only thing we're waiting for is _write cbs
  10028. // This is relevant for synchronous Transform streams
  10029. this.prefinished = false;
  10030. // True if the error was already emitted and should not be thrown again
  10031. this.errorEmitted = false;
  10032. // count buffered requests
  10033. this.bufferedRequestCount = 0;
  10034. // allocate the first CorkedRequest, there is always
  10035. // one allocated and free to use, and we maintain at most two
  10036. this.corkedRequestsFree = new CorkedRequest(this);
  10037. }
  10038. WritableState.prototype.getBuffer = function getBuffer() {
  10039. var current = this.bufferedRequest;
  10040. var out = [];
  10041. while (current) {
  10042. out.push(current);
  10043. current = current.next;
  10044. }
  10045. return out;
  10046. };
  10047. (function () {
  10048. try {
  10049. Object.defineProperty(WritableState.prototype, 'buffer', {
  10050. get: internalUtil.deprecate(function () {
  10051. return this.getBuffer();
  10052. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  10053. });
  10054. } catch (_) {}
  10055. })();
  10056. // Test _writableState for inheritance to account for Duplex streams,
  10057. // whose prototype chain only points to Readable.
  10058. var realHasInstance;
  10059. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  10060. realHasInstance = Function.prototype[Symbol.hasInstance];
  10061. Object.defineProperty(Writable, Symbol.hasInstance, {
  10062. value: function (object) {
  10063. if (realHasInstance.call(this, object)) return true;
  10064. if (this !== Writable) return false;
  10065. return object && object._writableState instanceof WritableState;
  10066. }
  10067. });
  10068. } else {
  10069. realHasInstance = function (object) {
  10070. return object instanceof this;
  10071. };
  10072. }
  10073. function Writable(options) {
  10074. Duplex = Duplex || require('./_stream_duplex');
  10075. // Writable ctor is applied to Duplexes, too.
  10076. // `realHasInstance` is necessary because using plain `instanceof`
  10077. // would return false, as no `_writableState` property is attached.
  10078. // Trying to use the custom `instanceof` for Writable here will also break the
  10079. // Node.js LazyTransform implementation, which has a non-trivial getter for
  10080. // `_writableState` that would lead to infinite recursion.
  10081. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  10082. return new Writable(options);
  10083. }
  10084. this._writableState = new WritableState(options, this);
  10085. // legacy.
  10086. this.writable = true;
  10087. if (options) {
  10088. if (typeof options.write === 'function') this._write = options.write;
  10089. if (typeof options.writev === 'function') this._writev = options.writev;
  10090. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  10091. if (typeof options.final === 'function') this._final = options.final;
  10092. }
  10093. Stream.call(this);
  10094. }
  10095. // Otherwise people can pipe Writable streams, which is just wrong.
  10096. Writable.prototype.pipe = function () {
  10097. this.emit('error', new Error('Cannot pipe, not readable'));
  10098. };
  10099. function writeAfterEnd(stream, cb) {
  10100. var er = new Error('write after end');
  10101. // TODO: defer error events consistently everywhere, not just the cb
  10102. stream.emit('error', er);
  10103. pna.nextTick(cb, er);
  10104. }
  10105. // Checks that a user-supplied chunk is valid, especially for the particular
  10106. // mode the stream is in. Currently this means that `null` is never accepted
  10107. // and undefined/non-string values are only allowed in object mode.
  10108. function validChunk(stream, state, chunk, cb) {
  10109. var valid = true;
  10110. var er = false;
  10111. if (chunk === null) {
  10112. er = new TypeError('May not write null values to stream');
  10113. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  10114. er = new TypeError('Invalid non-string/buffer chunk');
  10115. }
  10116. if (er) {
  10117. stream.emit('error', er);
  10118. pna.nextTick(cb, er);
  10119. valid = false;
  10120. }
  10121. return valid;
  10122. }
  10123. Writable.prototype.write = function (chunk, encoding, cb) {
  10124. var state = this._writableState;
  10125. var ret = false;
  10126. var isBuf = !state.objectMode && _isUint8Array(chunk);
  10127. if (isBuf && !Buffer.isBuffer(chunk)) {
  10128. chunk = _uint8ArrayToBuffer(chunk);
  10129. }
  10130. if (typeof encoding === 'function') {
  10131. cb = encoding;
  10132. encoding = null;
  10133. }
  10134. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  10135. if (typeof cb !== 'function') cb = nop;
  10136. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  10137. state.pendingcb++;
  10138. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  10139. }
  10140. return ret;
  10141. };
  10142. Writable.prototype.cork = function () {
  10143. var state = this._writableState;
  10144. state.corked++;
  10145. };
  10146. Writable.prototype.uncork = function () {
  10147. var state = this._writableState;
  10148. if (state.corked) {
  10149. state.corked--;
  10150. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  10151. }
  10152. };
  10153. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  10154. // node::ParseEncoding() requires lower case.
  10155. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  10156. 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);
  10157. this._writableState.defaultEncoding = encoding;
  10158. return this;
  10159. };
  10160. function decodeChunk(state, chunk, encoding) {
  10161. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  10162. chunk = Buffer.from(chunk, encoding);
  10163. }
  10164. return chunk;
  10165. }
  10166. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  10167. // making it explicit this property is not enumerable
  10168. // because otherwise some prototype manipulation in
  10169. // userland will fail
  10170. enumerable: false,
  10171. get: function () {
  10172. return this._writableState.highWaterMark;
  10173. }
  10174. });
  10175. // if we're already writing something, then just put this
  10176. // in the queue, and wait our turn. Otherwise, call _write
  10177. // If we return false, then we need a drain event, so set that flag.
  10178. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  10179. if (!isBuf) {
  10180. var newChunk = decodeChunk(state, chunk, encoding);
  10181. if (chunk !== newChunk) {
  10182. isBuf = true;
  10183. encoding = 'buffer';
  10184. chunk = newChunk;
  10185. }
  10186. }
  10187. var len = state.objectMode ? 1 : chunk.length;
  10188. state.length += len;
  10189. var ret = state.length < state.highWaterMark;
  10190. // we must ensure that previous needDrain will not be reset to false.
  10191. if (!ret) state.needDrain = true;
  10192. if (state.writing || state.corked) {
  10193. var last = state.lastBufferedRequest;
  10194. state.lastBufferedRequest = {
  10195. chunk: chunk,
  10196. encoding: encoding,
  10197. isBuf: isBuf,
  10198. callback: cb,
  10199. next: null
  10200. };
  10201. if (last) {
  10202. last.next = state.lastBufferedRequest;
  10203. } else {
  10204. state.bufferedRequest = state.lastBufferedRequest;
  10205. }
  10206. state.bufferedRequestCount += 1;
  10207. } else {
  10208. doWrite(stream, state, false, len, chunk, encoding, cb);
  10209. }
  10210. return ret;
  10211. }
  10212. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  10213. state.writelen = len;
  10214. state.writecb = cb;
  10215. state.writing = true;
  10216. state.sync = true;
  10217. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  10218. state.sync = false;
  10219. }
  10220. function onwriteError(stream, state, sync, er, cb) {
  10221. --state.pendingcb;
  10222. if (sync) {
  10223. // defer the callback if we are being called synchronously
  10224. // to avoid piling up things on the stack
  10225. pna.nextTick(cb, er);
  10226. // this can emit finish, and it will always happen
  10227. // after error
  10228. pna.nextTick(finishMaybe, stream, state);
  10229. stream._writableState.errorEmitted = true;
  10230. stream.emit('error', er);
  10231. } else {
  10232. // the caller expect this to happen before if
  10233. // it is async
  10234. cb(er);
  10235. stream._writableState.errorEmitted = true;
  10236. stream.emit('error', er);
  10237. // this can emit finish, but finish must
  10238. // always follow error
  10239. finishMaybe(stream, state);
  10240. }
  10241. }
  10242. function onwriteStateUpdate(state) {
  10243. state.writing = false;
  10244. state.writecb = null;
  10245. state.length -= state.writelen;
  10246. state.writelen = 0;
  10247. }
  10248. function onwrite(stream, er) {
  10249. var state = stream._writableState;
  10250. var sync = state.sync;
  10251. var cb = state.writecb;
  10252. onwriteStateUpdate(state);
  10253. if (er) onwriteError(stream, state, sync, er, cb);else {
  10254. // Check if we're actually ready to finish, but don't emit yet
  10255. var finished = needFinish(state);
  10256. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  10257. clearBuffer(stream, state);
  10258. }
  10259. if (sync) {
  10260. /*<replacement>*/
  10261. asyncWrite(afterWrite, stream, state, finished, cb);
  10262. /*</replacement>*/
  10263. } else {
  10264. afterWrite(stream, state, finished, cb);
  10265. }
  10266. }
  10267. }
  10268. function afterWrite(stream, state, finished, cb) {
  10269. if (!finished) onwriteDrain(stream, state);
  10270. state.pendingcb--;
  10271. cb();
  10272. finishMaybe(stream, state);
  10273. }
  10274. // Must force callback to be called on nextTick, so that we don't
  10275. // emit 'drain' before the write() consumer gets the 'false' return
  10276. // value, and has a chance to attach a 'drain' listener.
  10277. function onwriteDrain(stream, state) {
  10278. if (state.length === 0 && state.needDrain) {
  10279. state.needDrain = false;
  10280. stream.emit('drain');
  10281. }
  10282. }
  10283. // if there's something in the buffer waiting, then process it
  10284. function clearBuffer(stream, state) {
  10285. state.bufferProcessing = true;
  10286. var entry = state.bufferedRequest;
  10287. if (stream._writev && entry && entry.next) {
  10288. // Fast case, write everything using _writev()
  10289. var l = state.bufferedRequestCount;
  10290. var buffer = new Array(l);
  10291. var holder = state.corkedRequestsFree;
  10292. holder.entry = entry;
  10293. var count = 0;
  10294. var allBuffers = true;
  10295. while (entry) {
  10296. buffer[count] = entry;
  10297. if (!entry.isBuf) allBuffers = false;
  10298. entry = entry.next;
  10299. count += 1;
  10300. }
  10301. buffer.allBuffers = allBuffers;
  10302. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  10303. // doWrite is almost always async, defer these to save a bit of time
  10304. // as the hot path ends with doWrite
  10305. state.pendingcb++;
  10306. state.lastBufferedRequest = null;
  10307. if (holder.next) {
  10308. state.corkedRequestsFree = holder.next;
  10309. holder.next = null;
  10310. } else {
  10311. state.corkedRequestsFree = new CorkedRequest(state);
  10312. }
  10313. state.bufferedRequestCount = 0;
  10314. } else {
  10315. // Slow case, write chunks one-by-one
  10316. while (entry) {
  10317. var chunk = entry.chunk;
  10318. var encoding = entry.encoding;
  10319. var cb = entry.callback;
  10320. var len = state.objectMode ? 1 : chunk.length;
  10321. doWrite(stream, state, false, len, chunk, encoding, cb);
  10322. entry = entry.next;
  10323. state.bufferedRequestCount--;
  10324. // if we didn't call the onwrite immediately, then
  10325. // it means that we need to wait until it does.
  10326. // also, that means that the chunk and cb are currently
  10327. // being processed, so move the buffer counter past them.
  10328. if (state.writing) {
  10329. break;
  10330. }
  10331. }
  10332. if (entry === null) state.lastBufferedRequest = null;
  10333. }
  10334. state.bufferedRequest = entry;
  10335. state.bufferProcessing = false;
  10336. }
  10337. Writable.prototype._write = function (chunk, encoding, cb) {
  10338. cb(new Error('_write() is not implemented'));
  10339. };
  10340. Writable.prototype._writev = null;
  10341. Writable.prototype.end = function (chunk, encoding, cb) {
  10342. var state = this._writableState;
  10343. if (typeof chunk === 'function') {
  10344. cb = chunk;
  10345. chunk = null;
  10346. encoding = null;
  10347. } else if (typeof encoding === 'function') {
  10348. cb = encoding;
  10349. encoding = null;
  10350. }
  10351. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  10352. // .end() fully uncorks
  10353. if (state.corked) {
  10354. state.corked = 1;
  10355. this.uncork();
  10356. }
  10357. // ignore unnecessary end() calls.
  10358. if (!state.ending && !state.finished) endWritable(this, state, cb);
  10359. };
  10360. function needFinish(state) {
  10361. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  10362. }
  10363. function callFinal(stream, state) {
  10364. stream._final(function (err) {
  10365. state.pendingcb--;
  10366. if (err) {
  10367. stream.emit('error', err);
  10368. }
  10369. state.prefinished = true;
  10370. stream.emit('prefinish');
  10371. finishMaybe(stream, state);
  10372. });
  10373. }
  10374. function prefinish(stream, state) {
  10375. if (!state.prefinished && !state.finalCalled) {
  10376. if (typeof stream._final === 'function') {
  10377. state.pendingcb++;
  10378. state.finalCalled = true;
  10379. pna.nextTick(callFinal, stream, state);
  10380. } else {
  10381. state.prefinished = true;
  10382. stream.emit('prefinish');
  10383. }
  10384. }
  10385. }
  10386. function finishMaybe(stream, state) {
  10387. var need = needFinish(state);
  10388. if (need) {
  10389. prefinish(stream, state);
  10390. if (state.pendingcb === 0) {
  10391. state.finished = true;
  10392. stream.emit('finish');
  10393. }
  10394. }
  10395. return need;
  10396. }
  10397. function endWritable(stream, state, cb) {
  10398. state.ending = true;
  10399. finishMaybe(stream, state);
  10400. if (cb) {
  10401. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  10402. }
  10403. state.ended = true;
  10404. stream.writable = false;
  10405. }
  10406. function onCorkedFinish(corkReq, state, err) {
  10407. var entry = corkReq.entry;
  10408. corkReq.entry = null;
  10409. while (entry) {
  10410. var cb = entry.callback;
  10411. state.pendingcb--;
  10412. cb(err);
  10413. entry = entry.next;
  10414. }
  10415. if (state.corkedRequestsFree) {
  10416. state.corkedRequestsFree.next = corkReq;
  10417. } else {
  10418. state.corkedRequestsFree = corkReq;
  10419. }
  10420. }
  10421. Object.defineProperty(Writable.prototype, 'destroyed', {
  10422. get: function () {
  10423. if (this._writableState === undefined) {
  10424. return false;
  10425. }
  10426. return this._writableState.destroyed;
  10427. },
  10428. set: function (value) {
  10429. // we ignore the value if the stream
  10430. // has not been initialized yet
  10431. if (!this._writableState) {
  10432. return;
  10433. }
  10434. // backward compatibility, the user is explicitly
  10435. // managing destroyed
  10436. this._writableState.destroyed = value;
  10437. }
  10438. });
  10439. Writable.prototype.destroy = destroyImpl.destroy;
  10440. Writable.prototype._undestroy = destroyImpl.undestroy;
  10441. Writable.prototype._destroy = function (err, cb) {
  10442. this.end();
  10443. cb(err);
  10444. };
  10445. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  10446. },{"./_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){
  10447. 'use strict';
  10448. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10449. var Buffer = require('safe-buffer').Buffer;
  10450. var util = require('util');
  10451. function copyBuffer(src, target, offset) {
  10452. src.copy(target, offset);
  10453. }
  10454. module.exports = function () {
  10455. function BufferList() {
  10456. _classCallCheck(this, BufferList);
  10457. this.head = null;
  10458. this.tail = null;
  10459. this.length = 0;
  10460. }
  10461. BufferList.prototype.push = function push(v) {
  10462. var entry = { data: v, next: null };
  10463. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  10464. this.tail = entry;
  10465. ++this.length;
  10466. };
  10467. BufferList.prototype.unshift = function unshift(v) {
  10468. var entry = { data: v, next: this.head };
  10469. if (this.length === 0) this.tail = entry;
  10470. this.head = entry;
  10471. ++this.length;
  10472. };
  10473. BufferList.prototype.shift = function shift() {
  10474. if (this.length === 0) return;
  10475. var ret = this.head.data;
  10476. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  10477. --this.length;
  10478. return ret;
  10479. };
  10480. BufferList.prototype.clear = function clear() {
  10481. this.head = this.tail = null;
  10482. this.length = 0;
  10483. };
  10484. BufferList.prototype.join = function join(s) {
  10485. if (this.length === 0) return '';
  10486. var p = this.head;
  10487. var ret = '' + p.data;
  10488. while (p = p.next) {
  10489. ret += s + p.data;
  10490. }return ret;
  10491. };
  10492. BufferList.prototype.concat = function concat(n) {
  10493. if (this.length === 0) return Buffer.alloc(0);
  10494. if (this.length === 1) return this.head.data;
  10495. var ret = Buffer.allocUnsafe(n >>> 0);
  10496. var p = this.head;
  10497. var i = 0;
  10498. while (p) {
  10499. copyBuffer(p.data, ret, i);
  10500. i += p.data.length;
  10501. p = p.next;
  10502. }
  10503. return ret;
  10504. };
  10505. return BufferList;
  10506. }();
  10507. if (util && util.inspect && util.inspect.custom) {
  10508. module.exports.prototype[util.inspect.custom] = function () {
  10509. var obj = util.inspect({ length: this.length });
  10510. return this.constructor.name + ' ' + obj;
  10511. };
  10512. }
  10513. },{"safe-buffer":110,"util":11}],104:[function(require,module,exports){
  10514. 'use strict';
  10515. /*<replacement>*/
  10516. var pna = require('process-nextick-args');
  10517. /*</replacement>*/
  10518. // undocumented cb() API, needed for core, not for public API
  10519. function destroy(err, cb) {
  10520. var _this = this;
  10521. var readableDestroyed = this._readableState && this._readableState.destroyed;
  10522. var writableDestroyed = this._writableState && this._writableState.destroyed;
  10523. if (readableDestroyed || writableDestroyed) {
  10524. if (cb) {
  10525. cb(err);
  10526. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  10527. pna.nextTick(emitErrorNT, this, err);
  10528. }
  10529. return this;
  10530. }
  10531. // we set destroyed to true before firing error callbacks in order
  10532. // to make it re-entrance safe in case destroy() is called within callbacks
  10533. if (this._readableState) {
  10534. this._readableState.destroyed = true;
  10535. }
  10536. // if this is a duplex stream mark the writable part as destroyed as well
  10537. if (this._writableState) {
  10538. this._writableState.destroyed = true;
  10539. }
  10540. this._destroy(err || null, function (err) {
  10541. if (!cb && err) {
  10542. pna.nextTick(emitErrorNT, _this, err);
  10543. if (_this._writableState) {
  10544. _this._writableState.errorEmitted = true;
  10545. }
  10546. } else if (cb) {
  10547. cb(err);
  10548. }
  10549. });
  10550. return this;
  10551. }
  10552. function undestroy() {
  10553. if (this._readableState) {
  10554. this._readableState.destroyed = false;
  10555. this._readableState.reading = false;
  10556. this._readableState.ended = false;
  10557. this._readableState.endEmitted = false;
  10558. }
  10559. if (this._writableState) {
  10560. this._writableState.destroyed = false;
  10561. this._writableState.ended = false;
  10562. this._writableState.ending = false;
  10563. this._writableState.finished = false;
  10564. this._writableState.errorEmitted = false;
  10565. }
  10566. }
  10567. function emitErrorNT(self, err) {
  10568. self.emit('error', err);
  10569. }
  10570. module.exports = {
  10571. destroy: destroy,
  10572. undestroy: undestroy
  10573. };
  10574. },{"process-nextick-args":91}],105:[function(require,module,exports){
  10575. module.exports = require('events').EventEmitter;
  10576. },{"events":13}],106:[function(require,module,exports){
  10577. var toString = {}.toString;
  10578. module.exports = Array.isArray || function (arr) {
  10579. return toString.call(arr) == '[object Array]';
  10580. };
  10581. },{}],107:[function(require,module,exports){
  10582. // Copyright Joyent, Inc. and other Node contributors.
  10583. //
  10584. // Permission is hereby granted, free of charge, to any person obtaining a
  10585. // copy of this software and associated documentation files (the
  10586. // "Software"), to deal in the Software without restriction, including
  10587. // without limitation the rights to use, copy, modify, merge, publish,
  10588. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10589. // persons to whom the Software is furnished to do so, subject to the
  10590. // following conditions:
  10591. //
  10592. // The above copyright notice and this permission notice shall be included
  10593. // in all copies or substantial portions of the Software.
  10594. //
  10595. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10596. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10597. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10598. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10599. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10600. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10601. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10602. 'use strict';
  10603. /*<replacement>*/
  10604. var Buffer = require('safe-buffer').Buffer;
  10605. /*</replacement>*/
  10606. var isEncoding = Buffer.isEncoding || function (encoding) {
  10607. encoding = '' + encoding;
  10608. switch (encoding && encoding.toLowerCase()) {
  10609. 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':
  10610. return true;
  10611. default:
  10612. return false;
  10613. }
  10614. };
  10615. function _normalizeEncoding(enc) {
  10616. if (!enc) return 'utf8';
  10617. var retried;
  10618. while (true) {
  10619. switch (enc) {
  10620. case 'utf8':
  10621. case 'utf-8':
  10622. return 'utf8';
  10623. case 'ucs2':
  10624. case 'ucs-2':
  10625. case 'utf16le':
  10626. case 'utf-16le':
  10627. return 'utf16le';
  10628. case 'latin1':
  10629. case 'binary':
  10630. return 'latin1';
  10631. case 'base64':
  10632. case 'ascii':
  10633. case 'hex':
  10634. return enc;
  10635. default:
  10636. if (retried) return; // undefined
  10637. enc = ('' + enc).toLowerCase();
  10638. retried = true;
  10639. }
  10640. }
  10641. };
  10642. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  10643. // modules monkey-patch it to support additional encodings
  10644. function normalizeEncoding(enc) {
  10645. var nenc = _normalizeEncoding(enc);
  10646. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  10647. return nenc || enc;
  10648. }
  10649. // StringDecoder provides an interface for efficiently splitting a series of
  10650. // buffers into a series of JS strings without breaking apart multi-byte
  10651. // characters.
  10652. exports.StringDecoder = StringDecoder;
  10653. function StringDecoder(encoding) {
  10654. this.encoding = normalizeEncoding(encoding);
  10655. var nb;
  10656. switch (this.encoding) {
  10657. case 'utf16le':
  10658. this.text = utf16Text;
  10659. this.end = utf16End;
  10660. nb = 4;
  10661. break;
  10662. case 'utf8':
  10663. this.fillLast = utf8FillLast;
  10664. nb = 4;
  10665. break;
  10666. case 'base64':
  10667. this.text = base64Text;
  10668. this.end = base64End;
  10669. nb = 3;
  10670. break;
  10671. default:
  10672. this.write = simpleWrite;
  10673. this.end = simpleEnd;
  10674. return;
  10675. }
  10676. this.lastNeed = 0;
  10677. this.lastTotal = 0;
  10678. this.lastChar = Buffer.allocUnsafe(nb);
  10679. }
  10680. StringDecoder.prototype.write = function (buf) {
  10681. if (buf.length === 0) return '';
  10682. var r;
  10683. var i;
  10684. if (this.lastNeed) {
  10685. r = this.fillLast(buf);
  10686. if (r === undefined) return '';
  10687. i = this.lastNeed;
  10688. this.lastNeed = 0;
  10689. } else {
  10690. i = 0;
  10691. }
  10692. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  10693. return r || '';
  10694. };
  10695. StringDecoder.prototype.end = utf8End;
  10696. // Returns only complete characters in a Buffer
  10697. StringDecoder.prototype.text = utf8Text;
  10698. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  10699. StringDecoder.prototype.fillLast = function (buf) {
  10700. if (this.lastNeed <= buf.length) {
  10701. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  10702. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10703. }
  10704. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  10705. this.lastNeed -= buf.length;
  10706. };
  10707. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  10708. // continuation byte. If an invalid byte is detected, -2 is returned.
  10709. function utf8CheckByte(byte) {
  10710. 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;
  10711. return byte >> 6 === 0x02 ? -1 : -2;
  10712. }
  10713. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  10714. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  10715. // needed to complete the UTF-8 character (if applicable) are returned.
  10716. function utf8CheckIncomplete(self, buf, i) {
  10717. var j = buf.length - 1;
  10718. if (j < i) return 0;
  10719. var nb = utf8CheckByte(buf[j]);
  10720. if (nb >= 0) {
  10721. if (nb > 0) self.lastNeed = nb - 1;
  10722. return nb;
  10723. }
  10724. if (--j < i || nb === -2) return 0;
  10725. nb = utf8CheckByte(buf[j]);
  10726. if (nb >= 0) {
  10727. if (nb > 0) self.lastNeed = nb - 2;
  10728. return nb;
  10729. }
  10730. if (--j < i || nb === -2) return 0;
  10731. nb = utf8CheckByte(buf[j]);
  10732. if (nb >= 0) {
  10733. if (nb > 0) {
  10734. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  10735. }
  10736. return nb;
  10737. }
  10738. return 0;
  10739. }
  10740. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  10741. // needed or are available. If we see a non-continuation byte where we expect
  10742. // one, we "replace" the validated continuation bytes we've seen so far with
  10743. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  10744. // behavior. The continuation byte check is included three times in the case
  10745. // where all of the continuation bytes for a character exist in the same buffer.
  10746. // It is also done this way as a slight performance increase instead of using a
  10747. // loop.
  10748. function utf8CheckExtraBytes(self, buf, p) {
  10749. if ((buf[0] & 0xC0) !== 0x80) {
  10750. self.lastNeed = 0;
  10751. return '\ufffd';
  10752. }
  10753. if (self.lastNeed > 1 && buf.length > 1) {
  10754. if ((buf[1] & 0xC0) !== 0x80) {
  10755. self.lastNeed = 1;
  10756. return '\ufffd';
  10757. }
  10758. if (self.lastNeed > 2 && buf.length > 2) {
  10759. if ((buf[2] & 0xC0) !== 0x80) {
  10760. self.lastNeed = 2;
  10761. return '\ufffd';
  10762. }
  10763. }
  10764. }
  10765. }
  10766. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  10767. function utf8FillLast(buf) {
  10768. var p = this.lastTotal - this.lastNeed;
  10769. var r = utf8CheckExtraBytes(this, buf, p);
  10770. if (r !== undefined) return r;
  10771. if (this.lastNeed <= buf.length) {
  10772. buf.copy(this.lastChar, p, 0, this.lastNeed);
  10773. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10774. }
  10775. buf.copy(this.lastChar, p, 0, buf.length);
  10776. this.lastNeed -= buf.length;
  10777. }
  10778. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  10779. // partial character, the character's bytes are buffered until the required
  10780. // number of bytes are available.
  10781. function utf8Text(buf, i) {
  10782. var total = utf8CheckIncomplete(this, buf, i);
  10783. if (!this.lastNeed) return buf.toString('utf8', i);
  10784. this.lastTotal = total;
  10785. var end = buf.length - (total - this.lastNeed);
  10786. buf.copy(this.lastChar, 0, end);
  10787. return buf.toString('utf8', i, end);
  10788. }
  10789. // For UTF-8, a replacement character is added when ending on a partial
  10790. // character.
  10791. function utf8End(buf) {
  10792. var r = buf && buf.length ? this.write(buf) : '';
  10793. if (this.lastNeed) return r + '\ufffd';
  10794. return r;
  10795. }
  10796. // UTF-16LE typically needs two bytes per character, but even if we have an even
  10797. // number of bytes available, we need to check if we end on a leading/high
  10798. // surrogate. In that case, we need to wait for the next two bytes in order to
  10799. // decode the last character properly.
  10800. function utf16Text(buf, i) {
  10801. if ((buf.length - i) % 2 === 0) {
  10802. var r = buf.toString('utf16le', i);
  10803. if (r) {
  10804. var c = r.charCodeAt(r.length - 1);
  10805. if (c >= 0xD800 && c <= 0xDBFF) {
  10806. this.lastNeed = 2;
  10807. this.lastTotal = 4;
  10808. this.lastChar[0] = buf[buf.length - 2];
  10809. this.lastChar[1] = buf[buf.length - 1];
  10810. return r.slice(0, -1);
  10811. }
  10812. }
  10813. return r;
  10814. }
  10815. this.lastNeed = 1;
  10816. this.lastTotal = 2;
  10817. this.lastChar[0] = buf[buf.length - 1];
  10818. return buf.toString('utf16le', i, buf.length - 1);
  10819. }
  10820. // For UTF-16LE we do not explicitly append special replacement characters if we
  10821. // end on a partial character, we simply let v8 handle that.
  10822. function utf16End(buf) {
  10823. var r = buf && buf.length ? this.write(buf) : '';
  10824. if (this.lastNeed) {
  10825. var end = this.lastTotal - this.lastNeed;
  10826. return r + this.lastChar.toString('utf16le', 0, end);
  10827. }
  10828. return r;
  10829. }
  10830. function base64Text(buf, i) {
  10831. var n = (buf.length - i) % 3;
  10832. if (n === 0) return buf.toString('base64', i);
  10833. this.lastNeed = 3 - n;
  10834. this.lastTotal = 3;
  10835. if (n === 1) {
  10836. this.lastChar[0] = buf[buf.length - 1];
  10837. } else {
  10838. this.lastChar[0] = buf[buf.length - 2];
  10839. this.lastChar[1] = buf[buf.length - 1];
  10840. }
  10841. return buf.toString('base64', i, buf.length - n);
  10842. }
  10843. function base64End(buf) {
  10844. var r = buf && buf.length ? this.write(buf) : '';
  10845. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  10846. return r;
  10847. }
  10848. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  10849. function simpleWrite(buf) {
  10850. return buf.toString(this.encoding);
  10851. }
  10852. function simpleEnd(buf) {
  10853. return buf && buf.length ? this.write(buf) : '';
  10854. }
  10855. },{"safe-buffer":110}],108:[function(require,module,exports){
  10856. exports = module.exports = require('./lib/_stream_readable.js');
  10857. exports.Stream = exports;
  10858. exports.Readable = exports;
  10859. exports.Writable = require('./lib/_stream_writable.js');
  10860. exports.Duplex = require('./lib/_stream_duplex.js');
  10861. exports.Transform = require('./lib/_stream_transform.js');
  10862. exports.PassThrough = require('./lib/_stream_passthrough.js');
  10863. },{"./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){
  10864. 'use strict'
  10865. function ReInterval (callback, interval, args) {
  10866. var self = this;
  10867. this._callback = callback;
  10868. this._args = args;
  10869. this._interval = setInterval(callback, interval, this._args);
  10870. this.reschedule = function (interval) {
  10871. // if no interval entered, use the interval passed in on creation
  10872. if (!interval)
  10873. interval = self._interval;
  10874. if (self._interval)
  10875. clearInterval(self._interval);
  10876. self._interval = setInterval(self._callback, interval, self._args);
  10877. };
  10878. this.clear = function () {
  10879. if (self._interval) {
  10880. clearInterval(self._interval);
  10881. self._interval = undefined;
  10882. }
  10883. };
  10884. this.destroy = function () {
  10885. if (self._interval) {
  10886. clearInterval(self._interval);
  10887. }
  10888. self._callback = undefined;
  10889. self._interval = undefined;
  10890. self._args = undefined;
  10891. };
  10892. }
  10893. function reInterval () {
  10894. if (typeof arguments[0] !== 'function')
  10895. throw new Error('callback needed');
  10896. if (typeof arguments[1] !== 'number')
  10897. throw new Error('interval needed');
  10898. var args;
  10899. if (arguments.length > 0) {
  10900. args = new Array(arguments.length - 2);
  10901. for (var i = 0; i < args.length; i++) {
  10902. args[i] = arguments[i + 2];
  10903. }
  10904. }
  10905. return new ReInterval(arguments[0], arguments[1], args);
  10906. }
  10907. module.exports = reInterval;
  10908. },{}],110:[function(require,module,exports){
  10909. /* eslint-disable node/no-deprecated-api */
  10910. var buffer = require('buffer')
  10911. var Buffer = buffer.Buffer
  10912. // alternative to using Object.keys for old browsers
  10913. function copyProps (src, dst) {
  10914. for (var key in src) {
  10915. dst[key] = src[key]
  10916. }
  10917. }
  10918. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  10919. module.exports = buffer
  10920. } else {
  10921. // Copy properties from require('buffer')
  10922. copyProps(buffer, exports)
  10923. exports.Buffer = SafeBuffer
  10924. }
  10925. function SafeBuffer (arg, encodingOrOffset, length) {
  10926. return Buffer(arg, encodingOrOffset, length)
  10927. }
  10928. // Copy static methods from Buffer
  10929. copyProps(Buffer, SafeBuffer)
  10930. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  10931. if (typeof arg === 'number') {
  10932. throw new TypeError('Argument must not be a number')
  10933. }
  10934. return Buffer(arg, encodingOrOffset, length)
  10935. }
  10936. SafeBuffer.alloc = function (size, fill, encoding) {
  10937. if (typeof size !== 'number') {
  10938. throw new TypeError('Argument must be a number')
  10939. }
  10940. var buf = Buffer(size)
  10941. if (fill !== undefined) {
  10942. if (typeof encoding === 'string') {
  10943. buf.fill(fill, encoding)
  10944. } else {
  10945. buf.fill(fill)
  10946. }
  10947. } else {
  10948. buf.fill(0)
  10949. }
  10950. return buf
  10951. }
  10952. SafeBuffer.allocUnsafe = function (size) {
  10953. if (typeof size !== 'number') {
  10954. throw new TypeError('Argument must be a number')
  10955. }
  10956. return Buffer(size)
  10957. }
  10958. SafeBuffer.allocUnsafeSlow = function (size) {
  10959. if (typeof size !== 'number') {
  10960. throw new TypeError('Argument must be a number')
  10961. }
  10962. return buffer.SlowBuffer(size)
  10963. }
  10964. },{"buffer":12}],111:[function(require,module,exports){
  10965. module.exports = shift
  10966. function shift (stream) {
  10967. var rs = stream._readableState
  10968. if (!rs) return null
  10969. return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
  10970. }
  10971. function getStateLength (state) {
  10972. if (state.buffer.length) {
  10973. // Since node 6.3.0 state.buffer is a BufferList not an array
  10974. if (state.buffer.head) {
  10975. return state.buffer.head.data.length
  10976. }
  10977. return state.buffer[0].length
  10978. }
  10979. return state.length
  10980. }
  10981. },{}],112:[function(require,module,exports){
  10982. (function (setImmediate,clearImmediate){
  10983. var nextTick = require('process/browser.js').nextTick;
  10984. var apply = Function.prototype.apply;
  10985. var slice = Array.prototype.slice;
  10986. var immediateIds = {};
  10987. var nextImmediateId = 0;
  10988. // DOM APIs, for completeness
  10989. exports.setTimeout = function() {
  10990. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  10991. };
  10992. exports.setInterval = function() {
  10993. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  10994. };
  10995. exports.clearTimeout =
  10996. exports.clearInterval = function(timeout) { timeout.close(); };
  10997. function Timeout(id, clearFn) {
  10998. this._id = id;
  10999. this._clearFn = clearFn;
  11000. }
  11001. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  11002. Timeout.prototype.close = function() {
  11003. this._clearFn.call(window, this._id);
  11004. };
  11005. // Does not start the time, just sets up the members needed.
  11006. exports.enroll = function(item, msecs) {
  11007. clearTimeout(item._idleTimeoutId);
  11008. item._idleTimeout = msecs;
  11009. };
  11010. exports.unenroll = function(item) {
  11011. clearTimeout(item._idleTimeoutId);
  11012. item._idleTimeout = -1;
  11013. };
  11014. exports._unrefActive = exports.active = function(item) {
  11015. clearTimeout(item._idleTimeoutId);
  11016. var msecs = item._idleTimeout;
  11017. if (msecs >= 0) {
  11018. item._idleTimeoutId = setTimeout(function onTimeout() {
  11019. if (item._onTimeout)
  11020. item._onTimeout();
  11021. }, msecs);
  11022. }
  11023. };
  11024. // That's not how node.js implements it but the exposed api is the same.
  11025. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  11026. var id = nextImmediateId++;
  11027. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  11028. immediateIds[id] = true;
  11029. nextTick(function onNextTick() {
  11030. if (immediateIds[id]) {
  11031. // fn.call() is faster so we optimize for the common use-case
  11032. // @see http://jsperf.com/call-apply-segu
  11033. if (args) {
  11034. fn.apply(null, args);
  11035. } else {
  11036. fn.call(null);
  11037. }
  11038. // Prevent ids from leaking
  11039. exports.clearImmediate(id);
  11040. }
  11041. });
  11042. return id;
  11043. };
  11044. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  11045. delete immediateIds[id];
  11046. };
  11047. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  11048. },{"process/browser.js":92,"timers":112}],113:[function(require,module,exports){
  11049. // Copyright Joyent, Inc. and other Node contributors.
  11050. //
  11051. // Permission is hereby granted, free of charge, to any person obtaining a
  11052. // copy of this software and associated documentation files (the
  11053. // "Software"), to deal in the Software without restriction, including
  11054. // without limitation the rights to use, copy, modify, merge, publish,
  11055. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11056. // persons to whom the Software is furnished to do so, subject to the
  11057. // following conditions:
  11058. //
  11059. // The above copyright notice and this permission notice shall be included
  11060. // in all copies or substantial portions of the Software.
  11061. //
  11062. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11063. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11064. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11065. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11066. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11067. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11068. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11069. 'use strict';
  11070. var punycode = require('punycode');
  11071. var util = require('./util');
  11072. exports.parse = urlParse;
  11073. exports.resolve = urlResolve;
  11074. exports.resolveObject = urlResolveObject;
  11075. exports.format = urlFormat;
  11076. exports.Url = Url;
  11077. function Url() {
  11078. this.protocol = null;
  11079. this.slashes = null;
  11080. this.auth = null;
  11081. this.host = null;
  11082. this.port = null;
  11083. this.hostname = null;
  11084. this.hash = null;
  11085. this.search = null;
  11086. this.query = null;
  11087. this.pathname = null;
  11088. this.path = null;
  11089. this.href = null;
  11090. }
  11091. // Reference: RFC 3986, RFC 1808, RFC 2396
  11092. // define these here so at least they only have to be
  11093. // compiled once on the first module load.
  11094. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  11095. portPattern = /:[0-9]*$/,
  11096. // Special case for a simple path URL
  11097. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  11098. // RFC 2396: characters reserved for delimiting URLs.
  11099. // We actually just auto-escape these.
  11100. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  11101. // RFC 2396: characters not allowed for various reasons.
  11102. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  11103. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  11104. autoEscape = ['\''].concat(unwise),
  11105. // Characters that are never ever allowed in a hostname.
  11106. // Note that any invalid chars are also handled, but these
  11107. // are the ones that are *expected* to be seen, so we fast-path
  11108. // them.
  11109. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  11110. hostEndingChars = ['/', '?', '#'],
  11111. hostnameMaxLen = 255,
  11112. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  11113. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  11114. // protocols that can allow "unsafe" and "unwise" chars.
  11115. unsafeProtocol = {
  11116. 'javascript': true,
  11117. 'javascript:': true
  11118. },
  11119. // protocols that never have a hostname.
  11120. hostlessProtocol = {
  11121. 'javascript': true,
  11122. 'javascript:': true
  11123. },
  11124. // protocols that always contain a // bit.
  11125. slashedProtocol = {
  11126. 'http': true,
  11127. 'https': true,
  11128. 'ftp': true,
  11129. 'gopher': true,
  11130. 'file': true,
  11131. 'http:': true,
  11132. 'https:': true,
  11133. 'ftp:': true,
  11134. 'gopher:': true,
  11135. 'file:': true
  11136. },
  11137. querystring = require('querystring');
  11138. function urlParse(url, parseQueryString, slashesDenoteHost) {
  11139. if (url && util.isObject(url) && url instanceof Url) return url;
  11140. var u = new Url;
  11141. u.parse(url, parseQueryString, slashesDenoteHost);
  11142. return u;
  11143. }
  11144. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  11145. if (!util.isString(url)) {
  11146. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  11147. }
  11148. // Copy chrome, IE, opera backslash-handling behavior.
  11149. // Back slashes before the query string get converted to forward slashes
  11150. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  11151. var queryIndex = url.indexOf('?'),
  11152. splitter =
  11153. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  11154. uSplit = url.split(splitter),
  11155. slashRegex = /\\/g;
  11156. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  11157. url = uSplit.join(splitter);
  11158. var rest = url;
  11159. // trim before proceeding.
  11160. // This is to support parse stuff like " http://foo.com \n"
  11161. rest = rest.trim();
  11162. if (!slashesDenoteHost && url.split('#').length === 1) {
  11163. // Try fast path regexp
  11164. var simplePath = simplePathPattern.exec(rest);
  11165. if (simplePath) {
  11166. this.path = rest;
  11167. this.href = rest;
  11168. this.pathname = simplePath[1];
  11169. if (simplePath[2]) {
  11170. this.search = simplePath[2];
  11171. if (parseQueryString) {
  11172. this.query = querystring.parse(this.search.substr(1));
  11173. } else {
  11174. this.query = this.search.substr(1);
  11175. }
  11176. } else if (parseQueryString) {
  11177. this.search = '';
  11178. this.query = {};
  11179. }
  11180. return this;
  11181. }
  11182. }
  11183. var proto = protocolPattern.exec(rest);
  11184. if (proto) {
  11185. proto = proto[0];
  11186. var lowerProto = proto.toLowerCase();
  11187. this.protocol = lowerProto;
  11188. rest = rest.substr(proto.length);
  11189. }
  11190. // figure out if it's got a host
  11191. // user@server is *always* interpreted as a hostname, and url
  11192. // resolution will treat //foo/bar as host=foo,path=bar because that's
  11193. // how the browser resolves relative URLs.
  11194. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  11195. var slashes = rest.substr(0, 2) === '//';
  11196. if (slashes && !(proto && hostlessProtocol[proto])) {
  11197. rest = rest.substr(2);
  11198. this.slashes = true;
  11199. }
  11200. }
  11201. if (!hostlessProtocol[proto] &&
  11202. (slashes || (proto && !slashedProtocol[proto]))) {
  11203. // there's a hostname.
  11204. // the first instance of /, ?, ;, or # ends the host.
  11205. //
  11206. // If there is an @ in the hostname, then non-host chars *are* allowed
  11207. // to the left of the last @ sign, unless some host-ending character
  11208. // comes *before* the @-sign.
  11209. // URLs are obnoxious.
  11210. //
  11211. // ex:
  11212. // http://a@b@c/ => user:a@b host:c
  11213. // http://a@b?@c => user:a host:c path:/?@c
  11214. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  11215. // Review our test case against browsers more comprehensively.
  11216. // find the first instance of any hostEndingChars
  11217. var hostEnd = -1;
  11218. for (var i = 0; i < hostEndingChars.length; i++) {
  11219. var hec = rest.indexOf(hostEndingChars[i]);
  11220. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  11221. hostEnd = hec;
  11222. }
  11223. // at this point, either we have an explicit point where the
  11224. // auth portion cannot go past, or the last @ char is the decider.
  11225. var auth, atSign;
  11226. if (hostEnd === -1) {
  11227. // atSign can be anywhere.
  11228. atSign = rest.lastIndexOf('@');
  11229. } else {
  11230. // atSign must be in auth portion.
  11231. // http://a@b/c@d => host:b auth:a path:/c@d
  11232. atSign = rest.lastIndexOf('@', hostEnd);
  11233. }
  11234. // Now we have a portion which is definitely the auth.
  11235. // Pull that off.
  11236. if (atSign !== -1) {
  11237. auth = rest.slice(0, atSign);
  11238. rest = rest.slice(atSign + 1);
  11239. this.auth = decodeURIComponent(auth);
  11240. }
  11241. // the host is the remaining to the left of the first non-host char
  11242. hostEnd = -1;
  11243. for (var i = 0; i < nonHostChars.length; i++) {
  11244. var hec = rest.indexOf(nonHostChars[i]);
  11245. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  11246. hostEnd = hec;
  11247. }
  11248. // if we still have not hit it, then the entire thing is a host.
  11249. if (hostEnd === -1)
  11250. hostEnd = rest.length;
  11251. this.host = rest.slice(0, hostEnd);
  11252. rest = rest.slice(hostEnd);
  11253. // pull out port.
  11254. this.parseHost();
  11255. // we've indicated that there is a hostname,
  11256. // so even if it's empty, it has to be present.
  11257. this.hostname = this.hostname || '';
  11258. // if hostname begins with [ and ends with ]
  11259. // assume that it's an IPv6 address.
  11260. var ipv6Hostname = this.hostname[0] === '[' &&
  11261. this.hostname[this.hostname.length - 1] === ']';
  11262. // validate a little.
  11263. if (!ipv6Hostname) {
  11264. var hostparts = this.hostname.split(/\./);
  11265. for (var i = 0, l = hostparts.length; i < l; i++) {
  11266. var part = hostparts[i];
  11267. if (!part) continue;
  11268. if (!part.match(hostnamePartPattern)) {
  11269. var newpart = '';
  11270. for (var j = 0, k = part.length; j < k; j++) {
  11271. if (part.charCodeAt(j) > 127) {
  11272. // we replace non-ASCII char with a temporary placeholder
  11273. // we need this to make sure size of hostname is not
  11274. // broken by replacing non-ASCII by nothing
  11275. newpart += 'x';
  11276. } else {
  11277. newpart += part[j];
  11278. }
  11279. }
  11280. // we test again with ASCII char only
  11281. if (!newpart.match(hostnamePartPattern)) {
  11282. var validParts = hostparts.slice(0, i);
  11283. var notHost = hostparts.slice(i + 1);
  11284. var bit = part.match(hostnamePartStart);
  11285. if (bit) {
  11286. validParts.push(bit[1]);
  11287. notHost.unshift(bit[2]);
  11288. }
  11289. if (notHost.length) {
  11290. rest = '/' + notHost.join('.') + rest;
  11291. }
  11292. this.hostname = validParts.join('.');
  11293. break;
  11294. }
  11295. }
  11296. }
  11297. }
  11298. if (this.hostname.length > hostnameMaxLen) {
  11299. this.hostname = '';
  11300. } else {
  11301. // hostnames are always lower case.
  11302. this.hostname = this.hostname.toLowerCase();
  11303. }
  11304. if (!ipv6Hostname) {
  11305. // IDNA Support: Returns a punycoded representation of "domain".
  11306. // It only converts parts of the domain name that
  11307. // have non-ASCII characters, i.e. it doesn't matter if
  11308. // you call it with a domain that already is ASCII-only.
  11309. this.hostname = punycode.toASCII(this.hostname);
  11310. }
  11311. var p = this.port ? ':' + this.port : '';
  11312. var h = this.hostname || '';
  11313. this.host = h + p;
  11314. this.href += this.host;
  11315. // strip [ and ] from the hostname
  11316. // the host field still retains them, though
  11317. if (ipv6Hostname) {
  11318. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  11319. if (rest[0] !== '/') {
  11320. rest = '/' + rest;
  11321. }
  11322. }
  11323. }
  11324. // now rest is set to the post-host stuff.
  11325. // chop off any delim chars.
  11326. if (!unsafeProtocol[lowerProto]) {
  11327. // First, make 100% sure that any "autoEscape" chars get
  11328. // escaped, even if encodeURIComponent doesn't think they
  11329. // need to be.
  11330. for (var i = 0, l = autoEscape.length; i < l; i++) {
  11331. var ae = autoEscape[i];
  11332. if (rest.indexOf(ae) === -1)
  11333. continue;
  11334. var esc = encodeURIComponent(ae);
  11335. if (esc === ae) {
  11336. esc = escape(ae);
  11337. }
  11338. rest = rest.split(ae).join(esc);
  11339. }
  11340. }
  11341. // chop off from the tail first.
  11342. var hash = rest.indexOf('#');
  11343. if (hash !== -1) {
  11344. // got a fragment string.
  11345. this.hash = rest.substr(hash);
  11346. rest = rest.slice(0, hash);
  11347. }
  11348. var qm = rest.indexOf('?');
  11349. if (qm !== -1) {
  11350. this.search = rest.substr(qm);
  11351. this.query = rest.substr(qm + 1);
  11352. if (parseQueryString) {
  11353. this.query = querystring.parse(this.query);
  11354. }
  11355. rest = rest.slice(0, qm);
  11356. } else if (parseQueryString) {
  11357. // no query string, but parseQueryString still requested
  11358. this.search = '';
  11359. this.query = {};
  11360. }
  11361. if (rest) this.pathname = rest;
  11362. if (slashedProtocol[lowerProto] &&
  11363. this.hostname && !this.pathname) {
  11364. this.pathname = '/';
  11365. }
  11366. //to support http.request
  11367. if (this.pathname || this.search) {
  11368. var p = this.pathname || '';
  11369. var s = this.search || '';
  11370. this.path = p + s;
  11371. }
  11372. // finally, reconstruct the href based on what has been validated.
  11373. this.href = this.format();
  11374. return this;
  11375. };
  11376. // format a parsed object into a url string
  11377. function urlFormat(obj) {
  11378. // ensure it's an object, and not a string url.
  11379. // If it's an obj, this is a no-op.
  11380. // this way, you can call url_format() on strings
  11381. // to clean up potentially wonky urls.
  11382. if (util.isString(obj)) obj = urlParse(obj);
  11383. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  11384. return obj.format();
  11385. }
  11386. Url.prototype.format = function() {
  11387. var auth = this.auth || '';
  11388. if (auth) {
  11389. auth = encodeURIComponent(auth);
  11390. auth = auth.replace(/%3A/i, ':');
  11391. auth += '@';
  11392. }
  11393. var protocol = this.protocol || '',
  11394. pathname = this.pathname || '',
  11395. hash = this.hash || '',
  11396. host = false,
  11397. query = '';
  11398. if (this.host) {
  11399. host = auth + this.host;
  11400. } else if (this.hostname) {
  11401. host = auth + (this.hostname.indexOf(':') === -1 ?
  11402. this.hostname :
  11403. '[' + this.hostname + ']');
  11404. if (this.port) {
  11405. host += ':' + this.port;
  11406. }
  11407. }
  11408. if (this.query &&
  11409. util.isObject(this.query) &&
  11410. Object.keys(this.query).length) {
  11411. query = querystring.stringify(this.query);
  11412. }
  11413. var search = this.search || (query && ('?' + query)) || '';
  11414. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  11415. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  11416. // unless they had them to begin with.
  11417. if (this.slashes ||
  11418. (!protocol || slashedProtocol[protocol]) && host !== false) {
  11419. host = '//' + (host || '');
  11420. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  11421. } else if (!host) {
  11422. host = '';
  11423. }
  11424. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  11425. if (search && search.charAt(0) !== '?') search = '?' + search;
  11426. pathname = pathname.replace(/[?#]/g, function(match) {
  11427. return encodeURIComponent(match);
  11428. });
  11429. search = search.replace('#', '%23');
  11430. return protocol + host + pathname + search + hash;
  11431. };
  11432. function urlResolve(source, relative) {
  11433. return urlParse(source, false, true).resolve(relative);
  11434. }
  11435. Url.prototype.resolve = function(relative) {
  11436. return this.resolveObject(urlParse(relative, false, true)).format();
  11437. };
  11438. function urlResolveObject(source, relative) {
  11439. if (!source) return relative;
  11440. return urlParse(source, false, true).resolveObject(relative);
  11441. }
  11442. Url.prototype.resolveObject = function(relative) {
  11443. if (util.isString(relative)) {
  11444. var rel = new Url();
  11445. rel.parse(relative, false, true);
  11446. relative = rel;
  11447. }
  11448. var result = new Url();
  11449. var tkeys = Object.keys(this);
  11450. for (var tk = 0; tk < tkeys.length; tk++) {
  11451. var tkey = tkeys[tk];
  11452. result[tkey] = this[tkey];
  11453. }
  11454. // hash is always overridden, no matter what.
  11455. // even href="" will remove it.
  11456. result.hash = relative.hash;
  11457. // if the relative url is empty, then there's nothing left to do here.
  11458. if (relative.href === '') {
  11459. result.href = result.format();
  11460. return result;
  11461. }
  11462. // hrefs like //foo/bar always cut to the protocol.
  11463. if (relative.slashes && !relative.protocol) {
  11464. // take everything except the protocol from relative
  11465. var rkeys = Object.keys(relative);
  11466. for (var rk = 0; rk < rkeys.length; rk++) {
  11467. var rkey = rkeys[rk];
  11468. if (rkey !== 'protocol')
  11469. result[rkey] = relative[rkey];
  11470. }
  11471. //urlParse appends trailing / to urls like http://www.example.com
  11472. if (slashedProtocol[result.protocol] &&
  11473. result.hostname && !result.pathname) {
  11474. result.path = result.pathname = '/';
  11475. }
  11476. result.href = result.format();
  11477. return result;
  11478. }
  11479. if (relative.protocol && relative.protocol !== result.protocol) {
  11480. // if it's a known url protocol, then changing
  11481. // the protocol does weird things
  11482. // first, if it's not file:, then we MUST have a host,
  11483. // and if there was a path
  11484. // to begin with, then we MUST have a path.
  11485. // if it is file:, then the host is dropped,
  11486. // because that's known to be hostless.
  11487. // anything else is assumed to be absolute.
  11488. if (!slashedProtocol[relative.protocol]) {
  11489. var keys = Object.keys(relative);
  11490. for (var v = 0; v < keys.length; v++) {
  11491. var k = keys[v];
  11492. result[k] = relative[k];
  11493. }
  11494. result.href = result.format();
  11495. return result;
  11496. }
  11497. result.protocol = relative.protocol;
  11498. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  11499. var relPath = (relative.pathname || '').split('/');
  11500. while (relPath.length && !(relative.host = relPath.shift()));
  11501. if (!relative.host) relative.host = '';
  11502. if (!relative.hostname) relative.hostname = '';
  11503. if (relPath[0] !== '') relPath.unshift('');
  11504. if (relPath.length < 2) relPath.unshift('');
  11505. result.pathname = relPath.join('/');
  11506. } else {
  11507. result.pathname = relative.pathname;
  11508. }
  11509. result.search = relative.search;
  11510. result.query = relative.query;
  11511. result.host = relative.host || '';
  11512. result.auth = relative.auth;
  11513. result.hostname = relative.hostname || relative.host;
  11514. result.port = relative.port;
  11515. // to support http.request
  11516. if (result.pathname || result.search) {
  11517. var p = result.pathname || '';
  11518. var s = result.search || '';
  11519. result.path = p + s;
  11520. }
  11521. result.slashes = result.slashes || relative.slashes;
  11522. result.href = result.format();
  11523. return result;
  11524. }
  11525. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  11526. isRelAbs = (
  11527. relative.host ||
  11528. relative.pathname && relative.pathname.charAt(0) === '/'
  11529. ),
  11530. mustEndAbs = (isRelAbs || isSourceAbs ||
  11531. (result.host && relative.pathname)),
  11532. removeAllDots = mustEndAbs,
  11533. srcPath = result.pathname && result.pathname.split('/') || [],
  11534. relPath = relative.pathname && relative.pathname.split('/') || [],
  11535. psychotic = result.protocol && !slashedProtocol[result.protocol];
  11536. // if the url is a non-slashed url, then relative
  11537. // links like ../.. should be able
  11538. // to crawl up to the hostname, as well. This is strange.
  11539. // result.protocol has already been set by now.
  11540. // Later on, put the first path part into the host field.
  11541. if (psychotic) {
  11542. result.hostname = '';
  11543. result.port = null;
  11544. if (result.host) {
  11545. if (srcPath[0] === '') srcPath[0] = result.host;
  11546. else srcPath.unshift(result.host);
  11547. }
  11548. result.host = '';
  11549. if (relative.protocol) {
  11550. relative.hostname = null;
  11551. relative.port = null;
  11552. if (relative.host) {
  11553. if (relPath[0] === '') relPath[0] = relative.host;
  11554. else relPath.unshift(relative.host);
  11555. }
  11556. relative.host = null;
  11557. }
  11558. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  11559. }
  11560. if (isRelAbs) {
  11561. // it's absolute.
  11562. result.host = (relative.host || relative.host === '') ?
  11563. relative.host : result.host;
  11564. result.hostname = (relative.hostname || relative.hostname === '') ?
  11565. relative.hostname : result.hostname;
  11566. result.search = relative.search;
  11567. result.query = relative.query;
  11568. srcPath = relPath;
  11569. // fall through to the dot-handling below.
  11570. } else if (relPath.length) {
  11571. // it's relative
  11572. // throw away the existing file, and take the new path instead.
  11573. if (!srcPath) srcPath = [];
  11574. srcPath.pop();
  11575. srcPath = srcPath.concat(relPath);
  11576. result.search = relative.search;
  11577. result.query = relative.query;
  11578. } else if (!util.isNullOrUndefined(relative.search)) {
  11579. // just pull out the search.
  11580. // like href='?foo'.
  11581. // Put this after the other two cases because it simplifies the booleans
  11582. if (psychotic) {
  11583. result.hostname = result.host = srcPath.shift();
  11584. //occationaly the auth can get stuck only in host
  11585. //this especially happens in cases like
  11586. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  11587. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  11588. result.host.split('@') : false;
  11589. if (authInHost) {
  11590. result.auth = authInHost.shift();
  11591. result.host = result.hostname = authInHost.shift();
  11592. }
  11593. }
  11594. result.search = relative.search;
  11595. result.query = relative.query;
  11596. //to support http.request
  11597. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  11598. result.path = (result.pathname ? result.pathname : '') +
  11599. (result.search ? result.search : '');
  11600. }
  11601. result.href = result.format();
  11602. return result;
  11603. }
  11604. if (!srcPath.length) {
  11605. // no path at all. easy.
  11606. // we've already handled the other stuff above.
  11607. result.pathname = null;
  11608. //to support http.request
  11609. if (result.search) {
  11610. result.path = '/' + result.search;
  11611. } else {
  11612. result.path = null;
  11613. }
  11614. result.href = result.format();
  11615. return result;
  11616. }
  11617. // if a url ENDs in . or .., then it must get a trailing slash.
  11618. // however, if it ends in anything else non-slashy,
  11619. // then it must NOT get a trailing slash.
  11620. var last = srcPath.slice(-1)[0];
  11621. var hasTrailingSlash = (
  11622. (result.host || relative.host || srcPath.length > 1) &&
  11623. (last === '.' || last === '..') || last === '');
  11624. // strip single dots, resolve double dots to parent dir
  11625. // if the path tries to go above the root, `up` ends up > 0
  11626. var up = 0;
  11627. for (var i = srcPath.length; i >= 0; i--) {
  11628. last = srcPath[i];
  11629. if (last === '.') {
  11630. srcPath.splice(i, 1);
  11631. } else if (last === '..') {
  11632. srcPath.splice(i, 1);
  11633. up++;
  11634. } else if (up) {
  11635. srcPath.splice(i, 1);
  11636. up--;
  11637. }
  11638. }
  11639. // if the path is allowed to go above the root, restore leading ..s
  11640. if (!mustEndAbs && !removeAllDots) {
  11641. for (; up--; up) {
  11642. srcPath.unshift('..');
  11643. }
  11644. }
  11645. if (mustEndAbs && srcPath[0] !== '' &&
  11646. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  11647. srcPath.unshift('');
  11648. }
  11649. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  11650. srcPath.push('');
  11651. }
  11652. var isAbsolute = srcPath[0] === '' ||
  11653. (srcPath[0] && srcPath[0].charAt(0) === '/');
  11654. // put the host back
  11655. if (psychotic) {
  11656. result.hostname = result.host = isAbsolute ? '' :
  11657. srcPath.length ? srcPath.shift() : '';
  11658. //occationaly the auth can get stuck only in host
  11659. //this especially happens in cases like
  11660. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  11661. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  11662. result.host.split('@') : false;
  11663. if (authInHost) {
  11664. result.auth = authInHost.shift();
  11665. result.host = result.hostname = authInHost.shift();
  11666. }
  11667. }
  11668. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  11669. if (mustEndAbs && !isAbsolute) {
  11670. srcPath.unshift('');
  11671. }
  11672. if (!srcPath.length) {
  11673. result.pathname = null;
  11674. result.path = null;
  11675. } else {
  11676. result.pathname = srcPath.join('/');
  11677. }
  11678. //to support request.http
  11679. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  11680. result.path = (result.pathname ? result.pathname : '') +
  11681. (result.search ? result.search : '');
  11682. }
  11683. result.auth = relative.auth || result.auth;
  11684. result.slashes = result.slashes || relative.slashes;
  11685. result.href = result.format();
  11686. return result;
  11687. };
  11688. Url.prototype.parseHost = function() {
  11689. var host = this.host;
  11690. var port = portPattern.exec(host);
  11691. if (port) {
  11692. port = port[0];
  11693. if (port !== ':') {
  11694. this.port = port.substr(1);
  11695. }
  11696. host = host.substr(0, host.length - port.length);
  11697. }
  11698. if (host) this.hostname = host;
  11699. };
  11700. },{"./util":114,"punycode":93,"querystring":96}],114:[function(require,module,exports){
  11701. 'use strict';
  11702. module.exports = {
  11703. isString: function(arg) {
  11704. return typeof(arg) === 'string';
  11705. },
  11706. isObject: function(arg) {
  11707. return typeof(arg) === 'object' && arg !== null;
  11708. },
  11709. isNull: function(arg) {
  11710. return arg === null;
  11711. },
  11712. isNullOrUndefined: function(arg) {
  11713. return arg == null;
  11714. }
  11715. };
  11716. },{}],115:[function(require,module,exports){
  11717. (function (global){
  11718. /**
  11719. * Module exports.
  11720. */
  11721. module.exports = deprecate;
  11722. /**
  11723. * Mark that a method should not be used.
  11724. * Returns a modified function which warns once by default.
  11725. *
  11726. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  11727. *
  11728. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  11729. * will throw an Error when invoked.
  11730. *
  11731. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  11732. * will invoke `console.trace()` instead of `console.error()`.
  11733. *
  11734. * @param {Function} fn - the function to deprecate
  11735. * @param {String} msg - the string to print to the console when `fn` is invoked
  11736. * @returns {Function} a new "deprecated" version of `fn`
  11737. * @api public
  11738. */
  11739. function deprecate (fn, msg) {
  11740. if (config('noDeprecation')) {
  11741. return fn;
  11742. }
  11743. var warned = false;
  11744. function deprecated() {
  11745. if (!warned) {
  11746. if (config('throwDeprecation')) {
  11747. throw new Error(msg);
  11748. } else if (config('traceDeprecation')) {
  11749. console.trace(msg);
  11750. } else {
  11751. console.warn(msg);
  11752. }
  11753. warned = true;
  11754. }
  11755. return fn.apply(this, arguments);
  11756. }
  11757. return deprecated;
  11758. }
  11759. /**
  11760. * Checks `localStorage` for boolean values for the given `name`.
  11761. *
  11762. * @param {String} name
  11763. * @returns {Boolean}
  11764. * @api private
  11765. */
  11766. function config (name) {
  11767. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  11768. try {
  11769. if (!global.localStorage) return false;
  11770. } catch (_) {
  11771. return false;
  11772. }
  11773. var val = global.localStorage[name];
  11774. if (null == val) return false;
  11775. return String(val).toLowerCase() === 'true';
  11776. }
  11777. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11778. },{}],116:[function(require,module,exports){
  11779. module.exports = function isBuffer(arg) {
  11780. return arg && typeof arg === 'object'
  11781. && typeof arg.copy === 'function'
  11782. && typeof arg.fill === 'function'
  11783. && typeof arg.readUInt8 === 'function';
  11784. }
  11785. },{}],117:[function(require,module,exports){
  11786. (function (process,global){
  11787. // Copyright Joyent, Inc. and other Node contributors.
  11788. //
  11789. // Permission is hereby granted, free of charge, to any person obtaining a
  11790. // copy of this software and associated documentation files (the
  11791. // "Software"), to deal in the Software without restriction, including
  11792. // without limitation the rights to use, copy, modify, merge, publish,
  11793. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11794. // persons to whom the Software is furnished to do so, subject to the
  11795. // following conditions:
  11796. //
  11797. // The above copyright notice and this permission notice shall be included
  11798. // in all copies or substantial portions of the Software.
  11799. //
  11800. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11801. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11802. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11803. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11804. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11805. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11806. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11807. var formatRegExp = /%[sdj%]/g;
  11808. exports.format = function(f) {
  11809. if (!isString(f)) {
  11810. var objects = [];
  11811. for (var i = 0; i < arguments.length; i++) {
  11812. objects.push(inspect(arguments[i]));
  11813. }
  11814. return objects.join(' ');
  11815. }
  11816. var i = 1;
  11817. var args = arguments;
  11818. var len = args.length;
  11819. var str = String(f).replace(formatRegExp, function(x) {
  11820. if (x === '%%') return '%';
  11821. if (i >= len) return x;
  11822. switch (x) {
  11823. case '%s': return String(args[i++]);
  11824. case '%d': return Number(args[i++]);
  11825. case '%j':
  11826. try {
  11827. return JSON.stringify(args[i++]);
  11828. } catch (_) {
  11829. return '[Circular]';
  11830. }
  11831. default:
  11832. return x;
  11833. }
  11834. });
  11835. for (var x = args[i]; i < len; x = args[++i]) {
  11836. if (isNull(x) || !isObject(x)) {
  11837. str += ' ' + x;
  11838. } else {
  11839. str += ' ' + inspect(x);
  11840. }
  11841. }
  11842. return str;
  11843. };
  11844. // Mark that a method should not be used.
  11845. // Returns a modified function which warns once by default.
  11846. // If --no-deprecation is set, then it is a no-op.
  11847. exports.deprecate = function(fn, msg) {
  11848. // Allow for deprecating things in the process of starting up.
  11849. if (isUndefined(global.process)) {
  11850. return function() {
  11851. return exports.deprecate(fn, msg).apply(this, arguments);
  11852. };
  11853. }
  11854. if (process.noDeprecation === true) {
  11855. return fn;
  11856. }
  11857. var warned = false;
  11858. function deprecated() {
  11859. if (!warned) {
  11860. if (process.throwDeprecation) {
  11861. throw new Error(msg);
  11862. } else if (process.traceDeprecation) {
  11863. console.trace(msg);
  11864. } else {
  11865. console.error(msg);
  11866. }
  11867. warned = true;
  11868. }
  11869. return fn.apply(this, arguments);
  11870. }
  11871. return deprecated;
  11872. };
  11873. var debugs = {};
  11874. var debugEnviron;
  11875. exports.debuglog = function(set) {
  11876. if (isUndefined(debugEnviron))
  11877. debugEnviron = process.env.NODE_DEBUG || '';
  11878. set = set.toUpperCase();
  11879. if (!debugs[set]) {
  11880. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  11881. var pid = process.pid;
  11882. debugs[set] = function() {
  11883. var msg = exports.format.apply(exports, arguments);
  11884. console.error('%s %d: %s', set, pid, msg);
  11885. };
  11886. } else {
  11887. debugs[set] = function() {};
  11888. }
  11889. }
  11890. return debugs[set];
  11891. };
  11892. /**
  11893. * Echos the value of a value. Trys to print the value out
  11894. * in the best way possible given the different types.
  11895. *
  11896. * @param {Object} obj The object to print out.
  11897. * @param {Object} opts Optional options object that alters the output.
  11898. */
  11899. /* legacy: obj, showHidden, depth, colors*/
  11900. function inspect(obj, opts) {
  11901. // default options
  11902. var ctx = {
  11903. seen: [],
  11904. stylize: stylizeNoColor
  11905. };
  11906. // legacy...
  11907. if (arguments.length >= 3) ctx.depth = arguments[2];
  11908. if (arguments.length >= 4) ctx.colors = arguments[3];
  11909. if (isBoolean(opts)) {
  11910. // legacy...
  11911. ctx.showHidden = opts;
  11912. } else if (opts) {
  11913. // got an "options" object
  11914. exports._extend(ctx, opts);
  11915. }
  11916. // set default options
  11917. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  11918. if (isUndefined(ctx.depth)) ctx.depth = 2;
  11919. if (isUndefined(ctx.colors)) ctx.colors = false;
  11920. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  11921. if (ctx.colors) ctx.stylize = stylizeWithColor;
  11922. return formatValue(ctx, obj, ctx.depth);
  11923. }
  11924. exports.inspect = inspect;
  11925. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  11926. inspect.colors = {
  11927. 'bold' : [1, 22],
  11928. 'italic' : [3, 23],
  11929. 'underline' : [4, 24],
  11930. 'inverse' : [7, 27],
  11931. 'white' : [37, 39],
  11932. 'grey' : [90, 39],
  11933. 'black' : [30, 39],
  11934. 'blue' : [34, 39],
  11935. 'cyan' : [36, 39],
  11936. 'green' : [32, 39],
  11937. 'magenta' : [35, 39],
  11938. 'red' : [31, 39],
  11939. 'yellow' : [33, 39]
  11940. };
  11941. // Don't use 'blue' not visible on cmd.exe
  11942. inspect.styles = {
  11943. 'special': 'cyan',
  11944. 'number': 'yellow',
  11945. 'boolean': 'yellow',
  11946. 'undefined': 'grey',
  11947. 'null': 'bold',
  11948. 'string': 'green',
  11949. 'date': 'magenta',
  11950. // "name": intentionally not styling
  11951. 'regexp': 'red'
  11952. };
  11953. function stylizeWithColor(str, styleType) {
  11954. var style = inspect.styles[styleType];
  11955. if (style) {
  11956. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  11957. '\u001b[' + inspect.colors[style][1] + 'm';
  11958. } else {
  11959. return str;
  11960. }
  11961. }
  11962. function stylizeNoColor(str, styleType) {
  11963. return str;
  11964. }
  11965. function arrayToHash(array) {
  11966. var hash = {};
  11967. array.forEach(function(val, idx) {
  11968. hash[val] = true;
  11969. });
  11970. return hash;
  11971. }
  11972. function formatValue(ctx, value, recurseTimes) {
  11973. // Provide a hook for user-specified inspect functions.
  11974. // Check that value is an object with an inspect function on it
  11975. if (ctx.customInspect &&
  11976. value &&
  11977. isFunction(value.inspect) &&
  11978. // Filter out the util module, it's inspect function is special
  11979. value.inspect !== exports.inspect &&
  11980. // Also filter out any prototype objects using the circular check.
  11981. !(value.constructor && value.constructor.prototype === value)) {
  11982. var ret = value.inspect(recurseTimes, ctx);
  11983. if (!isString(ret)) {
  11984. ret = formatValue(ctx, ret, recurseTimes);
  11985. }
  11986. return ret;
  11987. }
  11988. // Primitive types cannot have properties
  11989. var primitive = formatPrimitive(ctx, value);
  11990. if (primitive) {
  11991. return primitive;
  11992. }
  11993. // Look up the keys of the object.
  11994. var keys = Object.keys(value);
  11995. var visibleKeys = arrayToHash(keys);
  11996. if (ctx.showHidden) {
  11997. keys = Object.getOwnPropertyNames(value);
  11998. }
  11999. // IE doesn't make error fields non-enumerable
  12000. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  12001. if (isError(value)
  12002. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  12003. return formatError(value);
  12004. }
  12005. // Some type of object without properties can be shortcutted.
  12006. if (keys.length === 0) {
  12007. if (isFunction(value)) {
  12008. var name = value.name ? ': ' + value.name : '';
  12009. return ctx.stylize('[Function' + name + ']', 'special');
  12010. }
  12011. if (isRegExp(value)) {
  12012. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12013. }
  12014. if (isDate(value)) {
  12015. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  12016. }
  12017. if (isError(value)) {
  12018. return formatError(value);
  12019. }
  12020. }
  12021. var base = '', array = false, braces = ['{', '}'];
  12022. // Make Array say that they are Array
  12023. if (isArray(value)) {
  12024. array = true;
  12025. braces = ['[', ']'];
  12026. }
  12027. // Make functions say that they are functions
  12028. if (isFunction(value)) {
  12029. var n = value.name ? ': ' + value.name : '';
  12030. base = ' [Function' + n + ']';
  12031. }
  12032. // Make RegExps say that they are RegExps
  12033. if (isRegExp(value)) {
  12034. base = ' ' + RegExp.prototype.toString.call(value);
  12035. }
  12036. // Make dates with properties first say the date
  12037. if (isDate(value)) {
  12038. base = ' ' + Date.prototype.toUTCString.call(value);
  12039. }
  12040. // Make error with message first say the error
  12041. if (isError(value)) {
  12042. base = ' ' + formatError(value);
  12043. }
  12044. if (keys.length === 0 && (!array || value.length == 0)) {
  12045. return braces[0] + base + braces[1];
  12046. }
  12047. if (recurseTimes < 0) {
  12048. if (isRegExp(value)) {
  12049. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12050. } else {
  12051. return ctx.stylize('[Object]', 'special');
  12052. }
  12053. }
  12054. ctx.seen.push(value);
  12055. var output;
  12056. if (array) {
  12057. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  12058. } else {
  12059. output = keys.map(function(key) {
  12060. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  12061. });
  12062. }
  12063. ctx.seen.pop();
  12064. return reduceToSingleString(output, base, braces);
  12065. }
  12066. function formatPrimitive(ctx, value) {
  12067. if (isUndefined(value))
  12068. return ctx.stylize('undefined', 'undefined');
  12069. if (isString(value)) {
  12070. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  12071. .replace(/'/g, "\\'")
  12072. .replace(/\\"/g, '"') + '\'';
  12073. return ctx.stylize(simple, 'string');
  12074. }
  12075. if (isNumber(value))
  12076. return ctx.stylize('' + value, 'number');
  12077. if (isBoolean(value))
  12078. return ctx.stylize('' + value, 'boolean');
  12079. // For some reason typeof null is "object", so special case here.
  12080. if (isNull(value))
  12081. return ctx.stylize('null', 'null');
  12082. }
  12083. function formatError(value) {
  12084. return '[' + Error.prototype.toString.call(value) + ']';
  12085. }
  12086. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  12087. var output = [];
  12088. for (var i = 0, l = value.length; i < l; ++i) {
  12089. if (hasOwnProperty(value, String(i))) {
  12090. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12091. String(i), true));
  12092. } else {
  12093. output.push('');
  12094. }
  12095. }
  12096. keys.forEach(function(key) {
  12097. if (!key.match(/^\d+$/)) {
  12098. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12099. key, true));
  12100. }
  12101. });
  12102. return output;
  12103. }
  12104. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  12105. var name, str, desc;
  12106. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  12107. if (desc.get) {
  12108. if (desc.set) {
  12109. str = ctx.stylize('[Getter/Setter]', 'special');
  12110. } else {
  12111. str = ctx.stylize('[Getter]', 'special');
  12112. }
  12113. } else {
  12114. if (desc.set) {
  12115. str = ctx.stylize('[Setter]', 'special');
  12116. }
  12117. }
  12118. if (!hasOwnProperty(visibleKeys, key)) {
  12119. name = '[' + key + ']';
  12120. }
  12121. if (!str) {
  12122. if (ctx.seen.indexOf(desc.value) < 0) {
  12123. if (isNull(recurseTimes)) {
  12124. str = formatValue(ctx, desc.value, null);
  12125. } else {
  12126. str = formatValue(ctx, desc.value, recurseTimes - 1);
  12127. }
  12128. if (str.indexOf('\n') > -1) {
  12129. if (array) {
  12130. str = str.split('\n').map(function(line) {
  12131. return ' ' + line;
  12132. }).join('\n').substr(2);
  12133. } else {
  12134. str = '\n' + str.split('\n').map(function(line) {
  12135. return ' ' + line;
  12136. }).join('\n');
  12137. }
  12138. }
  12139. } else {
  12140. str = ctx.stylize('[Circular]', 'special');
  12141. }
  12142. }
  12143. if (isUndefined(name)) {
  12144. if (array && key.match(/^\d+$/)) {
  12145. return str;
  12146. }
  12147. name = JSON.stringify('' + key);
  12148. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  12149. name = name.substr(1, name.length - 2);
  12150. name = ctx.stylize(name, 'name');
  12151. } else {
  12152. name = name.replace(/'/g, "\\'")
  12153. .replace(/\\"/g, '"')
  12154. .replace(/(^"|"$)/g, "'");
  12155. name = ctx.stylize(name, 'string');
  12156. }
  12157. }
  12158. return name + ': ' + str;
  12159. }
  12160. function reduceToSingleString(output, base, braces) {
  12161. var numLinesEst = 0;
  12162. var length = output.reduce(function(prev, cur) {
  12163. numLinesEst++;
  12164. if (cur.indexOf('\n') >= 0) numLinesEst++;
  12165. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  12166. }, 0);
  12167. if (length > 60) {
  12168. return braces[0] +
  12169. (base === '' ? '' : base + '\n ') +
  12170. ' ' +
  12171. output.join(',\n ') +
  12172. ' ' +
  12173. braces[1];
  12174. }
  12175. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  12176. }
  12177. // NOTE: These type checking functions intentionally don't use `instanceof`
  12178. // because it is fragile and can be easily faked with `Object.create()`.
  12179. function isArray(ar) {
  12180. return Array.isArray(ar);
  12181. }
  12182. exports.isArray = isArray;
  12183. function isBoolean(arg) {
  12184. return typeof arg === 'boolean';
  12185. }
  12186. exports.isBoolean = isBoolean;
  12187. function isNull(arg) {
  12188. return arg === null;
  12189. }
  12190. exports.isNull = isNull;
  12191. function isNullOrUndefined(arg) {
  12192. return arg == null;
  12193. }
  12194. exports.isNullOrUndefined = isNullOrUndefined;
  12195. function isNumber(arg) {
  12196. return typeof arg === 'number';
  12197. }
  12198. exports.isNumber = isNumber;
  12199. function isString(arg) {
  12200. return typeof arg === 'string';
  12201. }
  12202. exports.isString = isString;
  12203. function isSymbol(arg) {
  12204. return typeof arg === 'symbol';
  12205. }
  12206. exports.isSymbol = isSymbol;
  12207. function isUndefined(arg) {
  12208. return arg === void 0;
  12209. }
  12210. exports.isUndefined = isUndefined;
  12211. function isRegExp(re) {
  12212. return isObject(re) && objectToString(re) === '[object RegExp]';
  12213. }
  12214. exports.isRegExp = isRegExp;
  12215. function isObject(arg) {
  12216. return typeof arg === 'object' && arg !== null;
  12217. }
  12218. exports.isObject = isObject;
  12219. function isDate(d) {
  12220. return isObject(d) && objectToString(d) === '[object Date]';
  12221. }
  12222. exports.isDate = isDate;
  12223. function isError(e) {
  12224. return isObject(e) &&
  12225. (objectToString(e) === '[object Error]' || e instanceof Error);
  12226. }
  12227. exports.isError = isError;
  12228. function isFunction(arg) {
  12229. return typeof arg === 'function';
  12230. }
  12231. exports.isFunction = isFunction;
  12232. function isPrimitive(arg) {
  12233. return arg === null ||
  12234. typeof arg === 'boolean' ||
  12235. typeof arg === 'number' ||
  12236. typeof arg === 'string' ||
  12237. typeof arg === 'symbol' || // ES6 symbol
  12238. typeof arg === 'undefined';
  12239. }
  12240. exports.isPrimitive = isPrimitive;
  12241. exports.isBuffer = require('./support/isBuffer');
  12242. function objectToString(o) {
  12243. return Object.prototype.toString.call(o);
  12244. }
  12245. function pad(n) {
  12246. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  12247. }
  12248. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  12249. 'Oct', 'Nov', 'Dec'];
  12250. // 26 Feb 16:19:34
  12251. function timestamp() {
  12252. var d = new Date();
  12253. var time = [pad(d.getHours()),
  12254. pad(d.getMinutes()),
  12255. pad(d.getSeconds())].join(':');
  12256. return [d.getDate(), months[d.getMonth()], time].join(' ');
  12257. }
  12258. // log is just a thin wrapper to console.log that prepends a timestamp
  12259. exports.log = function() {
  12260. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  12261. };
  12262. /**
  12263. * Inherit the prototype methods from one constructor into another.
  12264. *
  12265. * The Function.prototype.inherits from lang.js rewritten as a standalone
  12266. * function (not on Function.prototype). NOTE: If this file is to be loaded
  12267. * during bootstrapping this function needs to be rewritten using some native
  12268. * functions as prototype setup using normal JavaScript does not work as
  12269. * expected during bootstrapping (see mirror.js in r114903).
  12270. *
  12271. * @param {function} ctor Constructor function which needs to inherit the
  12272. * prototype.
  12273. * @param {function} superCtor Constructor function to inherit prototype from.
  12274. */
  12275. exports.inherits = require('inherits');
  12276. exports._extend = function(origin, add) {
  12277. // Don't do anything if add isn't an object
  12278. if (!add || !isObject(add)) return origin;
  12279. var keys = Object.keys(add);
  12280. var i = keys.length;
  12281. while (i--) {
  12282. origin[keys[i]] = add[keys[i]];
  12283. }
  12284. return origin;
  12285. };
  12286. function hasOwnProperty(obj, prop) {
  12287. return Object.prototype.hasOwnProperty.call(obj, prop);
  12288. }
  12289. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12290. },{"./support/isBuffer":116,"_process":92,"inherits":80}],118:[function(require,module,exports){
  12291. (function (process,global){
  12292. 'use strict'
  12293. var Transform = require('readable-stream').Transform
  12294. var duplexify = require('duplexify')
  12295. var WS = require('ws')
  12296. var Buffer = require('safe-buffer').Buffer
  12297. module.exports = WebSocketStream
  12298. function buildProxy (options, socketWrite, socketEnd) {
  12299. var proxy = new Transform({
  12300. objectMode: options.objectMode
  12301. })
  12302. proxy._write = socketWrite
  12303. proxy._flush = socketEnd
  12304. return proxy
  12305. }
  12306. function WebSocketStream(target, protocols, options) {
  12307. var stream, socket
  12308. var isBrowser = process.title === 'browser'
  12309. var isNative = !!global.WebSocket
  12310. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  12311. if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
  12312. // accept the "options" Object as the 2nd argument
  12313. options = protocols
  12314. protocols = null
  12315. if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
  12316. protocols = options.protocol;
  12317. }
  12318. }
  12319. if (!options) options = {}
  12320. if (options.objectMode === undefined) {
  12321. options.objectMode = !(options.binary === true || options.binary === undefined)
  12322. }
  12323. var proxy = buildProxy(options, socketWrite, socketEnd)
  12324. if (!options.objectMode) {
  12325. proxy._writev = writev
  12326. }
  12327. // browser only: sets the maximum socket buffer size before throttling
  12328. var bufferSize = options.browserBufferSize || 1024 * 512
  12329. // browser only: how long to wait when throttling
  12330. var bufferTimeout = options.browserBufferTimeout || 1000
  12331. // use existing WebSocket object that was passed in
  12332. if (typeof target === 'object') {
  12333. socket = target
  12334. // otherwise make a new one
  12335. } else {
  12336. // special constructor treatment for native websockets in browsers, see
  12337. // https://github.com/maxogden/websocket-stream/issues/82
  12338. if (isNative && isBrowser) {
  12339. socket = new WS(target, protocols)
  12340. } else {
  12341. socket = new WS(target, protocols, options)
  12342. }
  12343. socket.binaryType = 'arraybuffer'
  12344. }
  12345. // was already open when passed in
  12346. if (socket.readyState === socket.OPEN) {
  12347. stream = proxy
  12348. } else {
  12349. stream = duplexify.obj()
  12350. socket.onopen = onopen
  12351. }
  12352. stream.socket = socket
  12353. socket.onclose = onclose
  12354. socket.onerror = onerror
  12355. socket.onmessage = onmessage
  12356. proxy.on('close', destroy)
  12357. var coerceToBuffer = !options.objectMode
  12358. function socketWriteNode(chunk, enc, next) {
  12359. // avoid errors, this never happens unless
  12360. // destroy() is called
  12361. if (socket.readyState !== socket.OPEN) {
  12362. next()
  12363. return
  12364. }
  12365. if (coerceToBuffer && typeof chunk === 'string') {
  12366. chunk = Buffer.from(chunk, 'utf8')
  12367. }
  12368. socket.send(chunk, next)
  12369. }
  12370. function socketWriteBrowser(chunk, enc, next) {
  12371. if (socket.bufferedAmount > bufferSize) {
  12372. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  12373. return
  12374. }
  12375. if (coerceToBuffer && typeof chunk === 'string') {
  12376. chunk = Buffer.from(chunk, 'utf8')
  12377. }
  12378. try {
  12379. socket.send(chunk)
  12380. } catch(err) {
  12381. return next(err)
  12382. }
  12383. next()
  12384. }
  12385. function socketEnd(done) {
  12386. socket.close()
  12387. done()
  12388. }
  12389. function onopen() {
  12390. stream.setReadable(proxy)
  12391. stream.setWritable(proxy)
  12392. stream.emit('connect')
  12393. }
  12394. function onclose() {
  12395. stream.end()
  12396. stream.destroy()
  12397. }
  12398. function onerror(err) {
  12399. stream.destroy(err)
  12400. }
  12401. function onmessage(event) {
  12402. var data = event.data
  12403. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  12404. else data = Buffer.from(data, 'utf8')
  12405. proxy.push(data)
  12406. }
  12407. function destroy() {
  12408. socket.close()
  12409. }
  12410. // this is to be enabled only if objectMode is false
  12411. function writev (chunks, cb) {
  12412. var buffers = new Array(chunks.length)
  12413. for (var i = 0; i < chunks.length; i++) {
  12414. if (typeof chunks[i].chunk === 'string') {
  12415. buffers[i] = Buffer.from(chunks[i], 'utf8')
  12416. } else {
  12417. buffers[i] = chunks[i].chunk
  12418. }
  12419. }
  12420. this._write(Buffer.concat(buffers), 'binary', cb)
  12421. }
  12422. return stream
  12423. }
  12424. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12425. },{"_process":92,"duplexify":17,"readable-stream":108,"safe-buffer":110,"ws":119}],119:[function(require,module,exports){
  12426. var ws = null
  12427. if (typeof WebSocket !== 'undefined') {
  12428. ws = WebSocket
  12429. } else if (typeof MozWebSocket !== 'undefined') {
  12430. ws = MozWebSocket
  12431. } else if (typeof window !== 'undefined') {
  12432. ws = window.WebSocket || window.MozWebSocket
  12433. }
  12434. module.exports = ws
  12435. },{}],120:[function(require,module,exports){
  12436. // Returns a wrapper function that returns a wrapped callback
  12437. // The wrapper function should do some stuff, and return a
  12438. // presumably different callback function.
  12439. // This makes sure that own properties are retained, so that
  12440. // decorations and such are not lost along the way.
  12441. module.exports = wrappy
  12442. function wrappy (fn, cb) {
  12443. if (fn && cb) return wrappy(fn)(cb)
  12444. if (typeof fn !== 'function')
  12445. throw new TypeError('need wrapper function')
  12446. Object.keys(fn).forEach(function (k) {
  12447. wrapper[k] = fn[k]
  12448. })
  12449. return wrapper
  12450. function wrapper() {
  12451. var args = new Array(arguments.length)
  12452. for (var i = 0; i < args.length; i++) {
  12453. args[i] = arguments[i]
  12454. }
  12455. var ret = fn.apply(this, args)
  12456. var cb = args[args.length-1]
  12457. if (typeof ret === 'function' && ret !== cb) {
  12458. Object.keys(cb).forEach(function (k) {
  12459. ret[k] = cb[k]
  12460. })
  12461. }
  12462. return ret
  12463. }
  12464. }
  12465. },{}],121:[function(require,module,exports){
  12466. module.exports = extend
  12467. var hasOwnProperty = Object.prototype.hasOwnProperty;
  12468. function extend() {
  12469. var target = {}
  12470. for (var i = 0; i < arguments.length; i++) {
  12471. var source = arguments[i]
  12472. for (var key in source) {
  12473. if (hasOwnProperty.call(source, key)) {
  12474. target[key] = source[key]
  12475. }
  12476. }
  12477. }
  12478. return target
  12479. }
  12480. },{}]},{},[9])(9)
  12481. });