mqtt.js 399 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633
  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].cb === 'function') {
  90. queue[messageId].cb(new Error('Connection closed'))
  91. delete queue[messageId]
  92. }
  93. })
  94. }
  95. }
  96. function flushVolatile (queue) {
  97. if (queue) {
  98. Object.keys(queue).forEach(function (messageId) {
  99. if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
  100. queue[messageId].cb(new Error('Connection closed'))
  101. delete queue[messageId]
  102. }
  103. })
  104. }
  105. }
  106. function storeAndSend (client, packet, cb, cbStorePut) {
  107. client.outgoingStore.put(packet, function storedPacket (err) {
  108. if (err) {
  109. return cb && cb(err)
  110. }
  111. cbStorePut()
  112. sendPacket(client, packet, cb)
  113. })
  114. }
  115. function nop () {}
  116. /**
  117. * MqttClient constructor
  118. *
  119. * @param {Stream} stream - stream
  120. * @param {Object} [options] - connection options
  121. * (see Connection#connect)
  122. */
  123. function MqttClient (streamBuilder, options) {
  124. var k
  125. var that = this
  126. if (!(this instanceof MqttClient)) {
  127. return new MqttClient(streamBuilder, options)
  128. }
  129. this.options = options || {}
  130. // Defaults
  131. for (k in defaultConnectOptions) {
  132. if (typeof this.options[k] === 'undefined') {
  133. this.options[k] = defaultConnectOptions[k]
  134. } else {
  135. this.options[k] = options[k]
  136. }
  137. }
  138. this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
  139. this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
  140. this.streamBuilder = streamBuilder
  141. // Inflight message storages
  142. this.outgoingStore = options.outgoingStore || new Store()
  143. this.incomingStore = options.incomingStore || new Store()
  144. // Should QoS zero messages be queued when the connection is broken?
  145. this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
  146. // map of subscribed topics to support reconnection
  147. this._resubscribeTopics = {}
  148. // map of a subscribe messageId and a topic
  149. this.messageIdToTopic = {}
  150. // Ping timer, setup in _setupPingTimer
  151. this.pingTimer = null
  152. // Is the client connected?
  153. this.connected = false
  154. // Are we disconnecting?
  155. this.disconnecting = false
  156. // Packet queue
  157. this.queue = []
  158. // connack timer
  159. this.connackTimer = null
  160. // Reconnect timer
  161. this.reconnectTimer = null
  162. // Is processing store?
  163. this._storeProcessing = false
  164. // Packet Ids are put into the store during store processing
  165. this._packetIdsDuringStoreProcessing = {}
  166. /**
  167. * MessageIDs starting with 1
  168. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  169. */
  170. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  171. // Inflight callbacks
  172. this.outgoing = {}
  173. // True if connection is first time.
  174. this._firstConnection = true
  175. // Mark disconnected on stream close
  176. this.on('close', function () {
  177. this.connected = false
  178. clearTimeout(this.connackTimer)
  179. })
  180. // Send queued packets
  181. this.on('connect', function () {
  182. var queue = this.queue
  183. function deliver () {
  184. var entry = queue.shift()
  185. var packet = null
  186. if (!entry) {
  187. return
  188. }
  189. packet = entry.packet
  190. that._sendPacket(
  191. packet,
  192. function (err) {
  193. if (entry.cb) {
  194. entry.cb(err)
  195. }
  196. deliver()
  197. }
  198. )
  199. }
  200. deliver()
  201. })
  202. // Clear ping timer
  203. this.on('close', function () {
  204. if (that.pingTimer !== null) {
  205. that.pingTimer.clear()
  206. that.pingTimer = null
  207. }
  208. })
  209. // Setup reconnect timer on disconnect
  210. this.on('close', this._setupReconnect)
  211. events.EventEmitter.call(this)
  212. this._setupStream()
  213. }
  214. inherits(MqttClient, events.EventEmitter)
  215. /**
  216. * setup the event handlers in the inner stream.
  217. *
  218. * @api private
  219. */
  220. MqttClient.prototype._setupStream = function () {
  221. var connectPacket
  222. var that = this
  223. var writable = new Writable()
  224. var parser = mqttPacket.parser(this.options)
  225. var completeParse = null
  226. var packets = []
  227. this._clearReconnect()
  228. this.stream = this.streamBuilder(this)
  229. parser.on('packet', function (packet) {
  230. packets.push(packet)
  231. })
  232. function nextTickWork () {
  233. if (packets.length) {
  234. process.nextTick(work)
  235. } else {
  236. var done = completeParse
  237. completeParse = null
  238. done()
  239. }
  240. }
  241. function work () {
  242. var packet = packets.shift()
  243. if (packet) {
  244. that._handlePacket(packet, nextTickWork)
  245. } else {
  246. var done = completeParse
  247. completeParse = null
  248. if (done) done()
  249. }
  250. }
  251. writable._write = function (buf, enc, done) {
  252. completeParse = done
  253. parser.parse(buf)
  254. work()
  255. }
  256. this.stream.pipe(writable)
  257. // Suppress connection errors
  258. this.stream.on('error', nop)
  259. // Echo stream close
  260. this.stream.on('close', function () {
  261. flushVolatile(that.outgoing)
  262. that.emit('close')
  263. })
  264. // Send a connect packet
  265. connectPacket = Object.create(this.options)
  266. connectPacket.cmd = 'connect'
  267. // avoid message queue
  268. sendPacket(this, connectPacket)
  269. // Echo connection errors
  270. parser.on('error', this.emit.bind(this, 'error'))
  271. // auth
  272. if (this.options.properties) {
  273. if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
  274. this.emit('error', new Error('Packet has no Authentication Method'))
  275. return this
  276. }
  277. if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
  278. var authPacket = xtend({cmd: 'auth', reasonCode: 0}, this.options.authPacket)
  279. sendPacket(this, authPacket)
  280. }
  281. }
  282. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  283. this.stream.setMaxListeners(1000)
  284. clearTimeout(this.connackTimer)
  285. this.connackTimer = setTimeout(function () {
  286. that._cleanUp(true)
  287. }, this.options.connectTimeout)
  288. }
  289. MqttClient.prototype._handlePacket = function (packet, done) {
  290. var options = this.options
  291. if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
  292. this.emit('error', new Error('exceeding packets size ' + packet.cmd))
  293. this.end({reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }})
  294. return this
  295. }
  296. this.emit('packetreceive', packet)
  297. switch (packet.cmd) {
  298. case 'publish':
  299. this._handlePublish(packet, done)
  300. break
  301. case 'puback':
  302. case 'pubrec':
  303. case 'pubcomp':
  304. case 'suback':
  305. case 'unsuback':
  306. this._handleAck(packet)
  307. done()
  308. break
  309. case 'pubrel':
  310. this._handlePubrel(packet, done)
  311. break
  312. case 'connack':
  313. this._handleConnack(packet)
  314. done()
  315. break
  316. case 'pingresp':
  317. this._handlePingresp(packet)
  318. done()
  319. break
  320. case 'disconnect':
  321. this._handleDisconnect(packet)
  322. done()
  323. break
  324. default:
  325. // do nothing
  326. // maybe we should do an error handling
  327. // or just log it
  328. break
  329. }
  330. }
  331. MqttClient.prototype._checkDisconnecting = function (callback) {
  332. if (this.disconnecting) {
  333. if (callback) {
  334. callback(new Error('client disconnecting'))
  335. } else {
  336. this.emit('error', new Error('client disconnecting'))
  337. }
  338. }
  339. return this.disconnecting
  340. }
  341. /**
  342. * publish - publish <message> to <topic>
  343. *
  344. * @param {String} topic - topic to publish to
  345. * @param {String, Buffer} message - message to publish
  346. * @param {Object} [opts] - publish options, includes:
  347. * {Number} qos - qos level to publish on
  348. * {Boolean} retain - whether or not to retain the message
  349. * {Boolean} dup - whether or not mark a message as duplicate
  350. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  351. * @param {Function} [callback] - function(err){}
  352. * called when publish succeeds or fails
  353. * @returns {MqttClient} this - for chaining
  354. * @api public
  355. *
  356. * @example client.publish('topic', 'message');
  357. * @example
  358. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  359. * @example client.publish('topic', 'message', console.log);
  360. */
  361. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  362. var packet
  363. var options = this.options
  364. // .publish(topic, payload, cb);
  365. if (typeof opts === 'function') {
  366. callback = opts
  367. opts = null
  368. }
  369. // default opts
  370. var defaultOpts = {qos: 0, retain: false, dup: false}
  371. opts = xtend(defaultOpts, opts)
  372. if (this._checkDisconnecting(callback)) {
  373. return this
  374. }
  375. packet = {
  376. cmd: 'publish',
  377. topic: topic,
  378. payload: message,
  379. qos: opts.qos,
  380. retain: opts.retain,
  381. messageId: this._nextId(),
  382. dup: opts.dup
  383. }
  384. if (options.protocolVersion === 5) {
  385. packet.properties = opts.properties
  386. if ((!options.properties && packet.properties && packet.properties.topicAlias) || ((opts.properties && options.properties) &&
  387. ((opts.properties.topicAlias && options.properties.topicAliasMaximum && opts.properties.topicAlias > options.properties.topicAliasMaximum) ||
  388. (!options.properties.topicAliasMaximum && opts.properties.topicAlias)))) {
  389. /*
  390. if we are don`t setup topic alias or
  391. topic alias maximum less than topic alias or
  392. server don`t give topic alias maximum,
  393. we are removing topic alias from packet
  394. */
  395. delete packet.properties.topicAlias
  396. }
  397. }
  398. switch (opts.qos) {
  399. case 1:
  400. case 2:
  401. // Add to callbacks
  402. this.outgoing[packet.messageId] = {
  403. volatile: false,
  404. cb: callback || nop
  405. }
  406. if (this._storeProcessing) {
  407. this._packetIdsDuringStoreProcessing[packet.messageId] = false
  408. this._storePacket(packet, undefined, opts.cbStorePut)
  409. } else {
  410. this._sendPacket(packet, undefined, opts.cbStorePut)
  411. }
  412. break
  413. default:
  414. if (this._storeProcessing) {
  415. this._storePacket(packet, callback, opts.cbStorePut)
  416. } else {
  417. this._sendPacket(packet, callback, opts.cbStorePut)
  418. }
  419. break
  420. }
  421. return this
  422. }
  423. /**
  424. * subscribe - subscribe to <topic>
  425. *
  426. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  427. * @param {Object} [opts] - optional subscription options, includes:
  428. * {Number} qos - subscribe qos level
  429. * @param {Function} [callback] - function(err, granted){} where:
  430. * {Error} err - subscription error (none at the moment!)
  431. * {Array} granted - array of {topic: 't', qos: 0}
  432. * @returns {MqttClient} this - for chaining
  433. * @api public
  434. * @example client.subscribe('topic');
  435. * @example client.subscribe('topic', {qos: 1});
  436. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  437. * @example client.subscribe('topic', console.log);
  438. */
  439. MqttClient.prototype.subscribe = function () {
  440. var packet
  441. var args = new Array(arguments.length)
  442. for (var i = 0; i < arguments.length; i++) {
  443. args[i] = arguments[i]
  444. }
  445. var subs = []
  446. var obj = args.shift()
  447. var resubscribe = obj.resubscribe
  448. var callback = args.pop() || nop
  449. var opts = args.pop()
  450. var invalidTopic
  451. var that = this
  452. var version = this.options.protocolVersion
  453. delete obj.resubscribe
  454. if (typeof obj === 'string') {
  455. obj = [obj]
  456. }
  457. if (typeof callback !== 'function') {
  458. opts = callback
  459. callback = nop
  460. }
  461. invalidTopic = validations.validateTopics(obj)
  462. if (invalidTopic !== null) {
  463. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  464. return this
  465. }
  466. if (this._checkDisconnecting(callback)) {
  467. return this
  468. }
  469. var defaultOpts = {
  470. qos: 0
  471. }
  472. if (version === 5) {
  473. defaultOpts.nl = false
  474. defaultOpts.rap = false
  475. defaultOpts.rh = 0
  476. }
  477. opts = xtend(defaultOpts, opts)
  478. if (Array.isArray(obj)) {
  479. obj.forEach(function (topic) {
  480. if (!that._resubscribeTopics.hasOwnProperty(topic) ||
  481. that._resubscribeTopics[topic].qos < opts.qos ||
  482. resubscribe) {
  483. var currentOpts = {
  484. topic: topic,
  485. qos: opts.qos
  486. }
  487. if (version === 5) {
  488. currentOpts.nl = opts.nl
  489. currentOpts.rap = opts.rap
  490. currentOpts.rh = opts.rh
  491. currentOpts.properties = opts.properties
  492. }
  493. subs.push(currentOpts)
  494. }
  495. })
  496. } else {
  497. Object
  498. .keys(obj)
  499. .forEach(function (k) {
  500. if (!that._resubscribeTopics.hasOwnProperty(k) ||
  501. that._resubscribeTopics[k].qos < obj[k].qos ||
  502. resubscribe) {
  503. var currentOpts = {
  504. topic: k,
  505. qos: obj[k].qos
  506. }
  507. if (version === 5) {
  508. currentOpts.nl = obj[k].nl
  509. currentOpts.rap = obj[k].rap
  510. currentOpts.rh = obj[k].rh
  511. currentOpts.properties = opts.properties
  512. }
  513. subs.push(currentOpts)
  514. }
  515. })
  516. }
  517. packet = {
  518. cmd: 'subscribe',
  519. subscriptions: subs,
  520. qos: 1,
  521. retain: false,
  522. dup: false,
  523. messageId: this._nextId()
  524. }
  525. if (opts.properties) {
  526. packet.properties = opts.properties
  527. }
  528. if (!subs.length) {
  529. callback(null, [])
  530. return
  531. }
  532. // subscriptions to resubscribe to in case of disconnect
  533. if (this.options.resubscribe) {
  534. var topics = []
  535. subs.forEach(function (sub) {
  536. if (that.options.reconnectPeriod > 0) {
  537. var topic = { qos: sub.qos }
  538. if (version === 5) {
  539. topic.nl = sub.nl || false
  540. topic.rap = sub.rap || false
  541. topic.rh = sub.rh || 0
  542. topic.properties = sub.properties
  543. }
  544. that._resubscribeTopics[sub.topic] = topic
  545. topics.push(sub.topic)
  546. }
  547. })
  548. that.messageIdToTopic[packet.messageId] = topics
  549. }
  550. this.outgoing[packet.messageId] = {
  551. volatile: true,
  552. cb: function (err, packet) {
  553. if (!err) {
  554. var granted = packet.granted
  555. for (var i = 0; i < granted.length; i += 1) {
  556. subs[i].qos = granted[i]
  557. }
  558. }
  559. callback(err, subs)
  560. }
  561. }
  562. this._sendPacket(packet)
  563. return this
  564. }
  565. /**
  566. * unsubscribe - unsubscribe from topic(s)
  567. *
  568. * @param {String, Array} topic - topics to unsubscribe from
  569. * @param {Object} [opts] - optional subscription options, includes:
  570. * {Object} properties - properties of unsubscribe packet
  571. * @param {Function} [callback] - callback fired on unsuback
  572. * @returns {MqttClient} this - for chaining
  573. * @api public
  574. * @example client.unsubscribe('topic');
  575. * @example client.unsubscribe('topic', console.log);
  576. */
  577. MqttClient.prototype.unsubscribe = function () {
  578. var packet = {
  579. cmd: 'unsubscribe',
  580. qos: 1,
  581. messageId: this._nextId()
  582. }
  583. var that = this
  584. var args = new Array(arguments.length)
  585. for (var i = 0; i < arguments.length; i++) {
  586. args[i] = arguments[i]
  587. }
  588. var topic = args.shift()
  589. var callback = args.pop() || nop
  590. var opts = args.pop()
  591. if (typeof topic === 'string') {
  592. topic = [topic]
  593. }
  594. if (typeof callback !== 'function') {
  595. opts = callback
  596. callback = nop
  597. }
  598. if (this._checkDisconnecting(callback)) {
  599. return this
  600. }
  601. if (typeof topic === 'string') {
  602. packet.unsubscriptions = [topic]
  603. } else if (typeof topic === 'object' && topic.length) {
  604. packet.unsubscriptions = topic
  605. }
  606. if (this.options.resubscribe) {
  607. packet.unsubscriptions.forEach(function (topic) {
  608. delete that._resubscribeTopics[topic]
  609. })
  610. }
  611. if (typeof opts === 'object' && opts.properties) {
  612. packet.properties = opts.properties
  613. }
  614. this.outgoing[packet.messageId] = {
  615. volatile: true,
  616. cb: callback
  617. }
  618. this._sendPacket(packet)
  619. return this
  620. }
  621. /**
  622. * end - close connection
  623. *
  624. * @returns {MqttClient} this - for chaining
  625. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  626. * @param {Function} cb - called when the client has been closed
  627. *
  628. * @api public
  629. */
  630. MqttClient.prototype.end = function () {
  631. var that = this
  632. var force = arguments[0]
  633. var opts = arguments[1]
  634. var cb = arguments[2]
  635. if (force == null || typeof force !== 'boolean') {
  636. cb = opts || nop
  637. opts = force
  638. force = false
  639. if (typeof opts !== 'object') {
  640. cb = opts
  641. opts = null
  642. if (typeof cb !== 'function') {
  643. cb = nop
  644. }
  645. }
  646. }
  647. if (typeof opts !== 'object') {
  648. cb = opts
  649. opts = null
  650. }
  651. cb = cb || nop
  652. function closeStores () {
  653. that.disconnected = true
  654. that.incomingStore.close(function () {
  655. that.outgoingStore.close(function () {
  656. if (cb) {
  657. cb.apply(null, arguments)
  658. }
  659. that.emit('end')
  660. })
  661. })
  662. if (that._deferredReconnect) {
  663. that._deferredReconnect()
  664. }
  665. }
  666. function finish () {
  667. // defer closesStores of an I/O cycle,
  668. // just to make sure things are
  669. // ok for websockets
  670. that._cleanUp(force, setImmediate.bind(null, closeStores), opts)
  671. }
  672. if (this.disconnecting) {
  673. return this
  674. }
  675. this._clearReconnect()
  676. this.disconnecting = true
  677. if (!force && Object.keys(this.outgoing).length > 0) {
  678. // wait 10ms, just to be sure we received all of it
  679. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  680. } else {
  681. finish()
  682. }
  683. return this
  684. }
  685. /**
  686. * removeOutgoingMessage - remove a message in outgoing store
  687. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  688. *
  689. * @param {Number} mid - messageId to remove message
  690. * @returns {MqttClient} this - for chaining
  691. * @api public
  692. *
  693. * @example client.removeOutgoingMessage(client.getLastMessageId());
  694. */
  695. MqttClient.prototype.removeOutgoingMessage = function (mid) {
  696. var cb = this.outgoing[mid] ? this.outgoing[mid].cb : null
  697. delete this.outgoing[mid]
  698. this.outgoingStore.del({messageId: mid}, function () {
  699. cb(new Error('Message removed'))
  700. })
  701. return this
  702. }
  703. /**
  704. * reconnect - connect again using the same options as connect()
  705. *
  706. * @param {Object} [opts] - optional reconnect options, includes:
  707. * {Store} incomingStore - a store for the incoming packets
  708. * {Store} outgoingStore - a store for the outgoing packets
  709. * if opts is not given, current stores are used
  710. * @returns {MqttClient} this - for chaining
  711. *
  712. * @api public
  713. */
  714. MqttClient.prototype.reconnect = function (opts) {
  715. var that = this
  716. var f = function () {
  717. if (opts) {
  718. that.options.incomingStore = opts.incomingStore
  719. that.options.outgoingStore = opts.outgoingStore
  720. } else {
  721. that.options.incomingStore = null
  722. that.options.outgoingStore = null
  723. }
  724. that.incomingStore = that.options.incomingStore || new Store()
  725. that.outgoingStore = that.options.outgoingStore || new Store()
  726. that.disconnecting = false
  727. that.disconnected = false
  728. that._deferredReconnect = null
  729. that._reconnect()
  730. }
  731. if (this.disconnecting && !this.disconnected) {
  732. this._deferredReconnect = f
  733. } else {
  734. f()
  735. }
  736. return this
  737. }
  738. /**
  739. * _reconnect - implement reconnection
  740. * @api privateish
  741. */
  742. MqttClient.prototype._reconnect = function () {
  743. this.emit('reconnect')
  744. this._setupStream()
  745. }
  746. /**
  747. * _setupReconnect - setup reconnect timer
  748. */
  749. MqttClient.prototype._setupReconnect = function () {
  750. var that = this
  751. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  752. if (!this.reconnecting) {
  753. this.emit('offline')
  754. this.reconnecting = true
  755. }
  756. that.reconnectTimer = setInterval(function () {
  757. that._reconnect()
  758. }, that.options.reconnectPeriod)
  759. }
  760. }
  761. /**
  762. * _clearReconnect - clear the reconnect timer
  763. */
  764. MqttClient.prototype._clearReconnect = function () {
  765. if (this.reconnectTimer) {
  766. clearInterval(this.reconnectTimer)
  767. this.reconnectTimer = null
  768. }
  769. }
  770. /**
  771. * _cleanUp - clean up on connection end
  772. * @api private
  773. */
  774. MqttClient.prototype._cleanUp = function (forced, done) {
  775. var opts = arguments[2]
  776. if (done) {
  777. this.stream.on('close', done)
  778. }
  779. if (forced) {
  780. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  781. flush(this.outgoing)
  782. }
  783. this.stream.destroy()
  784. } else {
  785. var packet = xtend({ cmd: 'disconnect' }, opts)
  786. this._sendPacket(
  787. packet,
  788. setImmediate.bind(
  789. null,
  790. this.stream.end.bind(this.stream)
  791. )
  792. )
  793. }
  794. if (!this.disconnecting) {
  795. this._clearReconnect()
  796. this._setupReconnect()
  797. }
  798. if (this.pingTimer !== null) {
  799. this.pingTimer.clear()
  800. this.pingTimer = null
  801. }
  802. if (done && !this.connected) {
  803. this.stream.removeListener('close', done)
  804. done()
  805. }
  806. }
  807. /**
  808. * _sendPacket - send or queue a packet
  809. * @param {String} type - packet type (see `protocol`)
  810. * @param {Object} packet - packet options
  811. * @param {Function} cb - callback when the packet is sent
  812. * @param {Function} cbStorePut - called when message is put into outgoingStore
  813. * @api private
  814. */
  815. MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
  816. cbStorePut = cbStorePut || nop
  817. if (!this.connected) {
  818. this._storePacket(packet, cb, cbStorePut)
  819. return
  820. }
  821. // When sending a packet, reschedule the ping timer
  822. this._shiftPingInterval()
  823. switch (packet.cmd) {
  824. case 'publish':
  825. break
  826. case 'pubrel':
  827. storeAndSend(this, packet, cb, cbStorePut)
  828. return
  829. default:
  830. sendPacket(this, packet, cb)
  831. return
  832. }
  833. switch (packet.qos) {
  834. case 2:
  835. case 1:
  836. storeAndSend(this, packet, cb, cbStorePut)
  837. break
  838. /**
  839. * no need of case here since it will be caught by default
  840. * and jshint comply that before default it must be a break
  841. * anyway it will result in -1 evaluation
  842. */
  843. case 0:
  844. /* falls through */
  845. default:
  846. sendPacket(this, packet, cb)
  847. break
  848. }
  849. }
  850. /**
  851. * _storePacket - queue a packet
  852. * @param {String} type - packet type (see `protocol`)
  853. * @param {Object} packet - packet options
  854. * @param {Function} cb - callback when the packet is sent
  855. * @param {Function} cbStorePut - called when message is put into outgoingStore
  856. * @api private
  857. */
  858. MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
  859. cbStorePut = cbStorePut || nop
  860. if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
  861. this.queue.push({ packet: packet, cb: cb })
  862. } else if (packet.qos > 0) {
  863. cb = this.outgoing[packet.messageId] ? this.outgoing[packet.messageId].cb : null
  864. this.outgoingStore.put(packet, function (err) {
  865. if (err) {
  866. return cb && cb(err)
  867. }
  868. cbStorePut()
  869. })
  870. } else if (cb) {
  871. cb(new Error('No connection to broker'))
  872. }
  873. }
  874. /**
  875. * _setupPingTimer - setup the ping timer
  876. *
  877. * @api private
  878. */
  879. MqttClient.prototype._setupPingTimer = function () {
  880. var that = this
  881. if (!this.pingTimer && this.options.keepalive) {
  882. this.pingResp = true
  883. this.pingTimer = reInterval(function () {
  884. that._checkPing()
  885. }, this.options.keepalive * 1000)
  886. }
  887. }
  888. /**
  889. * _shiftPingInterval - reschedule the ping interval
  890. *
  891. * @api private
  892. */
  893. MqttClient.prototype._shiftPingInterval = function () {
  894. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  895. this.pingTimer.reschedule(this.options.keepalive * 1000)
  896. }
  897. }
  898. /**
  899. * _checkPing - check if a pingresp has come back, and ping the server again
  900. *
  901. * @api private
  902. */
  903. MqttClient.prototype._checkPing = function () {
  904. if (this.pingResp) {
  905. this.pingResp = false
  906. this._sendPacket({ cmd: 'pingreq' })
  907. } else {
  908. // do a forced cleanup since socket will be in bad shape
  909. this._cleanUp(true)
  910. }
  911. }
  912. /**
  913. * _handlePingresp - handle a pingresp
  914. *
  915. * @api private
  916. */
  917. MqttClient.prototype._handlePingresp = function () {
  918. this.pingResp = true
  919. }
  920. /**
  921. * _handleConnack
  922. *
  923. * @param {Object} packet
  924. * @api private
  925. */
  926. MqttClient.prototype._handleConnack = function (packet) {
  927. var options = this.options
  928. var version = options.protocolVersion
  929. var rc = version === 5 ? packet.reasonCode : packet.returnCode
  930. clearTimeout(this.connackTimer)
  931. if (packet.properties) {
  932. if (packet.properties.topicAliasMaximum) {
  933. if (!options.properties) { options.properties = {} }
  934. options.properties.topicAliasMaximum = packet.properties.topicAliasMaximum
  935. }
  936. if (packet.properties.serverKeepAlive && options.keepalive) {
  937. options.keepalive = packet.properties.serverKeepAlive
  938. this._shiftPingInterval()
  939. }
  940. if (packet.properties.maximumPacketSize) {
  941. if (!options.properties) { options.properties = {} }
  942. options.properties.maximumPacketSize = packet.properties.maximumPacketSize
  943. }
  944. }
  945. if (rc === 0) {
  946. this.reconnecting = false
  947. this._onConnect(packet)
  948. } else if (rc > 0) {
  949. var err = new Error('Connection refused: ' + errors[rc])
  950. err.code = rc
  951. this.emit('error', err)
  952. }
  953. }
  954. /**
  955. * _handlePublish
  956. *
  957. * @param {Object} packet
  958. * @api private
  959. */
  960. /*
  961. those late 2 case should be rewrite to comply with coding style:
  962. case 1:
  963. case 0:
  964. // do not wait sending a puback
  965. // no callback passed
  966. if (1 === qos) {
  967. this._sendPacket({
  968. cmd: 'puback',
  969. messageId: mid
  970. });
  971. }
  972. // emit the message event for both qos 1 and 0
  973. this.emit('message', topic, message, packet);
  974. this.handleMessage(packet, done);
  975. break;
  976. default:
  977. // do nothing but every switch mus have a default
  978. // log or throw an error about unknown qos
  979. break;
  980. for now i just suppressed the warnings
  981. */
  982. MqttClient.prototype._handlePublish = function (packet, done) {
  983. done = typeof done !== 'undefined' ? done : nop
  984. var topic = packet.topic.toString()
  985. var message = packet.payload
  986. var qos = packet.qos
  987. var mid = packet.messageId
  988. var that = this
  989. var options = this.options
  990. var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  991. switch (qos) {
  992. case 2: {
  993. options.customHandleAcks(topic, message, packet, function (error, code) {
  994. if (!(error instanceof Error)) {
  995. code = error
  996. error = null
  997. }
  998. if (error) { return that.emit('error', error) }
  999. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
  1000. if (code) {
  1001. that._sendPacket({cmd: 'pubrec', messageId: mid, reasonCode: code}, done)
  1002. } else {
  1003. that.incomingStore.put(packet, function () {
  1004. that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
  1005. })
  1006. }
  1007. })
  1008. break
  1009. }
  1010. case 1: {
  1011. // emit the message event
  1012. options.customHandleAcks(topic, message, packet, function (error, code) {
  1013. if (!(error instanceof Error)) {
  1014. code = error
  1015. error = null
  1016. }
  1017. if (error) { return that.emit('error', error) }
  1018. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
  1019. if (!code) { that.emit('message', topic, message, packet) }
  1020. that.handleMessage(packet, function (err) {
  1021. if (err) {
  1022. return done && done(err)
  1023. }
  1024. that._sendPacket({cmd: 'puback', messageId: mid, reasonCode: code}, done)
  1025. })
  1026. })
  1027. break
  1028. }
  1029. case 0:
  1030. // emit the message event
  1031. this.emit('message', topic, message, packet)
  1032. this.handleMessage(packet, done)
  1033. break
  1034. default:
  1035. // do nothing
  1036. // log or throw an error about unknown qos
  1037. break
  1038. }
  1039. }
  1040. /**
  1041. * Handle messages with backpressure support, one at a time.
  1042. * Override at will.
  1043. *
  1044. * @param Packet packet the packet
  1045. * @param Function callback call when finished
  1046. * @api public
  1047. */
  1048. MqttClient.prototype.handleMessage = function (packet, callback) {
  1049. callback()
  1050. }
  1051. /**
  1052. * _handleAck
  1053. *
  1054. * @param {Object} packet
  1055. * @api private
  1056. */
  1057. MqttClient.prototype._handleAck = function (packet) {
  1058. /* eslint no-fallthrough: "off" */
  1059. var mid = packet.messageId
  1060. var type = packet.cmd
  1061. var response = null
  1062. var cb = this.outgoing[mid] ? this.outgoing[mid].cb : null
  1063. var that = this
  1064. var err
  1065. if (!cb) {
  1066. // Server sent an ack in error, ignore it.
  1067. return
  1068. }
  1069. // Process
  1070. switch (type) {
  1071. case 'pubcomp':
  1072. // same thing as puback for QoS 2
  1073. case 'puback':
  1074. var pubackRC = packet.reasonCode
  1075. // Callback - we're done
  1076. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1077. err = new Error('Publish error: ' + errors[pubackRC])
  1078. err.code = pubackRC
  1079. cb(err, packet)
  1080. }
  1081. delete this.outgoing[mid]
  1082. this.outgoingStore.del(packet, cb)
  1083. break
  1084. case 'pubrec':
  1085. response = {
  1086. cmd: 'pubrel',
  1087. qos: 2,
  1088. messageId: mid
  1089. }
  1090. var pubrecRC = packet.reasonCode
  1091. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1092. err = new Error('Publish error: ' + errors[pubrecRC])
  1093. err.code = pubrecRC
  1094. cb(err, packet)
  1095. } else {
  1096. this._sendPacket(response)
  1097. }
  1098. break
  1099. case 'suback':
  1100. delete this.outgoing[mid]
  1101. for (var grantedI = 0; grantedI < packet.granted.length; grantedI++) {
  1102. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1103. // suback with Failure status
  1104. var topics = this.messageIdToTopic[mid]
  1105. if (topics) {
  1106. topics.forEach(function (topic) {
  1107. delete that._resubscribeTopics[topic]
  1108. })
  1109. }
  1110. }
  1111. }
  1112. cb(null, packet)
  1113. break
  1114. case 'unsuback':
  1115. delete this.outgoing[mid]
  1116. cb(null)
  1117. break
  1118. default:
  1119. that.emit('error', new Error('unrecognized packet type'))
  1120. }
  1121. if (this.disconnecting &&
  1122. Object.keys(this.outgoing).length === 0) {
  1123. this.emit('outgoingEmpty')
  1124. }
  1125. }
  1126. /**
  1127. * _handlePubrel
  1128. *
  1129. * @param {Object} packet
  1130. * @api private
  1131. */
  1132. MqttClient.prototype._handlePubrel = function (packet, callback) {
  1133. callback = typeof callback !== 'undefined' ? callback : nop
  1134. var mid = packet.messageId
  1135. var that = this
  1136. var comp = {cmd: 'pubcomp', messageId: mid}
  1137. that.incomingStore.get(packet, function (err, pub) {
  1138. if (!err) {
  1139. that.emit('message', pub.topic, pub.payload, pub)
  1140. that.handleMessage(pub, function (err) {
  1141. if (err) {
  1142. return callback(err)
  1143. }
  1144. that.incomingStore.del(pub, nop)
  1145. that._sendPacket(comp, callback)
  1146. })
  1147. } else {
  1148. that._sendPacket(comp, callback)
  1149. }
  1150. })
  1151. }
  1152. /**
  1153. * _handleDisconnect
  1154. *
  1155. * @param {Object} packet
  1156. * @api private
  1157. */
  1158. MqttClient.prototype._handleDisconnect = function (packet) {
  1159. this.emit('disconnect', packet)
  1160. }
  1161. /**
  1162. * _nextId
  1163. * @return unsigned int
  1164. */
  1165. MqttClient.prototype._nextId = function () {
  1166. // id becomes current state of this.nextId and increments afterwards
  1167. var id = this.nextId++
  1168. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  1169. if (this.nextId === 65536) {
  1170. this.nextId = 1
  1171. }
  1172. return id
  1173. }
  1174. /**
  1175. * getLastMessageId
  1176. * @return unsigned int
  1177. */
  1178. MqttClient.prototype.getLastMessageId = function () {
  1179. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  1180. }
  1181. /**
  1182. * _resubscribe
  1183. * @api private
  1184. */
  1185. MqttClient.prototype._resubscribe = function (connack) {
  1186. var _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
  1187. if (!this._firstConnection &&
  1188. (this.options.clean || (this.options.protocolVersion === 5 && !connack.sessionPresent)) &&
  1189. _resubscribeTopicsKeys.length > 0) {
  1190. if (this.options.resubscribe) {
  1191. if (this.options.protocolVersion === 5) {
  1192. for (var topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
  1193. var resubscribeTopic = {}
  1194. resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
  1195. resubscribeTopic.resubscribe = true
  1196. this.subscribe(resubscribeTopic, {properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})
  1197. }
  1198. } else {
  1199. this._resubscribeTopics.resubscribe = true
  1200. this.subscribe(this._resubscribeTopics)
  1201. }
  1202. } else {
  1203. this._resubscribeTopics = {}
  1204. }
  1205. }
  1206. this._firstConnection = false
  1207. }
  1208. /**
  1209. * _onConnect
  1210. *
  1211. * @api private
  1212. */
  1213. MqttClient.prototype._onConnect = function (packet) {
  1214. if (this.disconnected) {
  1215. this.emit('connect', packet)
  1216. return
  1217. }
  1218. var that = this
  1219. this._setupPingTimer()
  1220. this._resubscribe(packet)
  1221. this.connected = true
  1222. function startStreamProcess () {
  1223. var outStore = that.outgoingStore.createStream()
  1224. function clearStoreProcessing () {
  1225. that._storeProcessing = false
  1226. that._packetIdsDuringStoreProcessing = {}
  1227. }
  1228. that.once('close', remove)
  1229. outStore.on('error', function (err) {
  1230. clearStoreProcessing()
  1231. that.removeListener('close', remove)
  1232. that.emit('error', err)
  1233. })
  1234. function remove () {
  1235. outStore.destroy()
  1236. outStore = null
  1237. clearStoreProcessing()
  1238. }
  1239. function storeDeliver () {
  1240. // edge case, we wrapped this twice
  1241. if (!outStore) {
  1242. return
  1243. }
  1244. that._storeProcessing = true
  1245. var packet = outStore.read(1)
  1246. var cb
  1247. if (!packet) {
  1248. // read when data is available in the future
  1249. outStore.once('readable', storeDeliver)
  1250. return
  1251. }
  1252. // Skip already processed store packets
  1253. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1254. storeDeliver()
  1255. return
  1256. }
  1257. // Avoid unnecessary stream read operations when disconnected
  1258. if (!that.disconnecting && !that.reconnectTimer) {
  1259. cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
  1260. that.outgoing[packet.messageId] = {
  1261. volatile: false,
  1262. cb: function (err, status) {
  1263. // Ensure that the original callback passed in to publish gets invoked
  1264. if (cb) {
  1265. cb(err, status)
  1266. }
  1267. storeDeliver()
  1268. }
  1269. }
  1270. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1271. that._sendPacket(packet)
  1272. } else if (outStore.destroy) {
  1273. outStore.destroy()
  1274. }
  1275. }
  1276. outStore.on('end', function () {
  1277. var allProcessed = true
  1278. for (var id in that._packetIdsDuringStoreProcessing) {
  1279. if (!that._packetIdsDuringStoreProcessing[id]) {
  1280. allProcessed = false
  1281. break
  1282. }
  1283. }
  1284. if (allProcessed) {
  1285. clearStoreProcessing()
  1286. that.removeListener('close', remove)
  1287. that.emit('connect', packet)
  1288. } else {
  1289. startStreamProcess()
  1290. }
  1291. })
  1292. storeDeliver()
  1293. }
  1294. // start flowing
  1295. startStreamProcess()
  1296. }
  1297. module.exports = MqttClient
  1298. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1299. },{"./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){
  1300. (function (Buffer){
  1301. 'use strict'
  1302. var Transform = require('readable-stream').Transform
  1303. var duplexify = require('duplexify')
  1304. var base64 = require('base64-js')
  1305. /* global FileReader */
  1306. var my
  1307. var proxy
  1308. var stream
  1309. var isInitialized = false
  1310. function buildProxy () {
  1311. var proxy = new Transform()
  1312. proxy._write = function (chunk, encoding, next) {
  1313. my.sendSocketMessage({
  1314. data: chunk.buffer,
  1315. success: function () {
  1316. next()
  1317. },
  1318. fail: function () {
  1319. next(new Error())
  1320. }
  1321. })
  1322. }
  1323. proxy._flush = function socketEnd (done) {
  1324. my.closeSocket({
  1325. success: function () {
  1326. done()
  1327. }
  1328. })
  1329. }
  1330. return proxy
  1331. }
  1332. function setDefaultOpts (opts) {
  1333. if (!opts.hostname) {
  1334. opts.hostname = 'localhost'
  1335. }
  1336. if (!opts.path) {
  1337. opts.path = '/'
  1338. }
  1339. if (!opts.wsOptions) {
  1340. opts.wsOptions = {}
  1341. }
  1342. }
  1343. function buildUrl (opts, client) {
  1344. var protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1345. var url = protocol + '://' + opts.hostname + opts.path
  1346. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1347. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1348. }
  1349. if (typeof (opts.transformWsUrl) === 'function') {
  1350. url = opts.transformWsUrl(url, opts, client)
  1351. }
  1352. return url
  1353. }
  1354. function bindEventHandler () {
  1355. if (isInitialized) return
  1356. isInitialized = true
  1357. my.onSocketOpen(function () {
  1358. stream.setReadable(proxy)
  1359. stream.setWritable(proxy)
  1360. stream.emit('connect')
  1361. })
  1362. my.onSocketMessage(function (res) {
  1363. if (typeof res.data === 'string') {
  1364. var array = base64.toByteArray(res.data)
  1365. var buffer = Buffer.from(array)
  1366. proxy.push(buffer)
  1367. } else {
  1368. var reader = new FileReader()
  1369. reader.addEventListener('load', function () {
  1370. var data = reader.result
  1371. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1372. else data = Buffer.from(data, 'utf8')
  1373. proxy.push(data)
  1374. })
  1375. reader.readAsArrayBuffer(res.data)
  1376. }
  1377. })
  1378. my.onSocketClose(function () {
  1379. stream.end()
  1380. stream.destroy()
  1381. })
  1382. my.onSocketError(function (res) {
  1383. stream.destroy(res)
  1384. })
  1385. }
  1386. function buildStream (client, opts) {
  1387. opts.hostname = opts.hostname || opts.host
  1388. if (!opts.hostname) {
  1389. throw new Error('Could not determine host. Specify host manually.')
  1390. }
  1391. var websocketSubProtocol =
  1392. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1393. ? 'mqttv3.1'
  1394. : 'mqtt'
  1395. setDefaultOpts(opts)
  1396. var url = buildUrl(opts, client)
  1397. my = opts.my
  1398. my.connectSocket({
  1399. url: url,
  1400. protocols: websocketSubProtocol
  1401. })
  1402. proxy = buildProxy()
  1403. stream = duplexify.obj()
  1404. bindEventHandler()
  1405. return stream
  1406. }
  1407. module.exports = buildStream
  1408. }).call(this,require("buffer").Buffer)
  1409. },{"base64-js":10,"buffer":12,"duplexify":17,"readable-stream":108}],3:[function(require,module,exports){
  1410. 'use strict'
  1411. var net = require('net')
  1412. /*
  1413. variables port and host can be removed since
  1414. you have all required information in opts object
  1415. */
  1416. function buildBuilder (client, opts) {
  1417. var port, host
  1418. opts.port = opts.port || 1883
  1419. opts.hostname = opts.hostname || opts.host || 'localhost'
  1420. port = opts.port
  1421. host = opts.hostname
  1422. return net.createConnection(port, host)
  1423. }
  1424. module.exports = buildBuilder
  1425. },{"net":11}],4:[function(require,module,exports){
  1426. 'use strict'
  1427. var tls = require('tls')
  1428. function buildBuilder (mqttClient, opts) {
  1429. var connection
  1430. opts.port = opts.port || 8883
  1431. opts.host = opts.hostname || opts.host || 'localhost'
  1432. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1433. delete opts.path
  1434. connection = tls.connect(opts)
  1435. /* eslint no-use-before-define: [2, "nofunc"] */
  1436. connection.on('secureConnect', function () {
  1437. if (opts.rejectUnauthorized && !connection.authorized) {
  1438. connection.emit('error', new Error('TLS not authorized'))
  1439. } else {
  1440. connection.removeListener('error', handleTLSerrors)
  1441. }
  1442. })
  1443. function handleTLSerrors (err) {
  1444. // How can I get verify this error is a tls error?
  1445. if (opts.rejectUnauthorized) {
  1446. mqttClient.emit('error', err)
  1447. }
  1448. // close this connection to match the behaviour of net
  1449. // otherwise all we get is an error from the connection
  1450. // and close event doesn't fire. This is a work around
  1451. // to enable the reconnect code to work the same as with
  1452. // net.createConnection
  1453. connection.end()
  1454. }
  1455. connection.on('error', handleTLSerrors)
  1456. return connection
  1457. }
  1458. module.exports = buildBuilder
  1459. },{"tls":11}],5:[function(require,module,exports){
  1460. (function (process){
  1461. 'use strict'
  1462. var websocket = require('websocket-stream')
  1463. var urlModule = require('url')
  1464. var WSS_OPTIONS = [
  1465. 'rejectUnauthorized',
  1466. 'ca',
  1467. 'cert',
  1468. 'key',
  1469. 'pfx',
  1470. 'passphrase'
  1471. ]
  1472. var IS_BROWSER = process.title === 'browser'
  1473. function buildUrl (opts, client) {
  1474. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1475. if (typeof (opts.transformWsUrl) === 'function') {
  1476. url = opts.transformWsUrl(url, opts, client)
  1477. }
  1478. return url
  1479. }
  1480. function setDefaultOpts (opts) {
  1481. if (!opts.hostname) {
  1482. opts.hostname = 'localhost'
  1483. }
  1484. if (!opts.port) {
  1485. if (opts.protocol === 'wss') {
  1486. opts.port = 443
  1487. } else {
  1488. opts.port = 80
  1489. }
  1490. }
  1491. if (!opts.path) {
  1492. opts.path = '/'
  1493. }
  1494. if (!opts.wsOptions) {
  1495. opts.wsOptions = {}
  1496. }
  1497. if (!IS_BROWSER && opts.protocol === 'wss') {
  1498. // Add cert/key/ca etc options
  1499. WSS_OPTIONS.forEach(function (prop) {
  1500. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  1501. opts.wsOptions[prop] = opts[prop]
  1502. }
  1503. })
  1504. }
  1505. }
  1506. function createWebSocket (client, opts) {
  1507. var websocketSubProtocol =
  1508. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1509. ? 'mqttv3.1'
  1510. : 'mqtt'
  1511. setDefaultOpts(opts)
  1512. var url = buildUrl(opts, client)
  1513. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1514. }
  1515. function buildBuilder (client, opts) {
  1516. return createWebSocket(client, opts)
  1517. }
  1518. function buildBuilderBrowser (client, opts) {
  1519. if (!opts.hostname) {
  1520. opts.hostname = opts.host
  1521. }
  1522. if (!opts.hostname) {
  1523. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1524. // can not determine the `hostname` automatically. If connecting to
  1525. // localhost, please supply the `hostname` as an argument.
  1526. if (typeof (document) === 'undefined') {
  1527. throw new Error('Could not determine host. Specify host manually.')
  1528. }
  1529. var parsed = urlModule.parse(document.URL)
  1530. opts.hostname = parsed.hostname
  1531. if (!opts.port) {
  1532. opts.port = parsed.port
  1533. }
  1534. }
  1535. return createWebSocket(client, opts)
  1536. }
  1537. if (IS_BROWSER) {
  1538. module.exports = buildBuilderBrowser
  1539. } else {
  1540. module.exports = buildBuilder
  1541. }
  1542. }).call(this,require('_process'))
  1543. },{"_process":92,"url":113,"websocket-stream":118}],6:[function(require,module,exports){
  1544. (function (process,Buffer){
  1545. 'use strict'
  1546. var Transform = require('readable-stream').Transform
  1547. var duplexify = require('duplexify')
  1548. /* global wx */
  1549. var socketTask
  1550. var proxy
  1551. var stream
  1552. function buildProxy () {
  1553. var proxy = new Transform()
  1554. proxy._write = function (chunk, encoding, next) {
  1555. socketTask.send({
  1556. data: chunk.buffer,
  1557. success: function () {
  1558. next()
  1559. },
  1560. fail: function (errMsg) {
  1561. next(new Error(errMsg))
  1562. }
  1563. })
  1564. }
  1565. proxy._flush = function socketEnd (done) {
  1566. socketTask.close({
  1567. success: function () {
  1568. done()
  1569. }
  1570. })
  1571. }
  1572. return proxy
  1573. }
  1574. function setDefaultOpts (opts) {
  1575. if (!opts.hostname) {
  1576. opts.hostname = 'localhost'
  1577. }
  1578. if (!opts.path) {
  1579. opts.path = '/'
  1580. }
  1581. if (!opts.wsOptions) {
  1582. opts.wsOptions = {}
  1583. }
  1584. }
  1585. function buildUrl (opts, client) {
  1586. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1587. var url = protocol + '://' + opts.hostname + opts.path
  1588. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1589. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1590. }
  1591. if (typeof (opts.transformWsUrl) === 'function') {
  1592. url = opts.transformWsUrl(url, opts, client)
  1593. }
  1594. return url
  1595. }
  1596. function bindEventHandler () {
  1597. socketTask.onOpen(function () {
  1598. stream.setReadable(proxy)
  1599. stream.setWritable(proxy)
  1600. stream.emit('connect')
  1601. })
  1602. socketTask.onMessage(function (res) {
  1603. var data = res.data
  1604. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1605. else data = Buffer.from(data, 'utf8')
  1606. proxy.push(data)
  1607. })
  1608. socketTask.onClose(function () {
  1609. stream.end()
  1610. stream.destroy()
  1611. })
  1612. socketTask.onError(function (res) {
  1613. stream.destroy(new Error(res.errMsg))
  1614. })
  1615. }
  1616. function buildStream (client, opts) {
  1617. opts.hostname = opts.hostname || opts.host
  1618. if (!opts.hostname) {
  1619. throw new Error('Could not determine host. Specify host manually.')
  1620. }
  1621. var websocketSubProtocol =
  1622. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1623. ? 'mqttv3.1'
  1624. : 'mqtt'
  1625. setDefaultOpts(opts)
  1626. var url = buildUrl(opts, client)
  1627. socketTask = wx.connectSocket({
  1628. url: url,
  1629. protocols: websocketSubProtocol
  1630. })
  1631. proxy = buildProxy()
  1632. stream = duplexify.obj()
  1633. stream._destroy = function (err, cb) {
  1634. socketTask.close({
  1635. success: function () {
  1636. cb && cb(err)
  1637. }
  1638. })
  1639. }
  1640. var destroyRef = stream.destroy
  1641. stream.destroy = function () {
  1642. stream.destroy = destroyRef
  1643. var self = this
  1644. process.nextTick(function () {
  1645. socketTask.close({
  1646. fail: function () {
  1647. self._destroy(new Error())
  1648. }
  1649. })
  1650. })
  1651. }.bind(stream)
  1652. bindEventHandler()
  1653. return stream
  1654. }
  1655. module.exports = buildStream
  1656. }).call(this,require('_process'),require("buffer").Buffer)
  1657. },{"_process":92,"buffer":12,"duplexify":17,"readable-stream":108}],7:[function(require,module,exports){
  1658. (function (process){
  1659. 'use strict'
  1660. /**
  1661. * Module dependencies
  1662. */
  1663. var xtend = require('xtend')
  1664. var Readable = require('readable-stream').Readable
  1665. var streamsOpts = { objectMode: true }
  1666. var defaultStoreOptions = {
  1667. clean: true
  1668. }
  1669. /**
  1670. * es6-map can preserve insertion order even if ES version is older.
  1671. *
  1672. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
  1673. * It should be noted that a Map which is a map of an object, especially
  1674. * a dictionary of dictionaries, will only map to the object's insertion
  1675. * order. In ES2015 this is ordered for objects but for older versions of
  1676. * ES, this may be random and not ordered.
  1677. *
  1678. */
  1679. var Map = require('es6-map')
  1680. /**
  1681. * In-memory implementation of the message store
  1682. * This can actually be saved into files.
  1683. *
  1684. * @param {Object} [options] - store options
  1685. */
  1686. function Store (options) {
  1687. if (!(this instanceof Store)) {
  1688. return new Store(options)
  1689. }
  1690. this.options = options || {}
  1691. // Defaults
  1692. this.options = xtend(defaultStoreOptions, options)
  1693. this._inflights = new Map()
  1694. }
  1695. /**
  1696. * Adds a packet to the store, a packet is
  1697. * anything that has a messageId property.
  1698. *
  1699. */
  1700. Store.prototype.put = function (packet, cb) {
  1701. this._inflights.set(packet.messageId, packet)
  1702. if (cb) {
  1703. cb()
  1704. }
  1705. return this
  1706. }
  1707. /**
  1708. * Creates a stream with all the packets in the store
  1709. *
  1710. */
  1711. Store.prototype.createStream = function () {
  1712. var stream = new Readable(streamsOpts)
  1713. var destroyed = false
  1714. var values = []
  1715. var i = 0
  1716. this._inflights.forEach(function (value, key) {
  1717. values.push(value)
  1718. })
  1719. stream._read = function () {
  1720. if (!destroyed && i < values.length) {
  1721. this.push(values[i++])
  1722. } else {
  1723. this.push(null)
  1724. }
  1725. }
  1726. stream.destroy = function () {
  1727. if (destroyed) {
  1728. return
  1729. }
  1730. var self = this
  1731. destroyed = true
  1732. process.nextTick(function () {
  1733. self.emit('close')
  1734. })
  1735. }
  1736. return stream
  1737. }
  1738. /**
  1739. * deletes a packet from the store.
  1740. */
  1741. Store.prototype.del = function (packet, cb) {
  1742. packet = this._inflights.get(packet.messageId)
  1743. if (packet) {
  1744. this._inflights.delete(packet.messageId)
  1745. cb(null, packet)
  1746. } else if (cb) {
  1747. cb(new Error('missing packet'))
  1748. }
  1749. return this
  1750. }
  1751. /**
  1752. * get a packet from the store.
  1753. */
  1754. Store.prototype.get = function (packet, cb) {
  1755. packet = this._inflights.get(packet.messageId)
  1756. if (packet) {
  1757. cb(null, packet)
  1758. } else if (cb) {
  1759. cb(new Error('missing packet'))
  1760. }
  1761. return this
  1762. }
  1763. /**
  1764. * Close the store
  1765. */
  1766. Store.prototype.close = function (cb) {
  1767. if (this.options.clean) {
  1768. this._inflights = null
  1769. }
  1770. if (cb) {
  1771. cb()
  1772. }
  1773. }
  1774. module.exports = Store
  1775. }).call(this,require('_process'))
  1776. },{"_process":92,"es6-map":67,"readable-stream":108,"xtend":121}],8:[function(require,module,exports){
  1777. 'use strict'
  1778. /**
  1779. * Validate a topic to see if it's valid or not.
  1780. * A topic is valid if it follow below rules:
  1781. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1782. * - Rule #2: Part `#` must be located at the end of the mailbox
  1783. *
  1784. * @param {String} topic - A topic
  1785. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1786. */
  1787. function validateTopic (topic) {
  1788. var parts = topic.split('/')
  1789. for (var i = 0; i < parts.length; i++) {
  1790. if (parts[i] === '+') {
  1791. continue
  1792. }
  1793. if (parts[i] === '#') {
  1794. // for Rule #2
  1795. return i === parts.length - 1
  1796. }
  1797. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1798. return false
  1799. }
  1800. }
  1801. return true
  1802. }
  1803. /**
  1804. * Validate an array of topics to see if any of them is valid or not
  1805. * @param {Array} topics - Array of topics
  1806. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1807. */
  1808. function validateTopics (topics) {
  1809. if (topics.length === 0) {
  1810. return 'empty_topic_list'
  1811. }
  1812. for (var i = 0; i < topics.length; i++) {
  1813. if (!validateTopic(topics[i])) {
  1814. return topics[i]
  1815. }
  1816. }
  1817. return null
  1818. }
  1819. module.exports = {
  1820. validateTopics: validateTopics
  1821. }
  1822. },{}],9:[function(require,module,exports){
  1823. (function (process){
  1824. 'use strict'
  1825. var MqttClient = require('../client')
  1826. var Store = require('../store')
  1827. var url = require('url')
  1828. var xtend = require('xtend')
  1829. var protocols = {}
  1830. if (process.title !== 'browser') {
  1831. protocols.mqtt = require('./tcp')
  1832. protocols.tcp = require('./tcp')
  1833. protocols.ssl = require('./tls')
  1834. protocols.tls = require('./tls')
  1835. protocols.mqtts = require('./tls')
  1836. } else {
  1837. protocols.wx = require('./wx')
  1838. protocols.wxs = require('./wx')
  1839. protocols.ali = require('./ali')
  1840. protocols.alis = require('./ali')
  1841. }
  1842. protocols.ws = require('./ws')
  1843. protocols.wss = require('./ws')
  1844. /**
  1845. * Parse the auth attribute and merge username and password in the options object.
  1846. *
  1847. * @param {Object} [opts] option object
  1848. */
  1849. function parseAuthOptions (opts) {
  1850. var matches
  1851. if (opts.auth) {
  1852. matches = opts.auth.match(/^(.+):(.+)$/)
  1853. if (matches) {
  1854. opts.username = matches[1]
  1855. opts.password = matches[2]
  1856. } else {
  1857. opts.username = opts.auth
  1858. }
  1859. }
  1860. }
  1861. /**
  1862. * connect - connect to an MQTT broker.
  1863. *
  1864. * @param {String} [brokerUrl] - url of the broker, optional
  1865. * @param {Object} opts - see MqttClient#constructor
  1866. */
  1867. function connect (brokerUrl, opts) {
  1868. if ((typeof brokerUrl === 'object') && !opts) {
  1869. opts = brokerUrl
  1870. brokerUrl = null
  1871. }
  1872. opts = opts || {}
  1873. if (brokerUrl) {
  1874. var parsed = url.parse(brokerUrl, true)
  1875. if (parsed.port != null) {
  1876. parsed.port = Number(parsed.port)
  1877. }
  1878. opts = xtend(parsed, opts)
  1879. if (opts.protocol === null) {
  1880. throw new Error('Missing protocol')
  1881. }
  1882. opts.protocol = opts.protocol.replace(/:$/, '')
  1883. }
  1884. // merge in the auth options if supplied
  1885. parseAuthOptions(opts)
  1886. // support clientId passed in the query string of the url
  1887. if (opts.query && typeof opts.query.clientId === 'string') {
  1888. opts.clientId = opts.query.clientId
  1889. }
  1890. if (opts.cert && opts.key) {
  1891. if (opts.protocol) {
  1892. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  1893. switch (opts.protocol) {
  1894. case 'mqtt':
  1895. opts.protocol = 'mqtts'
  1896. break
  1897. case 'ws':
  1898. opts.protocol = 'wss'
  1899. break
  1900. case 'wx':
  1901. opts.protocol = 'wxs'
  1902. break
  1903. case 'ali':
  1904. opts.protocol = 'alis'
  1905. break
  1906. default:
  1907. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  1908. }
  1909. }
  1910. } else {
  1911. // don't know what protocol he want to use, mqtts or wss
  1912. throw new Error('Missing secure protocol key')
  1913. }
  1914. }
  1915. if (!protocols[opts.protocol]) {
  1916. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  1917. opts.protocol = [
  1918. 'mqtt',
  1919. 'mqtts',
  1920. 'ws',
  1921. 'wss',
  1922. 'wx',
  1923. 'wxs',
  1924. 'ali',
  1925. 'alis'
  1926. ].filter(function (key, index) {
  1927. if (isSecure && index % 2 === 0) {
  1928. // Skip insecure protocols when requesting a secure one.
  1929. return false
  1930. }
  1931. return (typeof protocols[key] === 'function')
  1932. })[0]
  1933. }
  1934. if (opts.clean === false && !opts.clientId) {
  1935. throw new Error('Missing clientId for unclean clients')
  1936. }
  1937. if (opts.protocol) {
  1938. opts.defaultProtocol = opts.protocol
  1939. }
  1940. function wrapper (client) {
  1941. if (opts.servers) {
  1942. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  1943. client._reconnectCount = 0
  1944. }
  1945. opts.host = opts.servers[client._reconnectCount].host
  1946. opts.port = opts.servers[client._reconnectCount].port
  1947. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  1948. opts.hostname = opts.host
  1949. client._reconnectCount++
  1950. }
  1951. return protocols[opts.protocol](client, opts)
  1952. }
  1953. return new MqttClient(wrapper, opts)
  1954. }
  1955. module.exports = connect
  1956. module.exports.connect = connect
  1957. module.exports.MqttClient = MqttClient
  1958. module.exports.Store = Store
  1959. }).call(this,require('_process'))
  1960. },{"../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){
  1961. 'use strict'
  1962. exports.byteLength = byteLength
  1963. exports.toByteArray = toByteArray
  1964. exports.fromByteArray = fromByteArray
  1965. var lookup = []
  1966. var revLookup = []
  1967. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1968. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1969. for (var i = 0, len = code.length; i < len; ++i) {
  1970. lookup[i] = code[i]
  1971. revLookup[code.charCodeAt(i)] = i
  1972. }
  1973. // Support decoding URL-safe base64 strings, as Node.js does.
  1974. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  1975. revLookup['-'.charCodeAt(0)] = 62
  1976. revLookup['_'.charCodeAt(0)] = 63
  1977. function getLens (b64) {
  1978. var len = b64.length
  1979. if (len % 4 > 0) {
  1980. throw new Error('Invalid string. Length must be a multiple of 4')
  1981. }
  1982. // Trim off extra bytes after placeholder bytes are found
  1983. // See: https://github.com/beatgammit/base64-js/issues/42
  1984. var validLen = b64.indexOf('=')
  1985. if (validLen === -1) validLen = len
  1986. var placeHoldersLen = validLen === len
  1987. ? 0
  1988. : 4 - (validLen % 4)
  1989. return [validLen, placeHoldersLen]
  1990. }
  1991. // base64 is 4/3 + up to two characters of the original data
  1992. function byteLength (b64) {
  1993. var lens = getLens(b64)
  1994. var validLen = lens[0]
  1995. var placeHoldersLen = lens[1]
  1996. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1997. }
  1998. function _byteLength (b64, validLen, placeHoldersLen) {
  1999. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2000. }
  2001. function toByteArray (b64) {
  2002. var tmp
  2003. var lens = getLens(b64)
  2004. var validLen = lens[0]
  2005. var placeHoldersLen = lens[1]
  2006. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2007. var curByte = 0
  2008. // if there are placeholders, only get up to the last complete 4 chars
  2009. var len = placeHoldersLen > 0
  2010. ? validLen - 4
  2011. : validLen
  2012. for (var i = 0; i < len; i += 4) {
  2013. tmp =
  2014. (revLookup[b64.charCodeAt(i)] << 18) |
  2015. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2016. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2017. revLookup[b64.charCodeAt(i + 3)]
  2018. arr[curByte++] = (tmp >> 16) & 0xFF
  2019. arr[curByte++] = (tmp >> 8) & 0xFF
  2020. arr[curByte++] = tmp & 0xFF
  2021. }
  2022. if (placeHoldersLen === 2) {
  2023. tmp =
  2024. (revLookup[b64.charCodeAt(i)] << 2) |
  2025. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2026. arr[curByte++] = tmp & 0xFF
  2027. }
  2028. if (placeHoldersLen === 1) {
  2029. tmp =
  2030. (revLookup[b64.charCodeAt(i)] << 10) |
  2031. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2032. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2033. arr[curByte++] = (tmp >> 8) & 0xFF
  2034. arr[curByte++] = tmp & 0xFF
  2035. }
  2036. return arr
  2037. }
  2038. function tripletToBase64 (num) {
  2039. return lookup[num >> 18 & 0x3F] +
  2040. lookup[num >> 12 & 0x3F] +
  2041. lookup[num >> 6 & 0x3F] +
  2042. lookup[num & 0x3F]
  2043. }
  2044. function encodeChunk (uint8, start, end) {
  2045. var tmp
  2046. var output = []
  2047. for (var i = start; i < end; i += 3) {
  2048. tmp =
  2049. ((uint8[i] << 16) & 0xFF0000) +
  2050. ((uint8[i + 1] << 8) & 0xFF00) +
  2051. (uint8[i + 2] & 0xFF)
  2052. output.push(tripletToBase64(tmp))
  2053. }
  2054. return output.join('')
  2055. }
  2056. function fromByteArray (uint8) {
  2057. var tmp
  2058. var len = uint8.length
  2059. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2060. var parts = []
  2061. var maxChunkLength = 16383 // must be multiple of 3
  2062. // go through the array every three bytes, we'll deal with trailing stuff later
  2063. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2064. parts.push(encodeChunk(
  2065. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2066. ))
  2067. }
  2068. // pad the end with zeros, but make sure to not forget the extra bytes
  2069. if (extraBytes === 1) {
  2070. tmp = uint8[len - 1]
  2071. parts.push(
  2072. lookup[tmp >> 2] +
  2073. lookup[(tmp << 4) & 0x3F] +
  2074. '=='
  2075. )
  2076. } else if (extraBytes === 2) {
  2077. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2078. parts.push(
  2079. lookup[tmp >> 10] +
  2080. lookup[(tmp >> 4) & 0x3F] +
  2081. lookup[(tmp << 2) & 0x3F] +
  2082. '='
  2083. )
  2084. }
  2085. return parts.join('')
  2086. }
  2087. },{}],11:[function(require,module,exports){
  2088. },{}],12:[function(require,module,exports){
  2089. /*!
  2090. * The buffer module from node.js, for the browser.
  2091. *
  2092. * @author Feross Aboukhadijeh <https://feross.org>
  2093. * @license MIT
  2094. */
  2095. /* eslint-disable no-proto */
  2096. 'use strict'
  2097. var base64 = require('base64-js')
  2098. var ieee754 = require('ieee754')
  2099. exports.Buffer = Buffer
  2100. exports.SlowBuffer = SlowBuffer
  2101. exports.INSPECT_MAX_BYTES = 50
  2102. var K_MAX_LENGTH = 0x7fffffff
  2103. exports.kMaxLength = K_MAX_LENGTH
  2104. /**
  2105. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2106. * === true Use Uint8Array implementation (fastest)
  2107. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2108. * implementation (most compatible, even IE6)
  2109. *
  2110. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2111. * Opera 11.6+, iOS 4.2+.
  2112. *
  2113. * We report that the browser does not support typed arrays if the are not subclassable
  2114. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2115. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2116. * for __proto__ and has a buggy typed array implementation.
  2117. */
  2118. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2119. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2120. typeof console.error === 'function') {
  2121. console.error(
  2122. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2123. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2124. )
  2125. }
  2126. function typedArraySupport () {
  2127. // Can typed array instances can be augmented?
  2128. try {
  2129. var arr = new Uint8Array(1)
  2130. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2131. return arr.foo() === 42
  2132. } catch (e) {
  2133. return false
  2134. }
  2135. }
  2136. Object.defineProperty(Buffer.prototype, 'parent', {
  2137. enumerable: true,
  2138. get: function () {
  2139. if (!Buffer.isBuffer(this)) return undefined
  2140. return this.buffer
  2141. }
  2142. })
  2143. Object.defineProperty(Buffer.prototype, 'offset', {
  2144. enumerable: true,
  2145. get: function () {
  2146. if (!Buffer.isBuffer(this)) return undefined
  2147. return this.byteOffset
  2148. }
  2149. })
  2150. function createBuffer (length) {
  2151. if (length > K_MAX_LENGTH) {
  2152. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2153. }
  2154. // Return an augmented `Uint8Array` instance
  2155. var buf = new Uint8Array(length)
  2156. buf.__proto__ = Buffer.prototype
  2157. return buf
  2158. }
  2159. /**
  2160. * The Buffer constructor returns instances of `Uint8Array` that have their
  2161. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2162. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2163. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2164. * returns a single octet.
  2165. *
  2166. * The `Uint8Array` prototype remains unmodified.
  2167. */
  2168. function Buffer (arg, encodingOrOffset, length) {
  2169. // Common case.
  2170. if (typeof arg === 'number') {
  2171. if (typeof encodingOrOffset === 'string') {
  2172. throw new TypeError(
  2173. 'The "string" argument must be of type string. Received type number'
  2174. )
  2175. }
  2176. return allocUnsafe(arg)
  2177. }
  2178. return from(arg, encodingOrOffset, length)
  2179. }
  2180. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2181. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2182. Buffer[Symbol.species] === Buffer) {
  2183. Object.defineProperty(Buffer, Symbol.species, {
  2184. value: null,
  2185. configurable: true,
  2186. enumerable: false,
  2187. writable: false
  2188. })
  2189. }
  2190. Buffer.poolSize = 8192 // not used by this implementation
  2191. function from (value, encodingOrOffset, length) {
  2192. if (typeof value === 'string') {
  2193. return fromString(value, encodingOrOffset)
  2194. }
  2195. if (ArrayBuffer.isView(value)) {
  2196. return fromArrayLike(value)
  2197. }
  2198. if (value == null) {
  2199. throw TypeError(
  2200. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2201. 'or Array-like Object. Received type ' + (typeof value)
  2202. )
  2203. }
  2204. if (isInstance(value, ArrayBuffer) ||
  2205. (value && isInstance(value.buffer, ArrayBuffer))) {
  2206. return fromArrayBuffer(value, encodingOrOffset, length)
  2207. }
  2208. if (typeof value === 'number') {
  2209. throw new TypeError(
  2210. 'The "value" argument must not be of type number. Received type number'
  2211. )
  2212. }
  2213. var valueOf = value.valueOf && value.valueOf()
  2214. if (valueOf != null && valueOf !== value) {
  2215. return Buffer.from(valueOf, encodingOrOffset, length)
  2216. }
  2217. var b = fromObject(value)
  2218. if (b) return b
  2219. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2220. typeof value[Symbol.toPrimitive] === 'function') {
  2221. return Buffer.from(
  2222. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2223. )
  2224. }
  2225. throw new TypeError(
  2226. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2227. 'or Array-like Object. Received type ' + (typeof value)
  2228. )
  2229. }
  2230. /**
  2231. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2232. * if value is a number.
  2233. * Buffer.from(str[, encoding])
  2234. * Buffer.from(array)
  2235. * Buffer.from(buffer)
  2236. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2237. **/
  2238. Buffer.from = function (value, encodingOrOffset, length) {
  2239. return from(value, encodingOrOffset, length)
  2240. }
  2241. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2242. // https://github.com/feross/buffer/pull/148
  2243. Buffer.prototype.__proto__ = Uint8Array.prototype
  2244. Buffer.__proto__ = Uint8Array
  2245. function assertSize (size) {
  2246. if (typeof size !== 'number') {
  2247. throw new TypeError('"size" argument must be of type number')
  2248. } else if (size < 0) {
  2249. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2250. }
  2251. }
  2252. function alloc (size, fill, encoding) {
  2253. assertSize(size)
  2254. if (size <= 0) {
  2255. return createBuffer(size)
  2256. }
  2257. if (fill !== undefined) {
  2258. // Only pay attention to encoding if it's a string. This
  2259. // prevents accidentally sending in a number that would
  2260. // be interpretted as a start offset.
  2261. return typeof encoding === 'string'
  2262. ? createBuffer(size).fill(fill, encoding)
  2263. : createBuffer(size).fill(fill)
  2264. }
  2265. return createBuffer(size)
  2266. }
  2267. /**
  2268. * Creates a new filled Buffer instance.
  2269. * alloc(size[, fill[, encoding]])
  2270. **/
  2271. Buffer.alloc = function (size, fill, encoding) {
  2272. return alloc(size, fill, encoding)
  2273. }
  2274. function allocUnsafe (size) {
  2275. assertSize(size)
  2276. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2277. }
  2278. /**
  2279. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2280. * */
  2281. Buffer.allocUnsafe = function (size) {
  2282. return allocUnsafe(size)
  2283. }
  2284. /**
  2285. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2286. */
  2287. Buffer.allocUnsafeSlow = function (size) {
  2288. return allocUnsafe(size)
  2289. }
  2290. function fromString (string, encoding) {
  2291. if (typeof encoding !== 'string' || encoding === '') {
  2292. encoding = 'utf8'
  2293. }
  2294. if (!Buffer.isEncoding(encoding)) {
  2295. throw new TypeError('Unknown encoding: ' + encoding)
  2296. }
  2297. var length = byteLength(string, encoding) | 0
  2298. var buf = createBuffer(length)
  2299. var actual = buf.write(string, encoding)
  2300. if (actual !== length) {
  2301. // Writing a hex string, for example, that contains invalid characters will
  2302. // cause everything after the first invalid character to be ignored. (e.g.
  2303. // 'abxxcd' will be treated as 'ab')
  2304. buf = buf.slice(0, actual)
  2305. }
  2306. return buf
  2307. }
  2308. function fromArrayLike (array) {
  2309. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2310. var buf = createBuffer(length)
  2311. for (var i = 0; i < length; i += 1) {
  2312. buf[i] = array[i] & 255
  2313. }
  2314. return buf
  2315. }
  2316. function fromArrayBuffer (array, byteOffset, length) {
  2317. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2318. throw new RangeError('"offset" is outside of buffer bounds')
  2319. }
  2320. if (array.byteLength < byteOffset + (length || 0)) {
  2321. throw new RangeError('"length" is outside of buffer bounds')
  2322. }
  2323. var buf
  2324. if (byteOffset === undefined && length === undefined) {
  2325. buf = new Uint8Array(array)
  2326. } else if (length === undefined) {
  2327. buf = new Uint8Array(array, byteOffset)
  2328. } else {
  2329. buf = new Uint8Array(array, byteOffset, length)
  2330. }
  2331. // Return an augmented `Uint8Array` instance
  2332. buf.__proto__ = Buffer.prototype
  2333. return buf
  2334. }
  2335. function fromObject (obj) {
  2336. if (Buffer.isBuffer(obj)) {
  2337. var len = checked(obj.length) | 0
  2338. var buf = createBuffer(len)
  2339. if (buf.length === 0) {
  2340. return buf
  2341. }
  2342. obj.copy(buf, 0, 0, len)
  2343. return buf
  2344. }
  2345. if (obj.length !== undefined) {
  2346. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2347. return createBuffer(0)
  2348. }
  2349. return fromArrayLike(obj)
  2350. }
  2351. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2352. return fromArrayLike(obj.data)
  2353. }
  2354. }
  2355. function checked (length) {
  2356. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2357. // length is NaN (which is otherwise coerced to zero.)
  2358. if (length >= K_MAX_LENGTH) {
  2359. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2360. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2361. }
  2362. return length | 0
  2363. }
  2364. function SlowBuffer (length) {
  2365. if (+length != length) { // eslint-disable-line eqeqeq
  2366. length = 0
  2367. }
  2368. return Buffer.alloc(+length)
  2369. }
  2370. Buffer.isBuffer = function isBuffer (b) {
  2371. return b != null && b._isBuffer === true &&
  2372. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2373. }
  2374. Buffer.compare = function compare (a, b) {
  2375. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2376. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2377. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2378. throw new TypeError(
  2379. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2380. )
  2381. }
  2382. if (a === b) return 0
  2383. var x = a.length
  2384. var y = b.length
  2385. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2386. if (a[i] !== b[i]) {
  2387. x = a[i]
  2388. y = b[i]
  2389. break
  2390. }
  2391. }
  2392. if (x < y) return -1
  2393. if (y < x) return 1
  2394. return 0
  2395. }
  2396. Buffer.isEncoding = function isEncoding (encoding) {
  2397. switch (String(encoding).toLowerCase()) {
  2398. case 'hex':
  2399. case 'utf8':
  2400. case 'utf-8':
  2401. case 'ascii':
  2402. case 'latin1':
  2403. case 'binary':
  2404. case 'base64':
  2405. case 'ucs2':
  2406. case 'ucs-2':
  2407. case 'utf16le':
  2408. case 'utf-16le':
  2409. return true
  2410. default:
  2411. return false
  2412. }
  2413. }
  2414. Buffer.concat = function concat (list, length) {
  2415. if (!Array.isArray(list)) {
  2416. throw new TypeError('"list" argument must be an Array of Buffers')
  2417. }
  2418. if (list.length === 0) {
  2419. return Buffer.alloc(0)
  2420. }
  2421. var i
  2422. if (length === undefined) {
  2423. length = 0
  2424. for (i = 0; i < list.length; ++i) {
  2425. length += list[i].length
  2426. }
  2427. }
  2428. var buffer = Buffer.allocUnsafe(length)
  2429. var pos = 0
  2430. for (i = 0; i < list.length; ++i) {
  2431. var buf = list[i]
  2432. if (isInstance(buf, Uint8Array)) {
  2433. buf = Buffer.from(buf)
  2434. }
  2435. if (!Buffer.isBuffer(buf)) {
  2436. throw new TypeError('"list" argument must be an Array of Buffers')
  2437. }
  2438. buf.copy(buffer, pos)
  2439. pos += buf.length
  2440. }
  2441. return buffer
  2442. }
  2443. function byteLength (string, encoding) {
  2444. if (Buffer.isBuffer(string)) {
  2445. return string.length
  2446. }
  2447. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2448. return string.byteLength
  2449. }
  2450. if (typeof string !== 'string') {
  2451. throw new TypeError(
  2452. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2453. 'Received type ' + typeof string
  2454. )
  2455. }
  2456. var len = string.length
  2457. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2458. if (!mustMatch && len === 0) return 0
  2459. // Use a for loop to avoid recursion
  2460. var loweredCase = false
  2461. for (;;) {
  2462. switch (encoding) {
  2463. case 'ascii':
  2464. case 'latin1':
  2465. case 'binary':
  2466. return len
  2467. case 'utf8':
  2468. case 'utf-8':
  2469. return utf8ToBytes(string).length
  2470. case 'ucs2':
  2471. case 'ucs-2':
  2472. case 'utf16le':
  2473. case 'utf-16le':
  2474. return len * 2
  2475. case 'hex':
  2476. return len >>> 1
  2477. case 'base64':
  2478. return base64ToBytes(string).length
  2479. default:
  2480. if (loweredCase) {
  2481. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2482. }
  2483. encoding = ('' + encoding).toLowerCase()
  2484. loweredCase = true
  2485. }
  2486. }
  2487. }
  2488. Buffer.byteLength = byteLength
  2489. function slowToString (encoding, start, end) {
  2490. var loweredCase = false
  2491. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2492. // property of a typed array.
  2493. // This behaves neither like String nor Uint8Array in that we set start/end
  2494. // to their upper/lower bounds if the value passed is out of range.
  2495. // undefined is handled specially as per ECMA-262 6th Edition,
  2496. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2497. if (start === undefined || start < 0) {
  2498. start = 0
  2499. }
  2500. // Return early if start > this.length. Done here to prevent potential uint32
  2501. // coercion fail below.
  2502. if (start > this.length) {
  2503. return ''
  2504. }
  2505. if (end === undefined || end > this.length) {
  2506. end = this.length
  2507. }
  2508. if (end <= 0) {
  2509. return ''
  2510. }
  2511. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2512. end >>>= 0
  2513. start >>>= 0
  2514. if (end <= start) {
  2515. return ''
  2516. }
  2517. if (!encoding) encoding = 'utf8'
  2518. while (true) {
  2519. switch (encoding) {
  2520. case 'hex':
  2521. return hexSlice(this, start, end)
  2522. case 'utf8':
  2523. case 'utf-8':
  2524. return utf8Slice(this, start, end)
  2525. case 'ascii':
  2526. return asciiSlice(this, start, end)
  2527. case 'latin1':
  2528. case 'binary':
  2529. return latin1Slice(this, start, end)
  2530. case 'base64':
  2531. return base64Slice(this, start, end)
  2532. case 'ucs2':
  2533. case 'ucs-2':
  2534. case 'utf16le':
  2535. case 'utf-16le':
  2536. return utf16leSlice(this, start, end)
  2537. default:
  2538. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2539. encoding = (encoding + '').toLowerCase()
  2540. loweredCase = true
  2541. }
  2542. }
  2543. }
  2544. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2545. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2546. // reliably in a browserify context because there could be multiple different
  2547. // copies of the 'buffer' package in use. This method works even for Buffer
  2548. // instances that were created from another copy of the `buffer` package.
  2549. // See: https://github.com/feross/buffer/issues/154
  2550. Buffer.prototype._isBuffer = true
  2551. function swap (b, n, m) {
  2552. var i = b[n]
  2553. b[n] = b[m]
  2554. b[m] = i
  2555. }
  2556. Buffer.prototype.swap16 = function swap16 () {
  2557. var len = this.length
  2558. if (len % 2 !== 0) {
  2559. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2560. }
  2561. for (var i = 0; i < len; i += 2) {
  2562. swap(this, i, i + 1)
  2563. }
  2564. return this
  2565. }
  2566. Buffer.prototype.swap32 = function swap32 () {
  2567. var len = this.length
  2568. if (len % 4 !== 0) {
  2569. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2570. }
  2571. for (var i = 0; i < len; i += 4) {
  2572. swap(this, i, i + 3)
  2573. swap(this, i + 1, i + 2)
  2574. }
  2575. return this
  2576. }
  2577. Buffer.prototype.swap64 = function swap64 () {
  2578. var len = this.length
  2579. if (len % 8 !== 0) {
  2580. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2581. }
  2582. for (var i = 0; i < len; i += 8) {
  2583. swap(this, i, i + 7)
  2584. swap(this, i + 1, i + 6)
  2585. swap(this, i + 2, i + 5)
  2586. swap(this, i + 3, i + 4)
  2587. }
  2588. return this
  2589. }
  2590. Buffer.prototype.toString = function toString () {
  2591. var length = this.length
  2592. if (length === 0) return ''
  2593. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2594. return slowToString.apply(this, arguments)
  2595. }
  2596. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2597. Buffer.prototype.equals = function equals (b) {
  2598. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2599. if (this === b) return true
  2600. return Buffer.compare(this, b) === 0
  2601. }
  2602. Buffer.prototype.inspect = function inspect () {
  2603. var str = ''
  2604. var max = exports.INSPECT_MAX_BYTES
  2605. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2606. if (this.length > max) str += ' ... '
  2607. return '<Buffer ' + str + '>'
  2608. }
  2609. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2610. if (isInstance(target, Uint8Array)) {
  2611. target = Buffer.from(target, target.offset, target.byteLength)
  2612. }
  2613. if (!Buffer.isBuffer(target)) {
  2614. throw new TypeError(
  2615. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2616. 'Received type ' + (typeof target)
  2617. )
  2618. }
  2619. if (start === undefined) {
  2620. start = 0
  2621. }
  2622. if (end === undefined) {
  2623. end = target ? target.length : 0
  2624. }
  2625. if (thisStart === undefined) {
  2626. thisStart = 0
  2627. }
  2628. if (thisEnd === undefined) {
  2629. thisEnd = this.length
  2630. }
  2631. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2632. throw new RangeError('out of range index')
  2633. }
  2634. if (thisStart >= thisEnd && start >= end) {
  2635. return 0
  2636. }
  2637. if (thisStart >= thisEnd) {
  2638. return -1
  2639. }
  2640. if (start >= end) {
  2641. return 1
  2642. }
  2643. start >>>= 0
  2644. end >>>= 0
  2645. thisStart >>>= 0
  2646. thisEnd >>>= 0
  2647. if (this === target) return 0
  2648. var x = thisEnd - thisStart
  2649. var y = end - start
  2650. var len = Math.min(x, y)
  2651. var thisCopy = this.slice(thisStart, thisEnd)
  2652. var targetCopy = target.slice(start, end)
  2653. for (var i = 0; i < len; ++i) {
  2654. if (thisCopy[i] !== targetCopy[i]) {
  2655. x = thisCopy[i]
  2656. y = targetCopy[i]
  2657. break
  2658. }
  2659. }
  2660. if (x < y) return -1
  2661. if (y < x) return 1
  2662. return 0
  2663. }
  2664. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2665. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2666. //
  2667. // Arguments:
  2668. // - buffer - a Buffer to search
  2669. // - val - a string, Buffer, or number
  2670. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2671. // - encoding - an optional encoding, relevant is val is a string
  2672. // - dir - true for indexOf, false for lastIndexOf
  2673. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2674. // Empty buffer means no match
  2675. if (buffer.length === 0) return -1
  2676. // Normalize byteOffset
  2677. if (typeof byteOffset === 'string') {
  2678. encoding = byteOffset
  2679. byteOffset = 0
  2680. } else if (byteOffset > 0x7fffffff) {
  2681. byteOffset = 0x7fffffff
  2682. } else if (byteOffset < -0x80000000) {
  2683. byteOffset = -0x80000000
  2684. }
  2685. byteOffset = +byteOffset // Coerce to Number.
  2686. if (numberIsNaN(byteOffset)) {
  2687. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2688. byteOffset = dir ? 0 : (buffer.length - 1)
  2689. }
  2690. // Normalize byteOffset: negative offsets start from the end of the buffer
  2691. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2692. if (byteOffset >= buffer.length) {
  2693. if (dir) return -1
  2694. else byteOffset = buffer.length - 1
  2695. } else if (byteOffset < 0) {
  2696. if (dir) byteOffset = 0
  2697. else return -1
  2698. }
  2699. // Normalize val
  2700. if (typeof val === 'string') {
  2701. val = Buffer.from(val, encoding)
  2702. }
  2703. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2704. if (Buffer.isBuffer(val)) {
  2705. // Special case: looking for empty string/buffer always fails
  2706. if (val.length === 0) {
  2707. return -1
  2708. }
  2709. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2710. } else if (typeof val === 'number') {
  2711. val = val & 0xFF // Search for a byte value [0-255]
  2712. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2713. if (dir) {
  2714. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2715. } else {
  2716. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2717. }
  2718. }
  2719. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2720. }
  2721. throw new TypeError('val must be string, number or Buffer')
  2722. }
  2723. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2724. var indexSize = 1
  2725. var arrLength = arr.length
  2726. var valLength = val.length
  2727. if (encoding !== undefined) {
  2728. encoding = String(encoding).toLowerCase()
  2729. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2730. encoding === 'utf16le' || encoding === 'utf-16le') {
  2731. if (arr.length < 2 || val.length < 2) {
  2732. return -1
  2733. }
  2734. indexSize = 2
  2735. arrLength /= 2
  2736. valLength /= 2
  2737. byteOffset /= 2
  2738. }
  2739. }
  2740. function read (buf, i) {
  2741. if (indexSize === 1) {
  2742. return buf[i]
  2743. } else {
  2744. return buf.readUInt16BE(i * indexSize)
  2745. }
  2746. }
  2747. var i
  2748. if (dir) {
  2749. var foundIndex = -1
  2750. for (i = byteOffset; i < arrLength; i++) {
  2751. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2752. if (foundIndex === -1) foundIndex = i
  2753. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2754. } else {
  2755. if (foundIndex !== -1) i -= i - foundIndex
  2756. foundIndex = -1
  2757. }
  2758. }
  2759. } else {
  2760. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2761. for (i = byteOffset; i >= 0; i--) {
  2762. var found = true
  2763. for (var j = 0; j < valLength; j++) {
  2764. if (read(arr, i + j) !== read(val, j)) {
  2765. found = false
  2766. break
  2767. }
  2768. }
  2769. if (found) return i
  2770. }
  2771. }
  2772. return -1
  2773. }
  2774. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2775. return this.indexOf(val, byteOffset, encoding) !== -1
  2776. }
  2777. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2778. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2779. }
  2780. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2781. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2782. }
  2783. function hexWrite (buf, string, offset, length) {
  2784. offset = Number(offset) || 0
  2785. var remaining = buf.length - offset
  2786. if (!length) {
  2787. length = remaining
  2788. } else {
  2789. length = Number(length)
  2790. if (length > remaining) {
  2791. length = remaining
  2792. }
  2793. }
  2794. var strLen = string.length
  2795. if (length > strLen / 2) {
  2796. length = strLen / 2
  2797. }
  2798. for (var i = 0; i < length; ++i) {
  2799. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2800. if (numberIsNaN(parsed)) return i
  2801. buf[offset + i] = parsed
  2802. }
  2803. return i
  2804. }
  2805. function utf8Write (buf, string, offset, length) {
  2806. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2807. }
  2808. function asciiWrite (buf, string, offset, length) {
  2809. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2810. }
  2811. function latin1Write (buf, string, offset, length) {
  2812. return asciiWrite(buf, string, offset, length)
  2813. }
  2814. function base64Write (buf, string, offset, length) {
  2815. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2816. }
  2817. function ucs2Write (buf, string, offset, length) {
  2818. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2819. }
  2820. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2821. // Buffer#write(string)
  2822. if (offset === undefined) {
  2823. encoding = 'utf8'
  2824. length = this.length
  2825. offset = 0
  2826. // Buffer#write(string, encoding)
  2827. } else if (length === undefined && typeof offset === 'string') {
  2828. encoding = offset
  2829. length = this.length
  2830. offset = 0
  2831. // Buffer#write(string, offset[, length][, encoding])
  2832. } else if (isFinite(offset)) {
  2833. offset = offset >>> 0
  2834. if (isFinite(length)) {
  2835. length = length >>> 0
  2836. if (encoding === undefined) encoding = 'utf8'
  2837. } else {
  2838. encoding = length
  2839. length = undefined
  2840. }
  2841. } else {
  2842. throw new Error(
  2843. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2844. )
  2845. }
  2846. var remaining = this.length - offset
  2847. if (length === undefined || length > remaining) length = remaining
  2848. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2849. throw new RangeError('Attempt to write outside buffer bounds')
  2850. }
  2851. if (!encoding) encoding = 'utf8'
  2852. var loweredCase = false
  2853. for (;;) {
  2854. switch (encoding) {
  2855. case 'hex':
  2856. return hexWrite(this, string, offset, length)
  2857. case 'utf8':
  2858. case 'utf-8':
  2859. return utf8Write(this, string, offset, length)
  2860. case 'ascii':
  2861. return asciiWrite(this, string, offset, length)
  2862. case 'latin1':
  2863. case 'binary':
  2864. return latin1Write(this, string, offset, length)
  2865. case 'base64':
  2866. // Warning: maxLength not taken into account in base64Write
  2867. return base64Write(this, string, offset, length)
  2868. case 'ucs2':
  2869. case 'ucs-2':
  2870. case 'utf16le':
  2871. case 'utf-16le':
  2872. return ucs2Write(this, string, offset, length)
  2873. default:
  2874. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2875. encoding = ('' + encoding).toLowerCase()
  2876. loweredCase = true
  2877. }
  2878. }
  2879. }
  2880. Buffer.prototype.toJSON = function toJSON () {
  2881. return {
  2882. type: 'Buffer',
  2883. data: Array.prototype.slice.call(this._arr || this, 0)
  2884. }
  2885. }
  2886. function base64Slice (buf, start, end) {
  2887. if (start === 0 && end === buf.length) {
  2888. return base64.fromByteArray(buf)
  2889. } else {
  2890. return base64.fromByteArray(buf.slice(start, end))
  2891. }
  2892. }
  2893. function utf8Slice (buf, start, end) {
  2894. end = Math.min(buf.length, end)
  2895. var res = []
  2896. var i = start
  2897. while (i < end) {
  2898. var firstByte = buf[i]
  2899. var codePoint = null
  2900. var bytesPerSequence = (firstByte > 0xEF) ? 4
  2901. : (firstByte > 0xDF) ? 3
  2902. : (firstByte > 0xBF) ? 2
  2903. : 1
  2904. if (i + bytesPerSequence <= end) {
  2905. var secondByte, thirdByte, fourthByte, tempCodePoint
  2906. switch (bytesPerSequence) {
  2907. case 1:
  2908. if (firstByte < 0x80) {
  2909. codePoint = firstByte
  2910. }
  2911. break
  2912. case 2:
  2913. secondByte = buf[i + 1]
  2914. if ((secondByte & 0xC0) === 0x80) {
  2915. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  2916. if (tempCodePoint > 0x7F) {
  2917. codePoint = tempCodePoint
  2918. }
  2919. }
  2920. break
  2921. case 3:
  2922. secondByte = buf[i + 1]
  2923. thirdByte = buf[i + 2]
  2924. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  2925. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  2926. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  2927. codePoint = tempCodePoint
  2928. }
  2929. }
  2930. break
  2931. case 4:
  2932. secondByte = buf[i + 1]
  2933. thirdByte = buf[i + 2]
  2934. fourthByte = buf[i + 3]
  2935. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  2936. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  2937. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  2938. codePoint = tempCodePoint
  2939. }
  2940. }
  2941. }
  2942. }
  2943. if (codePoint === null) {
  2944. // we did not generate a valid codePoint so insert a
  2945. // replacement char (U+FFFD) and advance only 1 byte
  2946. codePoint = 0xFFFD
  2947. bytesPerSequence = 1
  2948. } else if (codePoint > 0xFFFF) {
  2949. // encode to utf16 (surrogate pair dance)
  2950. codePoint -= 0x10000
  2951. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  2952. codePoint = 0xDC00 | codePoint & 0x3FF
  2953. }
  2954. res.push(codePoint)
  2955. i += bytesPerSequence
  2956. }
  2957. return decodeCodePointsArray(res)
  2958. }
  2959. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  2960. // the lowest limit is Chrome, with 0x10000 args.
  2961. // We go 1 magnitude less, for safety
  2962. var MAX_ARGUMENTS_LENGTH = 0x1000
  2963. function decodeCodePointsArray (codePoints) {
  2964. var len = codePoints.length
  2965. if (len <= MAX_ARGUMENTS_LENGTH) {
  2966. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  2967. }
  2968. // Decode in chunks to avoid "call stack size exceeded".
  2969. var res = ''
  2970. var i = 0
  2971. while (i < len) {
  2972. res += String.fromCharCode.apply(
  2973. String,
  2974. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  2975. )
  2976. }
  2977. return res
  2978. }
  2979. function asciiSlice (buf, start, end) {
  2980. var ret = ''
  2981. end = Math.min(buf.length, end)
  2982. for (var i = start; i < end; ++i) {
  2983. ret += String.fromCharCode(buf[i] & 0x7F)
  2984. }
  2985. return ret
  2986. }
  2987. function latin1Slice (buf, start, end) {
  2988. var ret = ''
  2989. end = Math.min(buf.length, end)
  2990. for (var i = start; i < end; ++i) {
  2991. ret += String.fromCharCode(buf[i])
  2992. }
  2993. return ret
  2994. }
  2995. function hexSlice (buf, start, end) {
  2996. var len = buf.length
  2997. if (!start || start < 0) start = 0
  2998. if (!end || end < 0 || end > len) end = len
  2999. var out = ''
  3000. for (var i = start; i < end; ++i) {
  3001. out += toHex(buf[i])
  3002. }
  3003. return out
  3004. }
  3005. function utf16leSlice (buf, start, end) {
  3006. var bytes = buf.slice(start, end)
  3007. var res = ''
  3008. for (var i = 0; i < bytes.length; i += 2) {
  3009. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3010. }
  3011. return res
  3012. }
  3013. Buffer.prototype.slice = function slice (start, end) {
  3014. var len = this.length
  3015. start = ~~start
  3016. end = end === undefined ? len : ~~end
  3017. if (start < 0) {
  3018. start += len
  3019. if (start < 0) start = 0
  3020. } else if (start > len) {
  3021. start = len
  3022. }
  3023. if (end < 0) {
  3024. end += len
  3025. if (end < 0) end = 0
  3026. } else if (end > len) {
  3027. end = len
  3028. }
  3029. if (end < start) end = start
  3030. var newBuf = this.subarray(start, end)
  3031. // Return an augmented `Uint8Array` instance
  3032. newBuf.__proto__ = Buffer.prototype
  3033. return newBuf
  3034. }
  3035. /*
  3036. * Need to make sure that buffer isn't trying to write out of bounds.
  3037. */
  3038. function checkOffset (offset, ext, length) {
  3039. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3040. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3041. }
  3042. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3043. offset = offset >>> 0
  3044. byteLength = byteLength >>> 0
  3045. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3046. var val = this[offset]
  3047. var mul = 1
  3048. var i = 0
  3049. while (++i < byteLength && (mul *= 0x100)) {
  3050. val += this[offset + i] * mul
  3051. }
  3052. return val
  3053. }
  3054. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3055. offset = offset >>> 0
  3056. byteLength = byteLength >>> 0
  3057. if (!noAssert) {
  3058. checkOffset(offset, byteLength, this.length)
  3059. }
  3060. var val = this[offset + --byteLength]
  3061. var mul = 1
  3062. while (byteLength > 0 && (mul *= 0x100)) {
  3063. val += this[offset + --byteLength] * mul
  3064. }
  3065. return val
  3066. }
  3067. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3068. offset = offset >>> 0
  3069. if (!noAssert) checkOffset(offset, 1, this.length)
  3070. return this[offset]
  3071. }
  3072. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3073. offset = offset >>> 0
  3074. if (!noAssert) checkOffset(offset, 2, this.length)
  3075. return this[offset] | (this[offset + 1] << 8)
  3076. }
  3077. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3078. offset = offset >>> 0
  3079. if (!noAssert) checkOffset(offset, 2, this.length)
  3080. return (this[offset] << 8) | this[offset + 1]
  3081. }
  3082. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3083. offset = offset >>> 0
  3084. if (!noAssert) checkOffset(offset, 4, this.length)
  3085. return ((this[offset]) |
  3086. (this[offset + 1] << 8) |
  3087. (this[offset + 2] << 16)) +
  3088. (this[offset + 3] * 0x1000000)
  3089. }
  3090. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3091. offset = offset >>> 0
  3092. if (!noAssert) checkOffset(offset, 4, this.length)
  3093. return (this[offset] * 0x1000000) +
  3094. ((this[offset + 1] << 16) |
  3095. (this[offset + 2] << 8) |
  3096. this[offset + 3])
  3097. }
  3098. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3099. offset = offset >>> 0
  3100. byteLength = byteLength >>> 0
  3101. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3102. var val = this[offset]
  3103. var mul = 1
  3104. var i = 0
  3105. while (++i < byteLength && (mul *= 0x100)) {
  3106. val += this[offset + i] * mul
  3107. }
  3108. mul *= 0x80
  3109. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3110. return val
  3111. }
  3112. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3113. offset = offset >>> 0
  3114. byteLength = byteLength >>> 0
  3115. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3116. var i = byteLength
  3117. var mul = 1
  3118. var val = this[offset + --i]
  3119. while (i > 0 && (mul *= 0x100)) {
  3120. val += this[offset + --i] * mul
  3121. }
  3122. mul *= 0x80
  3123. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3124. return val
  3125. }
  3126. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3127. offset = offset >>> 0
  3128. if (!noAssert) checkOffset(offset, 1, this.length)
  3129. if (!(this[offset] & 0x80)) return (this[offset])
  3130. return ((0xff - this[offset] + 1) * -1)
  3131. }
  3132. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3133. offset = offset >>> 0
  3134. if (!noAssert) checkOffset(offset, 2, this.length)
  3135. var val = this[offset] | (this[offset + 1] << 8)
  3136. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3137. }
  3138. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3139. offset = offset >>> 0
  3140. if (!noAssert) checkOffset(offset, 2, this.length)
  3141. var val = this[offset + 1] | (this[offset] << 8)
  3142. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3143. }
  3144. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3145. offset = offset >>> 0
  3146. if (!noAssert) checkOffset(offset, 4, this.length)
  3147. return (this[offset]) |
  3148. (this[offset + 1] << 8) |
  3149. (this[offset + 2] << 16) |
  3150. (this[offset + 3] << 24)
  3151. }
  3152. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3153. offset = offset >>> 0
  3154. if (!noAssert) checkOffset(offset, 4, this.length)
  3155. return (this[offset] << 24) |
  3156. (this[offset + 1] << 16) |
  3157. (this[offset + 2] << 8) |
  3158. (this[offset + 3])
  3159. }
  3160. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3161. offset = offset >>> 0
  3162. if (!noAssert) checkOffset(offset, 4, this.length)
  3163. return ieee754.read(this, offset, true, 23, 4)
  3164. }
  3165. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3166. offset = offset >>> 0
  3167. if (!noAssert) checkOffset(offset, 4, this.length)
  3168. return ieee754.read(this, offset, false, 23, 4)
  3169. }
  3170. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3171. offset = offset >>> 0
  3172. if (!noAssert) checkOffset(offset, 8, this.length)
  3173. return ieee754.read(this, offset, true, 52, 8)
  3174. }
  3175. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3176. offset = offset >>> 0
  3177. if (!noAssert) checkOffset(offset, 8, this.length)
  3178. return ieee754.read(this, offset, false, 52, 8)
  3179. }
  3180. function checkInt (buf, value, offset, ext, max, min) {
  3181. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3182. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3183. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3184. }
  3185. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3186. value = +value
  3187. offset = offset >>> 0
  3188. byteLength = byteLength >>> 0
  3189. if (!noAssert) {
  3190. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3191. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3192. }
  3193. var mul = 1
  3194. var i = 0
  3195. this[offset] = value & 0xFF
  3196. while (++i < byteLength && (mul *= 0x100)) {
  3197. this[offset + i] = (value / mul) & 0xFF
  3198. }
  3199. return offset + byteLength
  3200. }
  3201. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3202. value = +value
  3203. offset = offset >>> 0
  3204. byteLength = byteLength >>> 0
  3205. if (!noAssert) {
  3206. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3207. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3208. }
  3209. var i = byteLength - 1
  3210. var mul = 1
  3211. this[offset + i] = value & 0xFF
  3212. while (--i >= 0 && (mul *= 0x100)) {
  3213. this[offset + i] = (value / mul) & 0xFF
  3214. }
  3215. return offset + byteLength
  3216. }
  3217. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3218. value = +value
  3219. offset = offset >>> 0
  3220. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3221. this[offset] = (value & 0xff)
  3222. return offset + 1
  3223. }
  3224. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3225. value = +value
  3226. offset = offset >>> 0
  3227. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3228. this[offset] = (value & 0xff)
  3229. this[offset + 1] = (value >>> 8)
  3230. return offset + 2
  3231. }
  3232. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3233. value = +value
  3234. offset = offset >>> 0
  3235. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3236. this[offset] = (value >>> 8)
  3237. this[offset + 1] = (value & 0xff)
  3238. return offset + 2
  3239. }
  3240. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3241. value = +value
  3242. offset = offset >>> 0
  3243. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3244. this[offset + 3] = (value >>> 24)
  3245. this[offset + 2] = (value >>> 16)
  3246. this[offset + 1] = (value >>> 8)
  3247. this[offset] = (value & 0xff)
  3248. return offset + 4
  3249. }
  3250. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3251. value = +value
  3252. offset = offset >>> 0
  3253. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3254. this[offset] = (value >>> 24)
  3255. this[offset + 1] = (value >>> 16)
  3256. this[offset + 2] = (value >>> 8)
  3257. this[offset + 3] = (value & 0xff)
  3258. return offset + 4
  3259. }
  3260. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3261. value = +value
  3262. offset = offset >>> 0
  3263. if (!noAssert) {
  3264. var limit = Math.pow(2, (8 * byteLength) - 1)
  3265. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3266. }
  3267. var i = 0
  3268. var mul = 1
  3269. var sub = 0
  3270. this[offset] = value & 0xFF
  3271. while (++i < byteLength && (mul *= 0x100)) {
  3272. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3273. sub = 1
  3274. }
  3275. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3276. }
  3277. return offset + byteLength
  3278. }
  3279. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3280. value = +value
  3281. offset = offset >>> 0
  3282. if (!noAssert) {
  3283. var limit = Math.pow(2, (8 * byteLength) - 1)
  3284. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3285. }
  3286. var i = byteLength - 1
  3287. var mul = 1
  3288. var sub = 0
  3289. this[offset + i] = value & 0xFF
  3290. while (--i >= 0 && (mul *= 0x100)) {
  3291. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3292. sub = 1
  3293. }
  3294. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3295. }
  3296. return offset + byteLength
  3297. }
  3298. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3299. value = +value
  3300. offset = offset >>> 0
  3301. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3302. if (value < 0) value = 0xff + value + 1
  3303. this[offset] = (value & 0xff)
  3304. return offset + 1
  3305. }
  3306. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3307. value = +value
  3308. offset = offset >>> 0
  3309. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3310. this[offset] = (value & 0xff)
  3311. this[offset + 1] = (value >>> 8)
  3312. return offset + 2
  3313. }
  3314. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3315. value = +value
  3316. offset = offset >>> 0
  3317. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3318. this[offset] = (value >>> 8)
  3319. this[offset + 1] = (value & 0xff)
  3320. return offset + 2
  3321. }
  3322. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3323. value = +value
  3324. offset = offset >>> 0
  3325. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3326. this[offset] = (value & 0xff)
  3327. this[offset + 1] = (value >>> 8)
  3328. this[offset + 2] = (value >>> 16)
  3329. this[offset + 3] = (value >>> 24)
  3330. return offset + 4
  3331. }
  3332. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3333. value = +value
  3334. offset = offset >>> 0
  3335. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3336. if (value < 0) value = 0xffffffff + value + 1
  3337. this[offset] = (value >>> 24)
  3338. this[offset + 1] = (value >>> 16)
  3339. this[offset + 2] = (value >>> 8)
  3340. this[offset + 3] = (value & 0xff)
  3341. return offset + 4
  3342. }
  3343. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3344. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3345. if (offset < 0) throw new RangeError('Index out of range')
  3346. }
  3347. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3348. value = +value
  3349. offset = offset >>> 0
  3350. if (!noAssert) {
  3351. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3352. }
  3353. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3354. return offset + 4
  3355. }
  3356. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3357. return writeFloat(this, value, offset, true, noAssert)
  3358. }
  3359. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3360. return writeFloat(this, value, offset, false, noAssert)
  3361. }
  3362. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3363. value = +value
  3364. offset = offset >>> 0
  3365. if (!noAssert) {
  3366. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3367. }
  3368. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3369. return offset + 8
  3370. }
  3371. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3372. return writeDouble(this, value, offset, true, noAssert)
  3373. }
  3374. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3375. return writeDouble(this, value, offset, false, noAssert)
  3376. }
  3377. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3378. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3379. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3380. if (!start) start = 0
  3381. if (!end && end !== 0) end = this.length
  3382. if (targetStart >= target.length) targetStart = target.length
  3383. if (!targetStart) targetStart = 0
  3384. if (end > 0 && end < start) end = start
  3385. // Copy 0 bytes; we're done
  3386. if (end === start) return 0
  3387. if (target.length === 0 || this.length === 0) return 0
  3388. // Fatal error conditions
  3389. if (targetStart < 0) {
  3390. throw new RangeError('targetStart out of bounds')
  3391. }
  3392. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3393. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3394. // Are we oob?
  3395. if (end > this.length) end = this.length
  3396. if (target.length - targetStart < end - start) {
  3397. end = target.length - targetStart + start
  3398. }
  3399. var len = end - start
  3400. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3401. // Use built-in when available, missing from IE11
  3402. this.copyWithin(targetStart, start, end)
  3403. } else if (this === target && start < targetStart && targetStart < end) {
  3404. // descending copy from end
  3405. for (var i = len - 1; i >= 0; --i) {
  3406. target[i + targetStart] = this[i + start]
  3407. }
  3408. } else {
  3409. Uint8Array.prototype.set.call(
  3410. target,
  3411. this.subarray(start, end),
  3412. targetStart
  3413. )
  3414. }
  3415. return len
  3416. }
  3417. // Usage:
  3418. // buffer.fill(number[, offset[, end]])
  3419. // buffer.fill(buffer[, offset[, end]])
  3420. // buffer.fill(string[, offset[, end]][, encoding])
  3421. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3422. // Handle string cases:
  3423. if (typeof val === 'string') {
  3424. if (typeof start === 'string') {
  3425. encoding = start
  3426. start = 0
  3427. end = this.length
  3428. } else if (typeof end === 'string') {
  3429. encoding = end
  3430. end = this.length
  3431. }
  3432. if (encoding !== undefined && typeof encoding !== 'string') {
  3433. throw new TypeError('encoding must be a string')
  3434. }
  3435. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3436. throw new TypeError('Unknown encoding: ' + encoding)
  3437. }
  3438. if (val.length === 1) {
  3439. var code = val.charCodeAt(0)
  3440. if ((encoding === 'utf8' && code < 128) ||
  3441. encoding === 'latin1') {
  3442. // Fast path: If `val` fits into a single byte, use that numeric value.
  3443. val = code
  3444. }
  3445. }
  3446. } else if (typeof val === 'number') {
  3447. val = val & 255
  3448. }
  3449. // Invalid ranges are not set to a default, so can range check early.
  3450. if (start < 0 || this.length < start || this.length < end) {
  3451. throw new RangeError('Out of range index')
  3452. }
  3453. if (end <= start) {
  3454. return this
  3455. }
  3456. start = start >>> 0
  3457. end = end === undefined ? this.length : end >>> 0
  3458. if (!val) val = 0
  3459. var i
  3460. if (typeof val === 'number') {
  3461. for (i = start; i < end; ++i) {
  3462. this[i] = val
  3463. }
  3464. } else {
  3465. var bytes = Buffer.isBuffer(val)
  3466. ? val
  3467. : Buffer.from(val, encoding)
  3468. var len = bytes.length
  3469. if (len === 0) {
  3470. throw new TypeError('The value "' + val +
  3471. '" is invalid for argument "value"')
  3472. }
  3473. for (i = 0; i < end - start; ++i) {
  3474. this[i + start] = bytes[i % len]
  3475. }
  3476. }
  3477. return this
  3478. }
  3479. // HELPER FUNCTIONS
  3480. // ================
  3481. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3482. function base64clean (str) {
  3483. // Node takes equal signs as end of the Base64 encoding
  3484. str = str.split('=')[0]
  3485. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3486. str = str.trim().replace(INVALID_BASE64_RE, '')
  3487. // Node converts strings with length < 2 to ''
  3488. if (str.length < 2) return ''
  3489. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3490. while (str.length % 4 !== 0) {
  3491. str = str + '='
  3492. }
  3493. return str
  3494. }
  3495. function toHex (n) {
  3496. if (n < 16) return '0' + n.toString(16)
  3497. return n.toString(16)
  3498. }
  3499. function utf8ToBytes (string, units) {
  3500. units = units || Infinity
  3501. var codePoint
  3502. var length = string.length
  3503. var leadSurrogate = null
  3504. var bytes = []
  3505. for (var i = 0; i < length; ++i) {
  3506. codePoint = string.charCodeAt(i)
  3507. // is surrogate component
  3508. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3509. // last char was a lead
  3510. if (!leadSurrogate) {
  3511. // no lead yet
  3512. if (codePoint > 0xDBFF) {
  3513. // unexpected trail
  3514. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3515. continue
  3516. } else if (i + 1 === length) {
  3517. // unpaired lead
  3518. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3519. continue
  3520. }
  3521. // valid lead
  3522. leadSurrogate = codePoint
  3523. continue
  3524. }
  3525. // 2 leads in a row
  3526. if (codePoint < 0xDC00) {
  3527. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3528. leadSurrogate = codePoint
  3529. continue
  3530. }
  3531. // valid surrogate pair
  3532. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3533. } else if (leadSurrogate) {
  3534. // valid bmp char, but last char was a lead
  3535. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3536. }
  3537. leadSurrogate = null
  3538. // encode utf8
  3539. if (codePoint < 0x80) {
  3540. if ((units -= 1) < 0) break
  3541. bytes.push(codePoint)
  3542. } else if (codePoint < 0x800) {
  3543. if ((units -= 2) < 0) break
  3544. bytes.push(
  3545. codePoint >> 0x6 | 0xC0,
  3546. codePoint & 0x3F | 0x80
  3547. )
  3548. } else if (codePoint < 0x10000) {
  3549. if ((units -= 3) < 0) break
  3550. bytes.push(
  3551. codePoint >> 0xC | 0xE0,
  3552. codePoint >> 0x6 & 0x3F | 0x80,
  3553. codePoint & 0x3F | 0x80
  3554. )
  3555. } else if (codePoint < 0x110000) {
  3556. if ((units -= 4) < 0) break
  3557. bytes.push(
  3558. codePoint >> 0x12 | 0xF0,
  3559. codePoint >> 0xC & 0x3F | 0x80,
  3560. codePoint >> 0x6 & 0x3F | 0x80,
  3561. codePoint & 0x3F | 0x80
  3562. )
  3563. } else {
  3564. throw new Error('Invalid code point')
  3565. }
  3566. }
  3567. return bytes
  3568. }
  3569. function asciiToBytes (str) {
  3570. var byteArray = []
  3571. for (var i = 0; i < str.length; ++i) {
  3572. // Node's code seems to be doing this and not & 0x7F..
  3573. byteArray.push(str.charCodeAt(i) & 0xFF)
  3574. }
  3575. return byteArray
  3576. }
  3577. function utf16leToBytes (str, units) {
  3578. var c, hi, lo
  3579. var byteArray = []
  3580. for (var i = 0; i < str.length; ++i) {
  3581. if ((units -= 2) < 0) break
  3582. c = str.charCodeAt(i)
  3583. hi = c >> 8
  3584. lo = c % 256
  3585. byteArray.push(lo)
  3586. byteArray.push(hi)
  3587. }
  3588. return byteArray
  3589. }
  3590. function base64ToBytes (str) {
  3591. return base64.toByteArray(base64clean(str))
  3592. }
  3593. function blitBuffer (src, dst, offset, length) {
  3594. for (var i = 0; i < length; ++i) {
  3595. if ((i + offset >= dst.length) || (i >= src.length)) break
  3596. dst[i + offset] = src[i]
  3597. }
  3598. return i
  3599. }
  3600. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3601. // the `instanceof` check but they should be treated as of that type.
  3602. // See: https://github.com/feross/buffer/issues/166
  3603. function isInstance (obj, type) {
  3604. return obj instanceof type ||
  3605. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3606. obj.constructor.name === type.name)
  3607. }
  3608. function numberIsNaN (obj) {
  3609. // For IE11 support
  3610. return obj !== obj // eslint-disable-line no-self-compare
  3611. }
  3612. },{"base64-js":10,"ieee754":79}],13:[function(require,module,exports){
  3613. // Copyright Joyent, Inc. and other Node contributors.
  3614. //
  3615. // Permission is hereby granted, free of charge, to any person obtaining a
  3616. // copy of this software and associated documentation files (the
  3617. // "Software"), to deal in the Software without restriction, including
  3618. // without limitation the rights to use, copy, modify, merge, publish,
  3619. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3620. // persons to whom the Software is furnished to do so, subject to the
  3621. // following conditions:
  3622. //
  3623. // The above copyright notice and this permission notice shall be included
  3624. // in all copies or substantial portions of the Software.
  3625. //
  3626. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3627. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3628. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3629. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3630. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3631. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3632. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3633. var objectCreate = Object.create || objectCreatePolyfill
  3634. var objectKeys = Object.keys || objectKeysPolyfill
  3635. var bind = Function.prototype.bind || functionBindPolyfill
  3636. function EventEmitter() {
  3637. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  3638. this._events = objectCreate(null);
  3639. this._eventsCount = 0;
  3640. }
  3641. this._maxListeners = this._maxListeners || undefined;
  3642. }
  3643. module.exports = EventEmitter;
  3644. // Backwards-compat with node 0.10.x
  3645. EventEmitter.EventEmitter = EventEmitter;
  3646. EventEmitter.prototype._events = undefined;
  3647. EventEmitter.prototype._maxListeners = undefined;
  3648. // By default EventEmitters will print a warning if more than 10 listeners are
  3649. // added to it. This is a useful default which helps finding memory leaks.
  3650. var defaultMaxListeners = 10;
  3651. var hasDefineProperty;
  3652. try {
  3653. var o = {};
  3654. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  3655. hasDefineProperty = o.x === 0;
  3656. } catch (err) { hasDefineProperty = false }
  3657. if (hasDefineProperty) {
  3658. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  3659. enumerable: true,
  3660. get: function() {
  3661. return defaultMaxListeners;
  3662. },
  3663. set: function(arg) {
  3664. // check whether the input is a positive number (whose value is zero or
  3665. // greater and not a NaN).
  3666. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  3667. throw new TypeError('"defaultMaxListeners" must be a positive number');
  3668. defaultMaxListeners = arg;
  3669. }
  3670. });
  3671. } else {
  3672. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  3673. }
  3674. // Obviously not all Emitters should be limited to 10. This function allows
  3675. // that to be increased. Set to zero for unlimited.
  3676. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  3677. if (typeof n !== 'number' || n < 0 || isNaN(n))
  3678. throw new TypeError('"n" argument must be a positive number');
  3679. this._maxListeners = n;
  3680. return this;
  3681. };
  3682. function $getMaxListeners(that) {
  3683. if (that._maxListeners === undefined)
  3684. return EventEmitter.defaultMaxListeners;
  3685. return that._maxListeners;
  3686. }
  3687. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  3688. return $getMaxListeners(this);
  3689. };
  3690. // These standalone emit* functions are used to optimize calling of event
  3691. // handlers for fast cases because emit() itself often has a variable number of
  3692. // arguments and can be deoptimized because of that. These functions always have
  3693. // the same number of arguments and thus do not get deoptimized, so the code
  3694. // inside them can execute faster.
  3695. function emitNone(handler, isFn, self) {
  3696. if (isFn)
  3697. handler.call(self);
  3698. else {
  3699. var len = handler.length;
  3700. var listeners = arrayClone(handler, len);
  3701. for (var i = 0; i < len; ++i)
  3702. listeners[i].call(self);
  3703. }
  3704. }
  3705. function emitOne(handler, isFn, self, arg1) {
  3706. if (isFn)
  3707. handler.call(self, arg1);
  3708. else {
  3709. var len = handler.length;
  3710. var listeners = arrayClone(handler, len);
  3711. for (var i = 0; i < len; ++i)
  3712. listeners[i].call(self, arg1);
  3713. }
  3714. }
  3715. function emitTwo(handler, isFn, self, arg1, arg2) {
  3716. if (isFn)
  3717. handler.call(self, arg1, arg2);
  3718. else {
  3719. var len = handler.length;
  3720. var listeners = arrayClone(handler, len);
  3721. for (var i = 0; i < len; ++i)
  3722. listeners[i].call(self, arg1, arg2);
  3723. }
  3724. }
  3725. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  3726. if (isFn)
  3727. handler.call(self, arg1, arg2, arg3);
  3728. else {
  3729. var len = handler.length;
  3730. var listeners = arrayClone(handler, len);
  3731. for (var i = 0; i < len; ++i)
  3732. listeners[i].call(self, arg1, arg2, arg3);
  3733. }
  3734. }
  3735. function emitMany(handler, isFn, self, args) {
  3736. if (isFn)
  3737. handler.apply(self, args);
  3738. else {
  3739. var len = handler.length;
  3740. var listeners = arrayClone(handler, len);
  3741. for (var i = 0; i < len; ++i)
  3742. listeners[i].apply(self, args);
  3743. }
  3744. }
  3745. EventEmitter.prototype.emit = function emit(type) {
  3746. var er, handler, len, args, i, events;
  3747. var doError = (type === 'error');
  3748. events = this._events;
  3749. if (events)
  3750. doError = (doError && events.error == null);
  3751. else if (!doError)
  3752. return false;
  3753. // If there is no 'error' event listener then throw.
  3754. if (doError) {
  3755. if (arguments.length > 1)
  3756. er = arguments[1];
  3757. if (er instanceof Error) {
  3758. throw er; // Unhandled 'error' event
  3759. } else {
  3760. // At least give some kind of context to the user
  3761. var err = new Error('Unhandled "error" event. (' + er + ')');
  3762. err.context = er;
  3763. throw err;
  3764. }
  3765. return false;
  3766. }
  3767. handler = events[type];
  3768. if (!handler)
  3769. return false;
  3770. var isFn = typeof handler === 'function';
  3771. len = arguments.length;
  3772. switch (len) {
  3773. // fast cases
  3774. case 1:
  3775. emitNone(handler, isFn, this);
  3776. break;
  3777. case 2:
  3778. emitOne(handler, isFn, this, arguments[1]);
  3779. break;
  3780. case 3:
  3781. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  3782. break;
  3783. case 4:
  3784. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  3785. break;
  3786. // slower
  3787. default:
  3788. args = new Array(len - 1);
  3789. for (i = 1; i < len; i++)
  3790. args[i - 1] = arguments[i];
  3791. emitMany(handler, isFn, this, args);
  3792. }
  3793. return true;
  3794. };
  3795. function _addListener(target, type, listener, prepend) {
  3796. var m;
  3797. var events;
  3798. var existing;
  3799. if (typeof listener !== 'function')
  3800. throw new TypeError('"listener" argument must be a function');
  3801. events = target._events;
  3802. if (!events) {
  3803. events = target._events = objectCreate(null);
  3804. target._eventsCount = 0;
  3805. } else {
  3806. // To avoid recursion in the case that type === "newListener"! Before
  3807. // adding it to the listeners, first emit "newListener".
  3808. if (events.newListener) {
  3809. target.emit('newListener', type,
  3810. listener.listener ? listener.listener : listener);
  3811. // Re-assign `events` because a newListener handler could have caused the
  3812. // this._events to be assigned to a new object
  3813. events = target._events;
  3814. }
  3815. existing = events[type];
  3816. }
  3817. if (!existing) {
  3818. // Optimize the case of one listener. Don't need the extra array object.
  3819. existing = events[type] = listener;
  3820. ++target._eventsCount;
  3821. } else {
  3822. if (typeof existing === 'function') {
  3823. // Adding the second element, need to change to array.
  3824. existing = events[type] =
  3825. prepend ? [listener, existing] : [existing, listener];
  3826. } else {
  3827. // If we've already got an array, just append.
  3828. if (prepend) {
  3829. existing.unshift(listener);
  3830. } else {
  3831. existing.push(listener);
  3832. }
  3833. }
  3834. // Check for listener leak
  3835. if (!existing.warned) {
  3836. m = $getMaxListeners(target);
  3837. if (m && m > 0 && existing.length > m) {
  3838. existing.warned = true;
  3839. var w = new Error('Possible EventEmitter memory leak detected. ' +
  3840. existing.length + ' "' + String(type) + '" listeners ' +
  3841. 'added. Use emitter.setMaxListeners() to ' +
  3842. 'increase limit.');
  3843. w.name = 'MaxListenersExceededWarning';
  3844. w.emitter = target;
  3845. w.type = type;
  3846. w.count = existing.length;
  3847. if (typeof console === 'object' && console.warn) {
  3848. console.warn('%s: %s', w.name, w.message);
  3849. }
  3850. }
  3851. }
  3852. }
  3853. return target;
  3854. }
  3855. EventEmitter.prototype.addListener = function addListener(type, listener) {
  3856. return _addListener(this, type, listener, false);
  3857. };
  3858. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  3859. EventEmitter.prototype.prependListener =
  3860. function prependListener(type, listener) {
  3861. return _addListener(this, type, listener, true);
  3862. };
  3863. function onceWrapper() {
  3864. if (!this.fired) {
  3865. this.target.removeListener(this.type, this.wrapFn);
  3866. this.fired = true;
  3867. switch (arguments.length) {
  3868. case 0:
  3869. return this.listener.call(this.target);
  3870. case 1:
  3871. return this.listener.call(this.target, arguments[0]);
  3872. case 2:
  3873. return this.listener.call(this.target, arguments[0], arguments[1]);
  3874. case 3:
  3875. return this.listener.call(this.target, arguments[0], arguments[1],
  3876. arguments[2]);
  3877. default:
  3878. var args = new Array(arguments.length);
  3879. for (var i = 0; i < args.length; ++i)
  3880. args[i] = arguments[i];
  3881. this.listener.apply(this.target, args);
  3882. }
  3883. }
  3884. }
  3885. function _onceWrap(target, type, listener) {
  3886. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  3887. var wrapped = bind.call(onceWrapper, state);
  3888. wrapped.listener = listener;
  3889. state.wrapFn = wrapped;
  3890. return wrapped;
  3891. }
  3892. EventEmitter.prototype.once = function once(type, listener) {
  3893. if (typeof listener !== 'function')
  3894. throw new TypeError('"listener" argument must be a function');
  3895. this.on(type, _onceWrap(this, type, listener));
  3896. return this;
  3897. };
  3898. EventEmitter.prototype.prependOnceListener =
  3899. function prependOnceListener(type, listener) {
  3900. if (typeof listener !== 'function')
  3901. throw new TypeError('"listener" argument must be a function');
  3902. this.prependListener(type, _onceWrap(this, type, listener));
  3903. return this;
  3904. };
  3905. // Emits a 'removeListener' event if and only if the listener was removed.
  3906. EventEmitter.prototype.removeListener =
  3907. function removeListener(type, listener) {
  3908. var list, events, position, i, originalListener;
  3909. if (typeof listener !== 'function')
  3910. throw new TypeError('"listener" argument must be a function');
  3911. events = this._events;
  3912. if (!events)
  3913. return this;
  3914. list = events[type];
  3915. if (!list)
  3916. return this;
  3917. if (list === listener || list.listener === listener) {
  3918. if (--this._eventsCount === 0)
  3919. this._events = objectCreate(null);
  3920. else {
  3921. delete events[type];
  3922. if (events.removeListener)
  3923. this.emit('removeListener', type, list.listener || listener);
  3924. }
  3925. } else if (typeof list !== 'function') {
  3926. position = -1;
  3927. for (i = list.length - 1; i >= 0; i--) {
  3928. if (list[i] === listener || list[i].listener === listener) {
  3929. originalListener = list[i].listener;
  3930. position = i;
  3931. break;
  3932. }
  3933. }
  3934. if (position < 0)
  3935. return this;
  3936. if (position === 0)
  3937. list.shift();
  3938. else
  3939. spliceOne(list, position);
  3940. if (list.length === 1)
  3941. events[type] = list[0];
  3942. if (events.removeListener)
  3943. this.emit('removeListener', type, originalListener || listener);
  3944. }
  3945. return this;
  3946. };
  3947. EventEmitter.prototype.removeAllListeners =
  3948. function removeAllListeners(type) {
  3949. var listeners, events, i;
  3950. events = this._events;
  3951. if (!events)
  3952. return this;
  3953. // not listening for removeListener, no need to emit
  3954. if (!events.removeListener) {
  3955. if (arguments.length === 0) {
  3956. this._events = objectCreate(null);
  3957. this._eventsCount = 0;
  3958. } else if (events[type]) {
  3959. if (--this._eventsCount === 0)
  3960. this._events = objectCreate(null);
  3961. else
  3962. delete events[type];
  3963. }
  3964. return this;
  3965. }
  3966. // emit removeListener for all listeners on all events
  3967. if (arguments.length === 0) {
  3968. var keys = objectKeys(events);
  3969. var key;
  3970. for (i = 0; i < keys.length; ++i) {
  3971. key = keys[i];
  3972. if (key === 'removeListener') continue;
  3973. this.removeAllListeners(key);
  3974. }
  3975. this.removeAllListeners('removeListener');
  3976. this._events = objectCreate(null);
  3977. this._eventsCount = 0;
  3978. return this;
  3979. }
  3980. listeners = events[type];
  3981. if (typeof listeners === 'function') {
  3982. this.removeListener(type, listeners);
  3983. } else if (listeners) {
  3984. // LIFO order
  3985. for (i = listeners.length - 1; i >= 0; i--) {
  3986. this.removeListener(type, listeners[i]);
  3987. }
  3988. }
  3989. return this;
  3990. };
  3991. function _listeners(target, type, unwrap) {
  3992. var events = target._events;
  3993. if (!events)
  3994. return [];
  3995. var evlistener = events[type];
  3996. if (!evlistener)
  3997. return [];
  3998. if (typeof evlistener === 'function')
  3999. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  4000. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  4001. }
  4002. EventEmitter.prototype.listeners = function listeners(type) {
  4003. return _listeners(this, type, true);
  4004. };
  4005. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4006. return _listeners(this, type, false);
  4007. };
  4008. EventEmitter.listenerCount = function(emitter, type) {
  4009. if (typeof emitter.listenerCount === 'function') {
  4010. return emitter.listenerCount(type);
  4011. } else {
  4012. return listenerCount.call(emitter, type);
  4013. }
  4014. };
  4015. EventEmitter.prototype.listenerCount = listenerCount;
  4016. function listenerCount(type) {
  4017. var events = this._events;
  4018. if (events) {
  4019. var evlistener = events[type];
  4020. if (typeof evlistener === 'function') {
  4021. return 1;
  4022. } else if (evlistener) {
  4023. return evlistener.length;
  4024. }
  4025. }
  4026. return 0;
  4027. }
  4028. EventEmitter.prototype.eventNames = function eventNames() {
  4029. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  4030. };
  4031. // About 1.5x faster than the two-arg version of Array#splice().
  4032. function spliceOne(list, index) {
  4033. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  4034. list[i] = list[k];
  4035. list.pop();
  4036. }
  4037. function arrayClone(arr, n) {
  4038. var copy = new Array(n);
  4039. for (var i = 0; i < n; ++i)
  4040. copy[i] = arr[i];
  4041. return copy;
  4042. }
  4043. function unwrapListeners(arr) {
  4044. var ret = new Array(arr.length);
  4045. for (var i = 0; i < ret.length; ++i) {
  4046. ret[i] = arr[i].listener || arr[i];
  4047. }
  4048. return ret;
  4049. }
  4050. function objectCreatePolyfill(proto) {
  4051. var F = function() {};
  4052. F.prototype = proto;
  4053. return new F;
  4054. }
  4055. function objectKeysPolyfill(obj) {
  4056. var keys = [];
  4057. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  4058. keys.push(k);
  4059. }
  4060. return k;
  4061. }
  4062. function functionBindPolyfill(context) {
  4063. var fn = this;
  4064. return function () {
  4065. return fn.apply(context, arguments);
  4066. };
  4067. }
  4068. },{}],14:[function(require,module,exports){
  4069. (function (Buffer){
  4070. // Copyright Joyent, Inc. and other Node contributors.
  4071. //
  4072. // Permission is hereby granted, free of charge, to any person obtaining a
  4073. // copy of this software and associated documentation files (the
  4074. // "Software"), to deal in the Software without restriction, including
  4075. // without limitation the rights to use, copy, modify, merge, publish,
  4076. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4077. // persons to whom the Software is furnished to do so, subject to the
  4078. // following conditions:
  4079. //
  4080. // The above copyright notice and this permission notice shall be included
  4081. // in all copies or substantial portions of the Software.
  4082. //
  4083. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4084. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4085. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4086. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4087. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4088. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4089. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4090. // NOTE: These type checking functions intentionally don't use `instanceof`
  4091. // because it is fragile and can be easily faked with `Object.create()`.
  4092. function isArray(arg) {
  4093. if (Array.isArray) {
  4094. return Array.isArray(arg);
  4095. }
  4096. return objectToString(arg) === '[object Array]';
  4097. }
  4098. exports.isArray = isArray;
  4099. function isBoolean(arg) {
  4100. return typeof arg === 'boolean';
  4101. }
  4102. exports.isBoolean = isBoolean;
  4103. function isNull(arg) {
  4104. return arg === null;
  4105. }
  4106. exports.isNull = isNull;
  4107. function isNullOrUndefined(arg) {
  4108. return arg == null;
  4109. }
  4110. exports.isNullOrUndefined = isNullOrUndefined;
  4111. function isNumber(arg) {
  4112. return typeof arg === 'number';
  4113. }
  4114. exports.isNumber = isNumber;
  4115. function isString(arg) {
  4116. return typeof arg === 'string';
  4117. }
  4118. exports.isString = isString;
  4119. function isSymbol(arg) {
  4120. return typeof arg === 'symbol';
  4121. }
  4122. exports.isSymbol = isSymbol;
  4123. function isUndefined(arg) {
  4124. return arg === void 0;
  4125. }
  4126. exports.isUndefined = isUndefined;
  4127. function isRegExp(re) {
  4128. return objectToString(re) === '[object RegExp]';
  4129. }
  4130. exports.isRegExp = isRegExp;
  4131. function isObject(arg) {
  4132. return typeof arg === 'object' && arg !== null;
  4133. }
  4134. exports.isObject = isObject;
  4135. function isDate(d) {
  4136. return objectToString(d) === '[object Date]';
  4137. }
  4138. exports.isDate = isDate;
  4139. function isError(e) {
  4140. return (objectToString(e) === '[object Error]' || e instanceof Error);
  4141. }
  4142. exports.isError = isError;
  4143. function isFunction(arg) {
  4144. return typeof arg === 'function';
  4145. }
  4146. exports.isFunction = isFunction;
  4147. function isPrimitive(arg) {
  4148. return arg === null ||
  4149. typeof arg === 'boolean' ||
  4150. typeof arg === 'number' ||
  4151. typeof arg === 'string' ||
  4152. typeof arg === 'symbol' || // ES6 symbol
  4153. typeof arg === 'undefined';
  4154. }
  4155. exports.isPrimitive = isPrimitive;
  4156. exports.isBuffer = Buffer.isBuffer;
  4157. function objectToString(o) {
  4158. return Object.prototype.toString.call(o);
  4159. }
  4160. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  4161. },{"../../is-buffer/index.js":81}],15:[function(require,module,exports){
  4162. 'use strict';
  4163. var copy = require('es5-ext/object/copy')
  4164. , normalizeOptions = require('es5-ext/object/normalize-options')
  4165. , ensureCallable = require('es5-ext/object/valid-callable')
  4166. , map = require('es5-ext/object/map')
  4167. , callable = require('es5-ext/object/valid-callable')
  4168. , validValue = require('es5-ext/object/valid-value')
  4169. , bind = Function.prototype.bind, defineProperty = Object.defineProperty
  4170. , hasOwnProperty = Object.prototype.hasOwnProperty
  4171. , define;
  4172. define = function (name, desc, options) {
  4173. var value = validValue(desc) && callable(desc.value), dgs;
  4174. dgs = copy(desc);
  4175. delete dgs.writable;
  4176. delete dgs.value;
  4177. dgs.get = function () {
  4178. if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
  4179. desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
  4180. defineProperty(this, name, desc);
  4181. return this[name];
  4182. };
  4183. return dgs;
  4184. };
  4185. module.exports = function (props/*, options*/) {
  4186. var options = normalizeOptions(arguments[1]);
  4187. if (options.resolveContext != null) ensureCallable(options.resolveContext);
  4188. return map(props, function (desc, name) { return define(name, desc, options); });
  4189. };
  4190. },{"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){
  4191. 'use strict';
  4192. var assign = require('es5-ext/object/assign')
  4193. , normalizeOpts = require('es5-ext/object/normalize-options')
  4194. , isCallable = require('es5-ext/object/is-callable')
  4195. , contains = require('es5-ext/string/#/contains')
  4196. , d;
  4197. d = module.exports = function (dscr, value/*, options*/) {
  4198. var c, e, w, options, desc;
  4199. if ((arguments.length < 2) || (typeof dscr !== 'string')) {
  4200. options = value;
  4201. value = dscr;
  4202. dscr = null;
  4203. } else {
  4204. options = arguments[2];
  4205. }
  4206. if (dscr == null) {
  4207. c = w = true;
  4208. e = false;
  4209. } else {
  4210. c = contains.call(dscr, 'c');
  4211. e = contains.call(dscr, 'e');
  4212. w = contains.call(dscr, 'w');
  4213. }
  4214. desc = { value: value, configurable: c, enumerable: e, writable: w };
  4215. return !options ? desc : assign(normalizeOpts(options), desc);
  4216. };
  4217. d.gs = function (dscr, get, set/*, options*/) {
  4218. var c, e, options, desc;
  4219. if (typeof dscr !== 'string') {
  4220. options = set;
  4221. set = get;
  4222. get = dscr;
  4223. dscr = null;
  4224. } else {
  4225. options = arguments[3];
  4226. }
  4227. if (get == null) {
  4228. get = undefined;
  4229. } else if (!isCallable(get)) {
  4230. options = get;
  4231. get = set = undefined;
  4232. } else if (set == null) {
  4233. set = undefined;
  4234. } else if (!isCallable(set)) {
  4235. options = set;
  4236. set = undefined;
  4237. }
  4238. if (dscr == null) {
  4239. c = true;
  4240. e = false;
  4241. } else {
  4242. c = contains.call(dscr, 'c');
  4243. e = contains.call(dscr, 'e');
  4244. }
  4245. desc = { get: get, set: set, configurable: c, enumerable: e };
  4246. return !options ? desc : assign(normalizeOpts(options), desc);
  4247. };
  4248. },{"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){
  4249. (function (process,Buffer){
  4250. var stream = require('readable-stream')
  4251. var eos = require('end-of-stream')
  4252. var inherits = require('inherits')
  4253. var shift = require('stream-shift')
  4254. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  4255. ? Buffer.from([0])
  4256. : new Buffer([0])
  4257. var onuncork = function(self, fn) {
  4258. if (self._corked) self.once('uncork', fn)
  4259. else fn()
  4260. }
  4261. var autoDestroy = function (self, err) {
  4262. if (self._autoDestroy) self.destroy(err)
  4263. }
  4264. var destroyer = function(self, end) {
  4265. return function(err) {
  4266. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  4267. else if (end && !self._ended) self.end()
  4268. }
  4269. }
  4270. var end = function(ws, fn) {
  4271. if (!ws) return fn()
  4272. if (ws._writableState && ws._writableState.finished) return fn()
  4273. if (ws._writableState) return ws.end(fn)
  4274. ws.end()
  4275. fn()
  4276. }
  4277. var toStreams2 = function(rs) {
  4278. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  4279. }
  4280. var Duplexify = function(writable, readable, opts) {
  4281. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  4282. stream.Duplex.call(this, opts)
  4283. this._writable = null
  4284. this._readable = null
  4285. this._readable2 = null
  4286. this._autoDestroy = !opts || opts.autoDestroy !== false
  4287. this._forwardDestroy = !opts || opts.destroy !== false
  4288. this._forwardEnd = !opts || opts.end !== false
  4289. this._corked = 1 // start corked
  4290. this._ondrain = null
  4291. this._drained = false
  4292. this._forwarding = false
  4293. this._unwrite = null
  4294. this._unread = null
  4295. this._ended = false
  4296. this.destroyed = false
  4297. if (writable) this.setWritable(writable)
  4298. if (readable) this.setReadable(readable)
  4299. }
  4300. inherits(Duplexify, stream.Duplex)
  4301. Duplexify.obj = function(writable, readable, opts) {
  4302. if (!opts) opts = {}
  4303. opts.objectMode = true
  4304. opts.highWaterMark = 16
  4305. return new Duplexify(writable, readable, opts)
  4306. }
  4307. Duplexify.prototype.cork = function() {
  4308. if (++this._corked === 1) this.emit('cork')
  4309. }
  4310. Duplexify.prototype.uncork = function() {
  4311. if (this._corked && --this._corked === 0) this.emit('uncork')
  4312. }
  4313. Duplexify.prototype.setWritable = function(writable) {
  4314. if (this._unwrite) this._unwrite()
  4315. if (this.destroyed) {
  4316. if (writable && writable.destroy) writable.destroy()
  4317. return
  4318. }
  4319. if (writable === null || writable === false) {
  4320. this.end()
  4321. return
  4322. }
  4323. var self = this
  4324. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  4325. var ondrain = function() {
  4326. var ondrain = self._ondrain
  4327. self._ondrain = null
  4328. if (ondrain) ondrain()
  4329. }
  4330. var clear = function() {
  4331. self._writable.removeListener('drain', ondrain)
  4332. unend()
  4333. }
  4334. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  4335. this._writable = writable
  4336. this._writable.on('drain', ondrain)
  4337. this._unwrite = clear
  4338. this.uncork() // always uncork setWritable
  4339. }
  4340. Duplexify.prototype.setReadable = function(readable) {
  4341. if (this._unread) this._unread()
  4342. if (this.destroyed) {
  4343. if (readable && readable.destroy) readable.destroy()
  4344. return
  4345. }
  4346. if (readable === null || readable === false) {
  4347. this.push(null)
  4348. this.resume()
  4349. return
  4350. }
  4351. var self = this
  4352. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  4353. var onreadable = function() {
  4354. self._forward()
  4355. }
  4356. var onend = function() {
  4357. self.push(null)
  4358. }
  4359. var clear = function() {
  4360. self._readable2.removeListener('readable', onreadable)
  4361. self._readable2.removeListener('end', onend)
  4362. unend()
  4363. }
  4364. this._drained = true
  4365. this._readable = readable
  4366. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  4367. this._readable2.on('readable', onreadable)
  4368. this._readable2.on('end', onend)
  4369. this._unread = clear
  4370. this._forward()
  4371. }
  4372. Duplexify.prototype._read = function() {
  4373. this._drained = true
  4374. this._forward()
  4375. }
  4376. Duplexify.prototype._forward = function() {
  4377. if (this._forwarding || !this._readable2 || !this._drained) return
  4378. this._forwarding = true
  4379. var data
  4380. while (this._drained && (data = shift(this._readable2)) !== null) {
  4381. if (this.destroyed) continue
  4382. this._drained = this.push(data)
  4383. }
  4384. this._forwarding = false
  4385. }
  4386. Duplexify.prototype.destroy = function(err) {
  4387. if (this.destroyed) return
  4388. this.destroyed = true
  4389. var self = this
  4390. process.nextTick(function() {
  4391. self._destroy(err)
  4392. })
  4393. }
  4394. Duplexify.prototype._destroy = function(err) {
  4395. if (err) {
  4396. var ondrain = this._ondrain
  4397. this._ondrain = null
  4398. if (ondrain) ondrain(err)
  4399. else this.emit('error', err)
  4400. }
  4401. if (this._forwardDestroy) {
  4402. if (this._readable && this._readable.destroy) this._readable.destroy()
  4403. if (this._writable && this._writable.destroy) this._writable.destroy()
  4404. }
  4405. this.emit('close')
  4406. }
  4407. Duplexify.prototype._write = function(data, enc, cb) {
  4408. if (this.destroyed) return cb()
  4409. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  4410. if (data === SIGNAL_FLUSH) return this._finish(cb)
  4411. if (!this._writable) return cb()
  4412. if (this._writable.write(data) === false) this._ondrain = cb
  4413. else cb()
  4414. }
  4415. Duplexify.prototype._finish = function(cb) {
  4416. var self = this
  4417. this.emit('preend')
  4418. onuncork(this, function() {
  4419. end(self._forwardEnd && self._writable, function() {
  4420. // haxx to not emit prefinish twice
  4421. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  4422. self.emit('prefinish')
  4423. onuncork(self, cb)
  4424. })
  4425. })
  4426. }
  4427. Duplexify.prototype.end = function(data, enc, cb) {
  4428. if (typeof data === 'function') return this.end(null, null, data)
  4429. if (typeof enc === 'function') return this.end(data, null, enc)
  4430. this._ended = true
  4431. if (data) this.write(data)
  4432. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  4433. return stream.Writable.prototype.end.call(this, cb)
  4434. }
  4435. module.exports = Duplexify
  4436. }).call(this,require('_process'),require("buffer").Buffer)
  4437. },{"_process":92,"buffer":12,"end-of-stream":18,"inherits":80,"readable-stream":108,"stream-shift":111}],18:[function(require,module,exports){
  4438. var once = require('once');
  4439. var noop = function() {};
  4440. var isRequest = function(stream) {
  4441. return stream.setHeader && typeof stream.abort === 'function';
  4442. };
  4443. var isChildProcess = function(stream) {
  4444. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  4445. };
  4446. var eos = function(stream, opts, callback) {
  4447. if (typeof opts === 'function') return eos(stream, null, opts);
  4448. if (!opts) opts = {};
  4449. callback = once(callback || noop);
  4450. var ws = stream._writableState;
  4451. var rs = stream._readableState;
  4452. var readable = opts.readable || (opts.readable !== false && stream.readable);
  4453. var writable = opts.writable || (opts.writable !== false && stream.writable);
  4454. var onlegacyfinish = function() {
  4455. if (!stream.writable) onfinish();
  4456. };
  4457. var onfinish = function() {
  4458. writable = false;
  4459. if (!readable) callback.call(stream);
  4460. };
  4461. var onend = function() {
  4462. readable = false;
  4463. if (!writable) callback.call(stream);
  4464. };
  4465. var onexit = function(exitCode) {
  4466. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  4467. };
  4468. var onerror = function(err) {
  4469. callback.call(stream, err);
  4470. };
  4471. var onclose = function() {
  4472. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  4473. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  4474. };
  4475. var onrequest = function() {
  4476. stream.req.on('finish', onfinish);
  4477. };
  4478. if (isRequest(stream)) {
  4479. stream.on('complete', onfinish);
  4480. stream.on('abort', onclose);
  4481. if (stream.req) onrequest();
  4482. else stream.on('request', onrequest);
  4483. } else if (writable && !ws) { // legacy streams
  4484. stream.on('end', onlegacyfinish);
  4485. stream.on('close', onlegacyfinish);
  4486. }
  4487. if (isChildProcess(stream)) stream.on('exit', onexit);
  4488. stream.on('end', onend);
  4489. stream.on('finish', onfinish);
  4490. if (opts.error !== false) stream.on('error', onerror);
  4491. stream.on('close', onclose);
  4492. return function() {
  4493. stream.removeListener('complete', onfinish);
  4494. stream.removeListener('abort', onclose);
  4495. stream.removeListener('request', onrequest);
  4496. if (stream.req) stream.req.removeListener('finish', onfinish);
  4497. stream.removeListener('end', onlegacyfinish);
  4498. stream.removeListener('close', onlegacyfinish);
  4499. stream.removeListener('finish', onfinish);
  4500. stream.removeListener('exit', onexit);
  4501. stream.removeListener('end', onend);
  4502. stream.removeListener('error', onerror);
  4503. stream.removeListener('close', onclose);
  4504. };
  4505. };
  4506. module.exports = eos;
  4507. },{"once":90}],19:[function(require,module,exports){
  4508. // Inspired by Google Closure:
  4509. // http://closure-library.googlecode.com/svn/docs/
  4510. // closure_goog_array_array.js.html#goog.array.clear
  4511. "use strict";
  4512. var value = require("../../object/valid-value");
  4513. module.exports = function () {
  4514. value(this).length = 0;
  4515. return this;
  4516. };
  4517. },{"../../object/valid-value":55}],20:[function(require,module,exports){
  4518. "use strict";
  4519. var numberIsNaN = require("../../number/is-nan")
  4520. , toPosInt = require("../../number/to-pos-integer")
  4521. , value = require("../../object/valid-value")
  4522. , indexOf = Array.prototype.indexOf
  4523. , objHasOwnProperty = Object.prototype.hasOwnProperty
  4524. , abs = Math.abs
  4525. , floor = Math.floor;
  4526. module.exports = function (searchElement /*, fromIndex*/) {
  4527. var i, length, fromIndex, val;
  4528. if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
  4529. length = toPosInt(value(this).length);
  4530. fromIndex = arguments[1];
  4531. if (isNaN(fromIndex)) fromIndex = 0;
  4532. else if (fromIndex >= 0) fromIndex = floor(fromIndex);
  4533. else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
  4534. for (i = fromIndex; i < length; ++i) {
  4535. if (objHasOwnProperty.call(this, i)) {
  4536. val = this[i];
  4537. if (numberIsNaN(val)) return i; // Jslint: ignore
  4538. }
  4539. }
  4540. return -1;
  4541. };
  4542. },{"../../number/is-nan":30,"../../number/to-pos-integer":34,"../../object/valid-value":55}],21:[function(require,module,exports){
  4543. "use strict";
  4544. module.exports = require("./is-implemented")()
  4545. ? Array.from
  4546. : require("./shim");
  4547. },{"./is-implemented":22,"./shim":23}],22:[function(require,module,exports){
  4548. "use strict";
  4549. module.exports = function () {
  4550. var from = Array.from, arr, result;
  4551. if (typeof from !== "function") return false;
  4552. arr = ["raz", "dwa"];
  4553. result = from(arr);
  4554. return Boolean(result && (result !== arr) && (result[1] === "dwa"));
  4555. };
  4556. },{}],23:[function(require,module,exports){
  4557. "use strict";
  4558. var iteratorSymbol = require("es6-symbol").iterator
  4559. , isArguments = require("../../function/is-arguments")
  4560. , isFunction = require("../../function/is-function")
  4561. , toPosInt = require("../../number/to-pos-integer")
  4562. , callable = require("../../object/valid-callable")
  4563. , validValue = require("../../object/valid-value")
  4564. , isValue = require("../../object/is-value")
  4565. , isString = require("../../string/is-string")
  4566. , isArray = Array.isArray
  4567. , call = Function.prototype.call
  4568. , desc = { configurable: true, enumerable: true, writable: true, value: null }
  4569. , defineProperty = Object.defineProperty;
  4570. // eslint-disable-next-line complexity
  4571. module.exports = function (arrayLike /*, mapFn, thisArg*/) {
  4572. var mapFn = arguments[1]
  4573. , thisArg = arguments[2]
  4574. , Context
  4575. , i
  4576. , j
  4577. , arr
  4578. , length
  4579. , code
  4580. , iterator
  4581. , result
  4582. , getIterator
  4583. , value;
  4584. arrayLike = Object(validValue(arrayLike));
  4585. if (isValue(mapFn)) callable(mapFn);
  4586. if (!this || this === Array || !isFunction(this)) {
  4587. // Result: Plain array
  4588. if (!mapFn) {
  4589. if (isArguments(arrayLike)) {
  4590. // Source: Arguments
  4591. length = arrayLike.length;
  4592. if (length !== 1) return Array.apply(null, arrayLike);
  4593. arr = new Array(1);
  4594. arr[0] = arrayLike[0];
  4595. return arr;
  4596. }
  4597. if (isArray(arrayLike)) {
  4598. // Source: Array
  4599. arr = new Array(length = arrayLike.length);
  4600. for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
  4601. return arr;
  4602. }
  4603. }
  4604. arr = [];
  4605. } else {
  4606. // Result: Non plain array
  4607. Context = this;
  4608. }
  4609. if (!isArray(arrayLike)) {
  4610. if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
  4611. // Source: Iterator
  4612. iterator = callable(getIterator).call(arrayLike);
  4613. if (Context) arr = new Context();
  4614. result = iterator.next();
  4615. i = 0;
  4616. while (!result.done) {
  4617. value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
  4618. if (Context) {
  4619. desc.value = value;
  4620. defineProperty(arr, i, desc);
  4621. } else {
  4622. arr[i] = value;
  4623. }
  4624. result = iterator.next();
  4625. ++i;
  4626. }
  4627. length = i;
  4628. } else if (isString(arrayLike)) {
  4629. // Source: String
  4630. length = arrayLike.length;
  4631. if (Context) arr = new Context();
  4632. for (i = 0, j = 0; i < length; ++i) {
  4633. value = arrayLike[i];
  4634. if (i + 1 < length) {
  4635. code = value.charCodeAt(0);
  4636. // eslint-disable-next-line max-depth
  4637. if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
  4638. }
  4639. value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
  4640. if (Context) {
  4641. desc.value = value;
  4642. defineProperty(arr, j, desc);
  4643. } else {
  4644. arr[j] = value;
  4645. }
  4646. ++j;
  4647. }
  4648. length = j;
  4649. }
  4650. }
  4651. if (length === undefined) {
  4652. // Source: array or array-like
  4653. length = toPosInt(arrayLike.length);
  4654. if (Context) arr = new Context(length);
  4655. for (i = 0; i < length; ++i) {
  4656. value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
  4657. if (Context) {
  4658. desc.value = value;
  4659. defineProperty(arr, i, desc);
  4660. } else {
  4661. arr[i] = value;
  4662. }
  4663. }
  4664. }
  4665. if (Context) {
  4666. desc.value = null;
  4667. arr.length = length;
  4668. }
  4669. return arr;
  4670. };
  4671. },{"../../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){
  4672. "use strict";
  4673. var objToString = Object.prototype.toString
  4674. , id = objToString.call(
  4675. (function () {
  4676. return arguments;
  4677. })()
  4678. );
  4679. module.exports = function (value) {
  4680. return objToString.call(value) === id;
  4681. };
  4682. },{}],25:[function(require,module,exports){
  4683. "use strict";
  4684. var objToString = Object.prototype.toString, id = objToString.call(require("./noop"));
  4685. module.exports = function (value) {
  4686. return typeof value === "function" && objToString.call(value) === id;
  4687. };
  4688. },{"./noop":26}],26:[function(require,module,exports){
  4689. "use strict";
  4690. // eslint-disable-next-line no-empty-function
  4691. module.exports = function () {};
  4692. },{}],27:[function(require,module,exports){
  4693. "use strict";
  4694. module.exports = require("./is-implemented")()
  4695. ? Math.sign
  4696. : require("./shim");
  4697. },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){
  4698. "use strict";
  4699. module.exports = function () {
  4700. var sign = Math.sign;
  4701. if (typeof sign !== "function") return false;
  4702. return (sign(10) === 1) && (sign(-20) === -1);
  4703. };
  4704. },{}],29:[function(require,module,exports){
  4705. "use strict";
  4706. module.exports = function (value) {
  4707. value = Number(value);
  4708. if (isNaN(value) || (value === 0)) return value;
  4709. return value > 0 ? 1 : -1;
  4710. };
  4711. },{}],30:[function(require,module,exports){
  4712. "use strict";
  4713. module.exports = require("./is-implemented")()
  4714. ? Number.isNaN
  4715. : require("./shim");
  4716. },{"./is-implemented":31,"./shim":32}],31:[function(require,module,exports){
  4717. "use strict";
  4718. module.exports = function () {
  4719. var numberIsNaN = Number.isNaN;
  4720. if (typeof numberIsNaN !== "function") return false;
  4721. return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
  4722. };
  4723. },{}],32:[function(require,module,exports){
  4724. "use strict";
  4725. module.exports = function (value) {
  4726. // eslint-disable-next-line no-self-compare
  4727. return value !== value;
  4728. };
  4729. },{}],33:[function(require,module,exports){
  4730. "use strict";
  4731. var sign = require("../math/sign")
  4732. , abs = Math.abs, floor = Math.floor;
  4733. module.exports = function (value) {
  4734. if (isNaN(value)) return 0;
  4735. value = Number(value);
  4736. if ((value === 0) || !isFinite(value)) return value;
  4737. return sign(value) * floor(abs(value));
  4738. };
  4739. },{"../math/sign":27}],34:[function(require,module,exports){
  4740. "use strict";
  4741. var toInteger = require("./to-integer")
  4742. , max = Math.max;
  4743. module.exports = function (value) {
  4744. return max(0, toInteger(value));
  4745. };
  4746. },{"./to-integer":33}],35:[function(require,module,exports){
  4747. // Internal method, used by iteration functions.
  4748. // Calls a function for each key-value pair found in object
  4749. // Optionally takes compareFn to iterate object in specific order
  4750. "use strict";
  4751. var callable = require("./valid-callable")
  4752. , value = require("./valid-value")
  4753. , bind = Function.prototype.bind
  4754. , call = Function.prototype.call
  4755. , keys = Object.keys
  4756. , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
  4757. module.exports = function (method, defVal) {
  4758. return function (obj, cb /*, thisArg, compareFn*/) {
  4759. var list, thisArg = arguments[2], compareFn = arguments[3];
  4760. obj = Object(value(obj));
  4761. callable(cb);
  4762. list = keys(obj);
  4763. if (compareFn) {
  4764. list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
  4765. }
  4766. if (typeof method !== "function") method = list[method];
  4767. return call.call(method, list, function (key, index) {
  4768. if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
  4769. return call.call(cb, thisArg, obj[key], key, obj, index);
  4770. });
  4771. };
  4772. };
  4773. },{"./valid-callable":54,"./valid-value":55}],36:[function(require,module,exports){
  4774. "use strict";
  4775. module.exports = require("./is-implemented")()
  4776. ? Object.assign
  4777. : require("./shim");
  4778. },{"./is-implemented":37,"./shim":38}],37:[function(require,module,exports){
  4779. "use strict";
  4780. module.exports = function () {
  4781. var assign = Object.assign, obj;
  4782. if (typeof assign !== "function") return false;
  4783. obj = { foo: "raz" };
  4784. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  4785. return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
  4786. };
  4787. },{}],38:[function(require,module,exports){
  4788. "use strict";
  4789. var keys = require("../keys")
  4790. , value = require("../valid-value")
  4791. , max = Math.max;
  4792. module.exports = function (dest, src /*, …srcn*/) {
  4793. var error, i, length = max(arguments.length, 2), assign;
  4794. dest = Object(value(dest));
  4795. assign = function (key) {
  4796. try {
  4797. dest[key] = src[key];
  4798. } catch (e) {
  4799. if (!error) error = e;
  4800. }
  4801. };
  4802. for (i = 1; i < length; ++i) {
  4803. src = arguments[i];
  4804. keys(src).forEach(assign);
  4805. }
  4806. if (error !== undefined) throw error;
  4807. return dest;
  4808. };
  4809. },{"../keys":45,"../valid-value":55}],39:[function(require,module,exports){
  4810. "use strict";
  4811. var aFrom = require("../array/from")
  4812. , assign = require("./assign")
  4813. , value = require("./valid-value");
  4814. module.exports = function (obj/*, propertyNames, options*/) {
  4815. var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
  4816. if (copy !== obj && !propertyNames) return copy;
  4817. var result = {};
  4818. if (propertyNames) {
  4819. aFrom(propertyNames, function (propertyName) {
  4820. if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
  4821. });
  4822. } else {
  4823. assign(result, obj);
  4824. }
  4825. return result;
  4826. };
  4827. },{"../array/from":21,"./assign":36,"./valid-value":55}],40:[function(require,module,exports){
  4828. // Workaround for http://code.google.com/p/v8/issues/detail?id=2804
  4829. "use strict";
  4830. var create = Object.create, shim;
  4831. if (!require("./set-prototype-of/is-implemented")()) {
  4832. shim = require("./set-prototype-of/shim");
  4833. }
  4834. module.exports = (function () {
  4835. var nullObject, polyProps, desc;
  4836. if (!shim) return create;
  4837. if (shim.level !== 1) return create;
  4838. nullObject = {};
  4839. polyProps = {};
  4840. desc = {
  4841. configurable: false,
  4842. enumerable: false,
  4843. writable: true,
  4844. value: undefined
  4845. };
  4846. Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
  4847. if (name === "__proto__") {
  4848. polyProps[name] = {
  4849. configurable: true,
  4850. enumerable: false,
  4851. writable: true,
  4852. value: undefined
  4853. };
  4854. return;
  4855. }
  4856. polyProps[name] = desc;
  4857. });
  4858. Object.defineProperties(nullObject, polyProps);
  4859. Object.defineProperty(shim, "nullPolyfill", {
  4860. configurable: false,
  4861. enumerable: false,
  4862. writable: false,
  4863. value: nullObject
  4864. });
  4865. return function (prototype, props) {
  4866. return create(prototype === null ? nullObject : prototype, props);
  4867. };
  4868. }());
  4869. },{"./set-prototype-of/is-implemented":52,"./set-prototype-of/shim":53}],41:[function(require,module,exports){
  4870. "use strict";
  4871. module.exports = require("./_iterate")("forEach");
  4872. },{"./_iterate":35}],42:[function(require,module,exports){
  4873. // Deprecated
  4874. "use strict";
  4875. module.exports = function (obj) {
  4876. return typeof obj === "function";
  4877. };
  4878. },{}],43:[function(require,module,exports){
  4879. "use strict";
  4880. var isValue = require("./is-value");
  4881. var map = { function: true, object: true };
  4882. module.exports = function (value) {
  4883. return (isValue(value) && map[typeof value]) || false;
  4884. };
  4885. },{"./is-value":44}],44:[function(require,module,exports){
  4886. "use strict";
  4887. var _undefined = require("../function/noop")(); // Support ES3 engines
  4888. module.exports = function (val) {
  4889. return (val !== _undefined) && (val !== null);
  4890. };
  4891. },{"../function/noop":26}],45:[function(require,module,exports){
  4892. "use strict";
  4893. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  4894. },{"./is-implemented":46,"./shim":47}],46:[function(require,module,exports){
  4895. "use strict";
  4896. module.exports = function () {
  4897. try {
  4898. Object.keys("primitive");
  4899. return true;
  4900. } catch (e) {
  4901. return false;
  4902. }
  4903. };
  4904. },{}],47:[function(require,module,exports){
  4905. "use strict";
  4906. var isValue = require("../is-value");
  4907. var keys = Object.keys;
  4908. module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
  4909. },{"../is-value":44}],48:[function(require,module,exports){
  4910. "use strict";
  4911. var callable = require("./valid-callable")
  4912. , forEach = require("./for-each")
  4913. , call = Function.prototype.call;
  4914. module.exports = function (obj, cb /*, thisArg*/) {
  4915. var result = {}, thisArg = arguments[2];
  4916. callable(cb);
  4917. forEach(obj, function (value, key, targetObj, index) {
  4918. result[key] = call.call(cb, thisArg, value, key, targetObj, index);
  4919. });
  4920. return result;
  4921. };
  4922. },{"./for-each":41,"./valid-callable":54}],49:[function(require,module,exports){
  4923. "use strict";
  4924. var isValue = require("./is-value");
  4925. var forEach = Array.prototype.forEach, create = Object.create;
  4926. var process = function (src, obj) {
  4927. var key;
  4928. for (key in src) obj[key] = src[key];
  4929. };
  4930. // eslint-disable-next-line no-unused-vars
  4931. module.exports = function (opts1 /*, …options*/) {
  4932. var result = create(null);
  4933. forEach.call(arguments, function (options) {
  4934. if (!isValue(options)) return;
  4935. process(Object(options), result);
  4936. });
  4937. return result;
  4938. };
  4939. },{"./is-value":44}],50:[function(require,module,exports){
  4940. "use strict";
  4941. var forEach = Array.prototype.forEach, create = Object.create;
  4942. // eslint-disable-next-line no-unused-vars
  4943. module.exports = function (arg /*, …args*/) {
  4944. var set = create(null);
  4945. forEach.call(arguments, function (name) {
  4946. set[name] = true;
  4947. });
  4948. return set;
  4949. };
  4950. },{}],51:[function(require,module,exports){
  4951. "use strict";
  4952. module.exports = require("./is-implemented")()
  4953. ? Object.setPrototypeOf
  4954. : require("./shim");
  4955. },{"./is-implemented":52,"./shim":53}],52:[function(require,module,exports){
  4956. "use strict";
  4957. var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
  4958. module.exports = function (/* CustomCreate*/) {
  4959. var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
  4960. if (typeof setPrototypeOf !== "function") return false;
  4961. return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
  4962. };
  4963. },{}],53:[function(require,module,exports){
  4964. /* eslint no-proto: "off" */
  4965. // Big thanks to @WebReflection for sorting this out
  4966. // https://gist.github.com/WebReflection/5593554
  4967. "use strict";
  4968. var isObject = require("../is-object")
  4969. , value = require("../valid-value")
  4970. , objIsPrototypeOf = Object.prototype.isPrototypeOf
  4971. , defineProperty = Object.defineProperty
  4972. , nullDesc = {
  4973. configurable: true,
  4974. enumerable: false,
  4975. writable: true,
  4976. value: undefined
  4977. }
  4978. , validate;
  4979. validate = function (obj, prototype) {
  4980. value(obj);
  4981. if (prototype === null || isObject(prototype)) return obj;
  4982. throw new TypeError("Prototype must be null or an object");
  4983. };
  4984. module.exports = (function (status) {
  4985. var fn, set;
  4986. if (!status) return null;
  4987. if (status.level === 2) {
  4988. if (status.set) {
  4989. set = status.set;
  4990. fn = function (obj, prototype) {
  4991. set.call(validate(obj, prototype), prototype);
  4992. return obj;
  4993. };
  4994. } else {
  4995. fn = function (obj, prototype) {
  4996. validate(obj, prototype).__proto__ = prototype;
  4997. return obj;
  4998. };
  4999. }
  5000. } else {
  5001. fn = function self(obj, prototype) {
  5002. var isNullBase;
  5003. validate(obj, prototype);
  5004. isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
  5005. if (isNullBase) delete self.nullPolyfill.__proto__;
  5006. if (prototype === null) prototype = self.nullPolyfill;
  5007. obj.__proto__ = prototype;
  5008. if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
  5009. return obj;
  5010. };
  5011. }
  5012. return Object.defineProperty(fn, "level", {
  5013. configurable: false,
  5014. enumerable: false,
  5015. writable: false,
  5016. value: status.level
  5017. });
  5018. }(
  5019. (function () {
  5020. var tmpObj1 = Object.create(null)
  5021. , tmpObj2 = {}
  5022. , set
  5023. , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
  5024. if (desc) {
  5025. try {
  5026. set = desc.set; // Opera crashes at this point
  5027. set.call(tmpObj1, tmpObj2);
  5028. } catch (ignore) {}
  5029. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
  5030. }
  5031. tmpObj1.__proto__ = tmpObj2;
  5032. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
  5033. tmpObj1 = {};
  5034. tmpObj1.__proto__ = tmpObj2;
  5035. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
  5036. return false;
  5037. })()
  5038. ));
  5039. require("../create");
  5040. },{"../create":40,"../is-object":43,"../valid-value":55}],54:[function(require,module,exports){
  5041. "use strict";
  5042. module.exports = function (fn) {
  5043. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  5044. return fn;
  5045. };
  5046. },{}],55:[function(require,module,exports){
  5047. "use strict";
  5048. var isValue = require("./is-value");
  5049. module.exports = function (value) {
  5050. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  5051. return value;
  5052. };
  5053. },{"./is-value":44}],56:[function(require,module,exports){
  5054. "use strict";
  5055. module.exports = require("./is-implemented")()
  5056. ? String.prototype.contains
  5057. : require("./shim");
  5058. },{"./is-implemented":57,"./shim":58}],57:[function(require,module,exports){
  5059. "use strict";
  5060. var str = "razdwatrzy";
  5061. module.exports = function () {
  5062. if (typeof str.contains !== "function") return false;
  5063. return (str.contains("dwa") === true) && (str.contains("foo") === false);
  5064. };
  5065. },{}],58:[function(require,module,exports){
  5066. "use strict";
  5067. var indexOf = String.prototype.indexOf;
  5068. module.exports = function (searchString/*, position*/) {
  5069. return indexOf.call(this, searchString, arguments[1]) > -1;
  5070. };
  5071. },{}],59:[function(require,module,exports){
  5072. "use strict";
  5073. var objToString = Object.prototype.toString, id = objToString.call("");
  5074. module.exports = function (value) {
  5075. return (
  5076. typeof value === "string" ||
  5077. (value &&
  5078. typeof value === "object" &&
  5079. (value instanceof String || objToString.call(value) === id)) ||
  5080. false
  5081. );
  5082. };
  5083. },{}],60:[function(require,module,exports){
  5084. "use strict";
  5085. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5086. , contains = require("es5-ext/string/#/contains")
  5087. , d = require("d")
  5088. , Symbol = require("es6-symbol")
  5089. , Iterator = require("./");
  5090. var defineProperty = Object.defineProperty, ArrayIterator;
  5091. ArrayIterator = module.exports = function (arr, kind) {
  5092. if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
  5093. Iterator.call(this, arr);
  5094. if (!kind) kind = "value";
  5095. else if (contains.call(kind, "key+value")) kind = "key+value";
  5096. else if (contains.call(kind, "key")) kind = "key";
  5097. else kind = "value";
  5098. defineProperty(this, "__kind__", d("", kind));
  5099. };
  5100. if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
  5101. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5102. delete ArrayIterator.prototype.constructor;
  5103. ArrayIterator.prototype = Object.create(Iterator.prototype, {
  5104. _resolve: d(function (i) {
  5105. if (this.__kind__ === "value") return this.__list__[i];
  5106. if (this.__kind__ === "key+value") return [i, this.__list__[i]];
  5107. return i;
  5108. })
  5109. });
  5110. defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
  5111. },{"./":63,"d":16,"es5-ext/object/set-prototype-of":51,"es5-ext/string/#/contains":56,"es6-symbol":73}],61:[function(require,module,exports){
  5112. "use strict";
  5113. var isArguments = require("es5-ext/function/is-arguments")
  5114. , callable = require("es5-ext/object/valid-callable")
  5115. , isString = require("es5-ext/string/is-string")
  5116. , get = require("./get");
  5117. var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
  5118. module.exports = function (iterable, cb /*, thisArg*/) {
  5119. var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
  5120. if (isArray(iterable) || isArguments(iterable)) mode = "array";
  5121. else if (isString(iterable)) mode = "string";
  5122. else iterable = get(iterable);
  5123. callable(cb);
  5124. doBreak = function () {
  5125. broken = true;
  5126. };
  5127. if (mode === "array") {
  5128. some.call(iterable, function (value) {
  5129. call.call(cb, thisArg, value, doBreak);
  5130. return broken;
  5131. });
  5132. return;
  5133. }
  5134. if (mode === "string") {
  5135. length = iterable.length;
  5136. for (i = 0; i < length; ++i) {
  5137. char = iterable[i];
  5138. if (i + 1 < length) {
  5139. code = char.charCodeAt(0);
  5140. if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
  5141. }
  5142. call.call(cb, thisArg, char, doBreak);
  5143. if (broken) break;
  5144. }
  5145. return;
  5146. }
  5147. result = iterable.next();
  5148. while (!result.done) {
  5149. call.call(cb, thisArg, result.value, doBreak);
  5150. if (broken) return;
  5151. result = iterable.next();
  5152. }
  5153. };
  5154. },{"./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){
  5155. "use strict";
  5156. var isArguments = require("es5-ext/function/is-arguments")
  5157. , isString = require("es5-ext/string/is-string")
  5158. , ArrayIterator = require("./array")
  5159. , StringIterator = require("./string")
  5160. , iterable = require("./valid-iterable")
  5161. , iteratorSymbol = require("es6-symbol").iterator;
  5162. module.exports = function (obj) {
  5163. if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
  5164. if (isArguments(obj)) return new ArrayIterator(obj);
  5165. if (isString(obj)) return new StringIterator(obj);
  5166. return new ArrayIterator(obj);
  5167. };
  5168. },{"./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){
  5169. "use strict";
  5170. var clear = require("es5-ext/array/#/clear")
  5171. , assign = require("es5-ext/object/assign")
  5172. , callable = require("es5-ext/object/valid-callable")
  5173. , value = require("es5-ext/object/valid-value")
  5174. , d = require("d")
  5175. , autoBind = require("d/auto-bind")
  5176. , Symbol = require("es6-symbol");
  5177. var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
  5178. module.exports = Iterator = function (list, context) {
  5179. if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
  5180. defineProperties(this, {
  5181. __list__: d("w", value(list)),
  5182. __context__: d("w", context),
  5183. __nextIndex__: d("w", 0)
  5184. });
  5185. if (!context) return;
  5186. callable(context.on);
  5187. context.on("_add", this._onAdd);
  5188. context.on("_delete", this._onDelete);
  5189. context.on("_clear", this._onClear);
  5190. };
  5191. // Internal %IteratorPrototype% doesn't expose its constructor
  5192. delete Iterator.prototype.constructor;
  5193. defineProperties(
  5194. Iterator.prototype,
  5195. assign(
  5196. {
  5197. _next: d(function () {
  5198. var i;
  5199. if (!this.__list__) return undefined;
  5200. if (this.__redo__) {
  5201. i = this.__redo__.shift();
  5202. if (i !== undefined) return i;
  5203. }
  5204. if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
  5205. this._unBind();
  5206. return undefined;
  5207. }),
  5208. next: d(function () {
  5209. return this._createResult(this._next());
  5210. }),
  5211. _createResult: d(function (i) {
  5212. if (i === undefined) return { done: true, value: undefined };
  5213. return { done: false, value: this._resolve(i) };
  5214. }),
  5215. _resolve: d(function (i) {
  5216. return this.__list__[i];
  5217. }),
  5218. _unBind: d(function () {
  5219. this.__list__ = null;
  5220. delete this.__redo__;
  5221. if (!this.__context__) return;
  5222. this.__context__.off("_add", this._onAdd);
  5223. this.__context__.off("_delete", this._onDelete);
  5224. this.__context__.off("_clear", this._onClear);
  5225. this.__context__ = null;
  5226. }),
  5227. toString: d(function () {
  5228. return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
  5229. })
  5230. },
  5231. autoBind({
  5232. _onAdd: d(function (index) {
  5233. if (index >= this.__nextIndex__) return;
  5234. ++this.__nextIndex__;
  5235. if (!this.__redo__) {
  5236. defineProperty(this, "__redo__", d("c", [index]));
  5237. return;
  5238. }
  5239. this.__redo__.forEach(function (redo, i) {
  5240. if (redo >= index) this.__redo__[i] = ++redo;
  5241. }, this);
  5242. this.__redo__.push(index);
  5243. }),
  5244. _onDelete: d(function (index) {
  5245. var i;
  5246. if (index >= this.__nextIndex__) return;
  5247. --this.__nextIndex__;
  5248. if (!this.__redo__) return;
  5249. i = this.__redo__.indexOf(index);
  5250. if (i !== -1) this.__redo__.splice(i, 1);
  5251. this.__redo__.forEach(function (redo, j) {
  5252. if (redo > index) this.__redo__[j] = --redo;
  5253. }, this);
  5254. }),
  5255. _onClear: d(function () {
  5256. if (this.__redo__) clear.call(this.__redo__);
  5257. this.__nextIndex__ = 0;
  5258. })
  5259. })
  5260. )
  5261. );
  5262. defineProperty(
  5263. Iterator.prototype,
  5264. Symbol.iterator,
  5265. d(function () {
  5266. return this;
  5267. })
  5268. );
  5269. },{"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){
  5270. "use strict";
  5271. var isArguments = require("es5-ext/function/is-arguments")
  5272. , isValue = require("es5-ext/object/is-value")
  5273. , isString = require("es5-ext/string/is-string");
  5274. var iteratorSymbol = require("es6-symbol").iterator
  5275. , isArray = Array.isArray;
  5276. module.exports = function (value) {
  5277. if (!isValue(value)) return false;
  5278. if (isArray(value)) return true;
  5279. if (isString(value)) return true;
  5280. if (isArguments(value)) return true;
  5281. return typeof value[iteratorSymbol] === "function";
  5282. };
  5283. },{"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){
  5284. // Thanks @mathiasbynens
  5285. // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
  5286. "use strict";
  5287. var setPrototypeOf = require("es5-ext/object/set-prototype-of")
  5288. , d = require("d")
  5289. , Symbol = require("es6-symbol")
  5290. , Iterator = require("./");
  5291. var defineProperty = Object.defineProperty, StringIterator;
  5292. StringIterator = module.exports = function (str) {
  5293. if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
  5294. str = String(str);
  5295. Iterator.call(this, str);
  5296. defineProperty(this, "__length__", d("", str.length));
  5297. };
  5298. if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
  5299. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5300. delete StringIterator.prototype.constructor;
  5301. StringIterator.prototype = Object.create(Iterator.prototype, {
  5302. _next: d(function () {
  5303. if (!this.__list__) return undefined;
  5304. if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
  5305. this._unBind();
  5306. return undefined;
  5307. }),
  5308. _resolve: d(function (i) {
  5309. var char = this.__list__[i], code;
  5310. if (this.__nextIndex__ === this.__length__) return char;
  5311. code = char.charCodeAt(0);
  5312. if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
  5313. return char;
  5314. })
  5315. });
  5316. defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
  5317. },{"./":63,"d":16,"es5-ext/object/set-prototype-of":51,"es6-symbol":73}],66:[function(require,module,exports){
  5318. "use strict";
  5319. var isIterable = require("./is-iterable");
  5320. module.exports = function (value) {
  5321. if (!isIterable(value)) throw new TypeError(value + " is not iterable");
  5322. return value;
  5323. };
  5324. },{"./is-iterable":64}],67:[function(require,module,exports){
  5325. 'use strict';
  5326. module.exports = require('./is-implemented')() ? Map : require('./polyfill');
  5327. },{"./is-implemented":68,"./polyfill":72}],68:[function(require,module,exports){
  5328. 'use strict';
  5329. module.exports = function () {
  5330. var map, iterator, result;
  5331. if (typeof Map !== 'function') return false;
  5332. try {
  5333. // WebKit doesn't support arguments and crashes
  5334. map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
  5335. } catch (e) {
  5336. return false;
  5337. }
  5338. if (String(map) !== '[object Map]') return false;
  5339. if (map.size !== 3) return false;
  5340. if (typeof map.clear !== 'function') return false;
  5341. if (typeof map.delete !== 'function') return false;
  5342. if (typeof map.entries !== 'function') return false;
  5343. if (typeof map.forEach !== 'function') return false;
  5344. if (typeof map.get !== 'function') return false;
  5345. if (typeof map.has !== 'function') return false;
  5346. if (typeof map.keys !== 'function') return false;
  5347. if (typeof map.set !== 'function') return false;
  5348. if (typeof map.values !== 'function') return false;
  5349. iterator = map.entries();
  5350. result = iterator.next();
  5351. if (result.done !== false) return false;
  5352. if (!result.value) return false;
  5353. if (result.value[0] !== 'raz') return false;
  5354. if (result.value[1] !== 'one') return false;
  5355. return true;
  5356. };
  5357. },{}],69:[function(require,module,exports){
  5358. // Exports true if environment provides native `Map` implementation,
  5359. // whatever that is.
  5360. 'use strict';
  5361. module.exports = (function () {
  5362. if (typeof Map === 'undefined') return false;
  5363. return (Object.prototype.toString.call(new Map()) === '[object Map]');
  5364. }());
  5365. },{}],70:[function(require,module,exports){
  5366. 'use strict';
  5367. module.exports = require('es5-ext/object/primitive-set')('key',
  5368. 'value', 'key+value');
  5369. },{"es5-ext/object/primitive-set":50}],71:[function(require,module,exports){
  5370. 'use strict';
  5371. var setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5372. , d = require('d')
  5373. , Iterator = require('es6-iterator')
  5374. , toStringTagSymbol = require('es6-symbol').toStringTag
  5375. , kinds = require('./iterator-kinds')
  5376. , defineProperties = Object.defineProperties
  5377. , unBind = Iterator.prototype._unBind
  5378. , MapIterator;
  5379. MapIterator = module.exports = function (map, kind) {
  5380. if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
  5381. Iterator.call(this, map.__mapKeysData__, map);
  5382. if (!kind || !kinds[kind]) kind = 'key+value';
  5383. defineProperties(this, {
  5384. __kind__: d('', kind),
  5385. __values__: d('w', map.__mapValuesData__)
  5386. });
  5387. };
  5388. if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
  5389. MapIterator.prototype = Object.create(Iterator.prototype, {
  5390. constructor: d(MapIterator),
  5391. _resolve: d(function (i) {
  5392. if (this.__kind__ === 'value') return this.__values__[i];
  5393. if (this.__kind__ === 'key') return this.__list__[i];
  5394. return [this.__list__[i], this.__values__[i]];
  5395. }),
  5396. _unBind: d(function () {
  5397. this.__values__ = null;
  5398. unBind.call(this);
  5399. }),
  5400. toString: d(function () { return '[object Map Iterator]'; })
  5401. });
  5402. Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
  5403. d('c', 'Map Iterator'));
  5404. },{"./iterator-kinds":70,"d":16,"es5-ext/object/set-prototype-of":51,"es6-iterator":63,"es6-symbol":73}],72:[function(require,module,exports){
  5405. 'use strict';
  5406. var clear = require('es5-ext/array/#/clear')
  5407. , eIndexOf = require('es5-ext/array/#/e-index-of')
  5408. , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  5409. , callable = require('es5-ext/object/valid-callable')
  5410. , validValue = require('es5-ext/object/valid-value')
  5411. , d = require('d')
  5412. , ee = require('event-emitter')
  5413. , Symbol = require('es6-symbol')
  5414. , iterator = require('es6-iterator/valid-iterable')
  5415. , forOf = require('es6-iterator/for-of')
  5416. , Iterator = require('./lib/iterator')
  5417. , isNative = require('./is-native-implemented')
  5418. , call = Function.prototype.call
  5419. , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf
  5420. , MapPoly;
  5421. module.exports = MapPoly = function (/*iterable*/) {
  5422. var iterable = arguments[0], keys, values, self;
  5423. if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\'');
  5424. if (isNative && setPrototypeOf && (Map !== MapPoly)) {
  5425. self = setPrototypeOf(new Map(), getPrototypeOf(this));
  5426. } else {
  5427. self = this;
  5428. }
  5429. if (iterable != null) iterator(iterable);
  5430. defineProperties(self, {
  5431. __mapKeysData__: d('c', keys = []),
  5432. __mapValuesData__: d('c', values = [])
  5433. });
  5434. if (!iterable) return self;
  5435. forOf(iterable, function (value) {
  5436. var key = validValue(value)[0];
  5437. value = value[1];
  5438. if (eIndexOf.call(keys, key) !== -1) return;
  5439. keys.push(key);
  5440. values.push(value);
  5441. }, self);
  5442. return self;
  5443. };
  5444. if (isNative) {
  5445. if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
  5446. MapPoly.prototype = Object.create(Map.prototype, {
  5447. constructor: d(MapPoly)
  5448. });
  5449. }
  5450. ee(defineProperties(MapPoly.prototype, {
  5451. clear: d(function () {
  5452. if (!this.__mapKeysData__.length) return;
  5453. clear.call(this.__mapKeysData__);
  5454. clear.call(this.__mapValuesData__);
  5455. this.emit('_clear');
  5456. }),
  5457. delete: d(function (key) {
  5458. var index = eIndexOf.call(this.__mapKeysData__, key);
  5459. if (index === -1) return false;
  5460. this.__mapKeysData__.splice(index, 1);
  5461. this.__mapValuesData__.splice(index, 1);
  5462. this.emit('_delete', index, key);
  5463. return true;
  5464. }),
  5465. entries: d(function () { return new Iterator(this, 'key+value'); }),
  5466. forEach: d(function (cb/*, thisArg*/) {
  5467. var thisArg = arguments[1], iterator, result;
  5468. callable(cb);
  5469. iterator = this.entries();
  5470. result = iterator._next();
  5471. while (result !== undefined) {
  5472. call.call(cb, thisArg, this.__mapValuesData__[result],
  5473. this.__mapKeysData__[result], this);
  5474. result = iterator._next();
  5475. }
  5476. }),
  5477. get: d(function (key) {
  5478. var index = eIndexOf.call(this.__mapKeysData__, key);
  5479. if (index === -1) return;
  5480. return this.__mapValuesData__[index];
  5481. }),
  5482. has: d(function (key) {
  5483. return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
  5484. }),
  5485. keys: d(function () { return new Iterator(this, 'key'); }),
  5486. set: d(function (key, value) {
  5487. var index = eIndexOf.call(this.__mapKeysData__, key), emit;
  5488. if (index === -1) {
  5489. index = this.__mapKeysData__.push(key) - 1;
  5490. emit = true;
  5491. }
  5492. this.__mapValuesData__[index] = value;
  5493. if (emit) this.emit('_add', index, key);
  5494. return this;
  5495. }),
  5496. size: d.gs(function () { return this.__mapKeysData__.length; }),
  5497. values: d(function () { return new Iterator(this, 'value'); }),
  5498. toString: d(function () { return '[object Map]'; })
  5499. }));
  5500. Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
  5501. return this.entries();
  5502. }));
  5503. Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
  5504. },{"./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){
  5505. 'use strict';
  5506. module.exports = require('./is-implemented')() ? Symbol : require('./polyfill');
  5507. },{"./is-implemented":74,"./polyfill":76}],74:[function(require,module,exports){
  5508. 'use strict';
  5509. var validTypes = { object: true, symbol: true };
  5510. module.exports = function () {
  5511. var symbol;
  5512. if (typeof Symbol !== 'function') return false;
  5513. symbol = Symbol('test symbol');
  5514. try { String(symbol); } catch (e) { return false; }
  5515. // Return 'true' also for polyfills
  5516. if (!validTypes[typeof Symbol.iterator]) return false;
  5517. if (!validTypes[typeof Symbol.toPrimitive]) return false;
  5518. if (!validTypes[typeof Symbol.toStringTag]) return false;
  5519. return true;
  5520. };
  5521. },{}],75:[function(require,module,exports){
  5522. 'use strict';
  5523. module.exports = function (x) {
  5524. if (!x) return false;
  5525. if (typeof x === 'symbol') return true;
  5526. if (!x.constructor) return false;
  5527. if (x.constructor.name !== 'Symbol') return false;
  5528. return (x[x.constructor.toStringTag] === 'Symbol');
  5529. };
  5530. },{}],76:[function(require,module,exports){
  5531. // ES2015 Symbol polyfill for environments that do not (or partially) support it
  5532. 'use strict';
  5533. var d = require('d')
  5534. , validateSymbol = require('./validate-symbol')
  5535. , create = Object.create, defineProperties = Object.defineProperties
  5536. , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  5537. , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null)
  5538. , isNativeSafe;
  5539. if (typeof Symbol === 'function') {
  5540. NativeSymbol = Symbol;
  5541. try {
  5542. String(NativeSymbol());
  5543. isNativeSafe = true;
  5544. } catch (ignore) {}
  5545. }
  5546. var generateName = (function () {
  5547. var created = create(null);
  5548. return function (desc) {
  5549. var postfix = 0, name, ie11BugWorkaround;
  5550. while (created[desc + (postfix || '')]) ++postfix;
  5551. desc += (postfix || '');
  5552. created[desc] = true;
  5553. name = '@@' + desc;
  5554. defineProperty(objPrototype, name, d.gs(null, function (value) {
  5555. // For IE11 issue see:
  5556. // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
  5557. // ie11-broken-getters-on-dom-objects
  5558. // https://github.com/medikoo/es6-symbol/issues/12
  5559. if (ie11BugWorkaround) return;
  5560. ie11BugWorkaround = true;
  5561. defineProperty(this, name, d(value));
  5562. ie11BugWorkaround = false;
  5563. }));
  5564. return name;
  5565. };
  5566. }());
  5567. // Internal constructor (not one exposed) for creating Symbol instances.
  5568. // This one is used to ensure that `someSymbol instanceof Symbol` always return false
  5569. HiddenSymbol = function Symbol(description) {
  5570. if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor');
  5571. return SymbolPolyfill(description);
  5572. };
  5573. // Exposed `Symbol` constructor
  5574. // (returns instances of HiddenSymbol)
  5575. module.exports = SymbolPolyfill = function Symbol(description) {
  5576. var symbol;
  5577. if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor');
  5578. if (isNativeSafe) return NativeSymbol(description);
  5579. symbol = create(HiddenSymbol.prototype);
  5580. description = (description === undefined ? '' : String(description));
  5581. return defineProperties(symbol, {
  5582. __description__: d('', description),
  5583. __name__: d('', generateName(description))
  5584. });
  5585. };
  5586. defineProperties(SymbolPolyfill, {
  5587. for: d(function (key) {
  5588. if (globalSymbols[key]) return globalSymbols[key];
  5589. return (globalSymbols[key] = SymbolPolyfill(String(key)));
  5590. }),
  5591. keyFor: d(function (s) {
  5592. var key;
  5593. validateSymbol(s);
  5594. for (key in globalSymbols) if (globalSymbols[key] === s) return key;
  5595. }),
  5596. // To ensure proper interoperability with other native functions (e.g. Array.from)
  5597. // fallback to eventual native implementation of given symbol
  5598. hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
  5599. isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
  5600. SymbolPolyfill('isConcatSpreadable')),
  5601. iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
  5602. match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
  5603. replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
  5604. search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
  5605. species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
  5606. split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
  5607. toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
  5608. toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
  5609. unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
  5610. });
  5611. // Internal tweaks for real symbol producer
  5612. defineProperties(HiddenSymbol.prototype, {
  5613. constructor: d(SymbolPolyfill),
  5614. toString: d('', function () { return this.__name__; })
  5615. });
  5616. // Proper implementation of methods exposed on Symbol.prototype
  5617. // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
  5618. defineProperties(SymbolPolyfill.prototype, {
  5619. toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
  5620. valueOf: d(function () { return validateSymbol(this); })
  5621. });
  5622. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () {
  5623. var symbol = validateSymbol(this);
  5624. if (typeof symbol === 'symbol') return symbol;
  5625. return symbol.toString();
  5626. }));
  5627. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));
  5628. // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
  5629. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
  5630. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
  5631. // Note: It's important to define `toPrimitive` as last one, as some implementations
  5632. // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
  5633. // And that may invoke error in definition flow:
  5634. // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
  5635. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
  5636. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
  5637. },{"./validate-symbol":77,"d":16}],77:[function(require,module,exports){
  5638. 'use strict';
  5639. var isSymbol = require('./is-symbol');
  5640. module.exports = function (value) {
  5641. if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
  5642. return value;
  5643. };
  5644. },{"./is-symbol":75}],78:[function(require,module,exports){
  5645. 'use strict';
  5646. var d = require('d')
  5647. , callable = require('es5-ext/object/valid-callable')
  5648. , apply = Function.prototype.apply, call = Function.prototype.call
  5649. , create = Object.create, defineProperty = Object.defineProperty
  5650. , defineProperties = Object.defineProperties
  5651. , hasOwnProperty = Object.prototype.hasOwnProperty
  5652. , descriptor = { configurable: true, enumerable: false, writable: true }
  5653. , on, once, off, emit, methods, descriptors, base;
  5654. on = function (type, listener) {
  5655. var data;
  5656. callable(listener);
  5657. if (!hasOwnProperty.call(this, '__ee__')) {
  5658. data = descriptor.value = create(null);
  5659. defineProperty(this, '__ee__', descriptor);
  5660. descriptor.value = null;
  5661. } else {
  5662. data = this.__ee__;
  5663. }
  5664. if (!data[type]) data[type] = listener;
  5665. else if (typeof data[type] === 'object') data[type].push(listener);
  5666. else data[type] = [data[type], listener];
  5667. return this;
  5668. };
  5669. once = function (type, listener) {
  5670. var once, self;
  5671. callable(listener);
  5672. self = this;
  5673. on.call(this, type, once = function () {
  5674. off.call(self, type, once);
  5675. apply.call(listener, this, arguments);
  5676. });
  5677. once.__eeOnceListener__ = listener;
  5678. return this;
  5679. };
  5680. off = function (type, listener) {
  5681. var data, listeners, candidate, i;
  5682. callable(listener);
  5683. if (!hasOwnProperty.call(this, '__ee__')) return this;
  5684. data = this.__ee__;
  5685. if (!data[type]) return this;
  5686. listeners = data[type];
  5687. if (typeof listeners === 'object') {
  5688. for (i = 0; (candidate = listeners[i]); ++i) {
  5689. if ((candidate === listener) ||
  5690. (candidate.__eeOnceListener__ === listener)) {
  5691. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  5692. else listeners.splice(i, 1);
  5693. }
  5694. }
  5695. } else {
  5696. if ((listeners === listener) ||
  5697. (listeners.__eeOnceListener__ === listener)) {
  5698. delete data[type];
  5699. }
  5700. }
  5701. return this;
  5702. };
  5703. emit = function (type) {
  5704. var i, l, listener, listeners, args;
  5705. if (!hasOwnProperty.call(this, '__ee__')) return;
  5706. listeners = this.__ee__[type];
  5707. if (!listeners) return;
  5708. if (typeof listeners === 'object') {
  5709. l = arguments.length;
  5710. args = new Array(l - 1);
  5711. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  5712. listeners = listeners.slice();
  5713. for (i = 0; (listener = listeners[i]); ++i) {
  5714. apply.call(listener, this, args);
  5715. }
  5716. } else {
  5717. switch (arguments.length) {
  5718. case 1:
  5719. call.call(listeners, this);
  5720. break;
  5721. case 2:
  5722. call.call(listeners, this, arguments[1]);
  5723. break;
  5724. case 3:
  5725. call.call(listeners, this, arguments[1], arguments[2]);
  5726. break;
  5727. default:
  5728. l = arguments.length;
  5729. args = new Array(l - 1);
  5730. for (i = 1; i < l; ++i) {
  5731. args[i - 1] = arguments[i];
  5732. }
  5733. apply.call(listeners, this, args);
  5734. }
  5735. }
  5736. };
  5737. methods = {
  5738. on: on,
  5739. once: once,
  5740. off: off,
  5741. emit: emit
  5742. };
  5743. descriptors = {
  5744. on: d(on),
  5745. once: d(once),
  5746. off: d(off),
  5747. emit: d(emit)
  5748. };
  5749. base = defineProperties({}, descriptors);
  5750. module.exports = exports = function (o) {
  5751. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  5752. };
  5753. exports.methods = methods;
  5754. },{"d":16,"es5-ext/object/valid-callable":54}],79:[function(require,module,exports){
  5755. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5756. var e, m
  5757. var eLen = (nBytes * 8) - mLen - 1
  5758. var eMax = (1 << eLen) - 1
  5759. var eBias = eMax >> 1
  5760. var nBits = -7
  5761. var i = isLE ? (nBytes - 1) : 0
  5762. var d = isLE ? -1 : 1
  5763. var s = buffer[offset + i]
  5764. i += d
  5765. e = s & ((1 << (-nBits)) - 1)
  5766. s >>= (-nBits)
  5767. nBits += eLen
  5768. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5769. m = e & ((1 << (-nBits)) - 1)
  5770. e >>= (-nBits)
  5771. nBits += mLen
  5772. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5773. if (e === 0) {
  5774. e = 1 - eBias
  5775. } else if (e === eMax) {
  5776. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5777. } else {
  5778. m = m + Math.pow(2, mLen)
  5779. e = e - eBias
  5780. }
  5781. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5782. }
  5783. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5784. var e, m, c
  5785. var eLen = (nBytes * 8) - mLen - 1
  5786. var eMax = (1 << eLen) - 1
  5787. var eBias = eMax >> 1
  5788. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5789. var i = isLE ? 0 : (nBytes - 1)
  5790. var d = isLE ? 1 : -1
  5791. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5792. value = Math.abs(value)
  5793. if (isNaN(value) || value === Infinity) {
  5794. m = isNaN(value) ? 1 : 0
  5795. e = eMax
  5796. } else {
  5797. e = Math.floor(Math.log(value) / Math.LN2)
  5798. if (value * (c = Math.pow(2, -e)) < 1) {
  5799. e--
  5800. c *= 2
  5801. }
  5802. if (e + eBias >= 1) {
  5803. value += rt / c
  5804. } else {
  5805. value += rt * Math.pow(2, 1 - eBias)
  5806. }
  5807. if (value * c >= 2) {
  5808. e++
  5809. c /= 2
  5810. }
  5811. if (e + eBias >= eMax) {
  5812. m = 0
  5813. e = eMax
  5814. } else if (e + eBias >= 1) {
  5815. m = ((value * c) - 1) * Math.pow(2, mLen)
  5816. e = e + eBias
  5817. } else {
  5818. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5819. e = 0
  5820. }
  5821. }
  5822. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5823. e = (e << mLen) | m
  5824. eLen += mLen
  5825. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5826. buffer[offset + i - d] |= s * 128
  5827. }
  5828. },{}],80:[function(require,module,exports){
  5829. if (typeof Object.create === 'function') {
  5830. // implementation from standard node.js 'util' module
  5831. module.exports = function inherits(ctor, superCtor) {
  5832. ctor.super_ = superCtor
  5833. ctor.prototype = Object.create(superCtor.prototype, {
  5834. constructor: {
  5835. value: ctor,
  5836. enumerable: false,
  5837. writable: true,
  5838. configurable: true
  5839. }
  5840. });
  5841. };
  5842. } else {
  5843. // old school shim for old browsers
  5844. module.exports = function inherits(ctor, superCtor) {
  5845. ctor.super_ = superCtor
  5846. var TempCtor = function () {}
  5847. TempCtor.prototype = superCtor.prototype
  5848. ctor.prototype = new TempCtor()
  5849. ctor.prototype.constructor = ctor
  5850. }
  5851. }
  5852. },{}],81:[function(require,module,exports){
  5853. /*!
  5854. * Determine if an object is a Buffer
  5855. *
  5856. * @author Feross Aboukhadijeh <https://feross.org>
  5857. * @license MIT
  5858. */
  5859. // The _isBuffer check is for Safari 5-7 support, because it's missing
  5860. // Object.prototype.constructor. Remove this eventually
  5861. module.exports = function (obj) {
  5862. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  5863. }
  5864. function isBuffer (obj) {
  5865. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  5866. }
  5867. // For Node v0.10 support. Remove this eventually.
  5868. function isSlowBuffer (obj) {
  5869. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  5870. }
  5871. },{}],82:[function(require,module,exports){
  5872. 'use strict'
  5873. var Buffer = require('safe-buffer').Buffer
  5874. /* Protocol - protocol constants */
  5875. var protocol = module.exports
  5876. /* Command code => mnemonic */
  5877. protocol.types = {
  5878. 0: 'reserved',
  5879. 1: 'connect',
  5880. 2: 'connack',
  5881. 3: 'publish',
  5882. 4: 'puback',
  5883. 5: 'pubrec',
  5884. 6: 'pubrel',
  5885. 7: 'pubcomp',
  5886. 8: 'subscribe',
  5887. 9: 'suback',
  5888. 10: 'unsubscribe',
  5889. 11: 'unsuback',
  5890. 12: 'pingreq',
  5891. 13: 'pingresp',
  5892. 14: 'disconnect',
  5893. 15: 'auth'
  5894. }
  5895. /* Mnemonic => Command code */
  5896. protocol.codes = {}
  5897. for (var k in protocol.types) {
  5898. var v = protocol.types[k]
  5899. protocol.codes[v] = k
  5900. }
  5901. /* Header */
  5902. protocol.CMD_SHIFT = 4
  5903. protocol.CMD_MASK = 0xF0
  5904. protocol.DUP_MASK = 0x08
  5905. protocol.QOS_MASK = 0x03
  5906. protocol.QOS_SHIFT = 1
  5907. protocol.RETAIN_MASK = 0x01
  5908. /* Length */
  5909. protocol.LENGTH_MASK = 0x7F
  5910. protocol.LENGTH_FIN_MASK = 0x80
  5911. /* Connack */
  5912. protocol.SESSIONPRESENT_MASK = 0x01
  5913. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  5914. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  5915. /* Connect */
  5916. protocol.USERNAME_MASK = 0x80
  5917. protocol.PASSWORD_MASK = 0x40
  5918. protocol.WILL_RETAIN_MASK = 0x20
  5919. protocol.WILL_QOS_MASK = 0x18
  5920. protocol.WILL_QOS_SHIFT = 3
  5921. protocol.WILL_FLAG_MASK = 0x04
  5922. protocol.CLEAN_SESSION_MASK = 0x02
  5923. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  5924. /* Properties */
  5925. protocol.properties = {
  5926. sessionExpiryInterval: 17,
  5927. willDelayInterval: 24,
  5928. receiveMaximum: 33,
  5929. maximumPacketSize: 39,
  5930. topicAliasMaximum: 34,
  5931. requestResponseInformation: 25,
  5932. requestProblemInformation: 23,
  5933. userProperties: 38,
  5934. authenticationMethod: 21,
  5935. authenticationData: 22,
  5936. payloadFormatIndicator: 1,
  5937. messageExpiryInterval: 2,
  5938. contentType: 3,
  5939. responseTopic: 8,
  5940. correlationData: 9,
  5941. maximumQoS: 36,
  5942. retainAvailable: 37,
  5943. assignedClientIdentifier: 18,
  5944. reasonString: 31,
  5945. wildcardSubscriptionAvailable: 40,
  5946. subscriptionIdentifiersAvailable: 41,
  5947. sharedSubscriptionAvailable: 42,
  5948. serverKeepAlive: 19,
  5949. responseInformation: 26,
  5950. serverReference: 28,
  5951. topicAlias: 35,
  5952. subscriptionIdentifier: 11
  5953. }
  5954. protocol.propertiesCodes = {}
  5955. for (var prop in protocol.properties) {
  5956. var id = protocol.properties[prop]
  5957. protocol.propertiesCodes[id] = prop
  5958. }
  5959. protocol.propertiesTypes = {
  5960. sessionExpiryInterval: 'int32',
  5961. willDelayInterval: 'int32',
  5962. receiveMaximum: 'int16',
  5963. maximumPacketSize: 'int32',
  5964. topicAliasMaximum: 'int16',
  5965. requestResponseInformation: 'byte',
  5966. requestProblemInformation: 'byte',
  5967. userProperties: 'pair',
  5968. authenticationMethod: 'string',
  5969. authenticationData: 'binary',
  5970. payloadFormatIndicator: 'byte',
  5971. messageExpiryInterval: 'int32',
  5972. contentType: 'string',
  5973. responseTopic: 'string',
  5974. correlationData: 'binary',
  5975. maximumQoS: 'int8',
  5976. retainAvailable: 'byte',
  5977. assignedClientIdentifier: 'string',
  5978. reasonString: 'string',
  5979. wildcardSubscriptionAvailable: 'byte',
  5980. subscriptionIdentifiersAvailable: 'byte',
  5981. sharedSubscriptionAvailable: 'byte',
  5982. serverKeepAlive: 'int32',
  5983. responseInformation: 'string',
  5984. serverReference: 'string',
  5985. topicAlias: 'int16',
  5986. subscriptionIdentifier: 'var'
  5987. }
  5988. function genHeader (type) {
  5989. return [0, 1, 2].map(function (qos) {
  5990. return [0, 1].map(function (dup) {
  5991. return [0, 1].map(function (retain) {
  5992. var buf = new Buffer(1)
  5993. buf.writeUInt8(
  5994. protocol.codes[type] << protocol.CMD_SHIFT |
  5995. (dup ? protocol.DUP_MASK : 0) |
  5996. qos << protocol.QOS_SHIFT | retain, 0, true)
  5997. return buf
  5998. })
  5999. })
  6000. })
  6001. }
  6002. /* Publish */
  6003. protocol.PUBLISH_HEADER = genHeader('publish')
  6004. /* Subscribe */
  6005. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  6006. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  6007. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  6008. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  6009. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  6010. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  6011. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  6012. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  6013. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  6014. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  6015. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  6016. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  6017. /* Unsubscribe */
  6018. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  6019. /* Confirmations */
  6020. protocol.ACKS = {
  6021. unsuback: genHeader('unsuback'),
  6022. puback: genHeader('puback'),
  6023. pubcomp: genHeader('pubcomp'),
  6024. pubrel: genHeader('pubrel'),
  6025. pubrec: genHeader('pubrec')
  6026. }
  6027. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  6028. /* Protocol versions */
  6029. protocol.VERSION3 = Buffer.from([3])
  6030. protocol.VERSION4 = Buffer.from([4])
  6031. protocol.VERSION5 = Buffer.from([5])
  6032. /* QoS */
  6033. protocol.QOS = [0, 1, 2].map(function (qos) {
  6034. return Buffer.from([qos])
  6035. })
  6036. /* Empty packets */
  6037. protocol.EMPTY = {
  6038. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  6039. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  6040. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  6041. }
  6042. },{"safe-buffer":110}],83:[function(require,module,exports){
  6043. 'use strict'
  6044. var Buffer = require('safe-buffer').Buffer
  6045. var writeToStream = require('./writeToStream')
  6046. var EE = require('events').EventEmitter
  6047. var inherits = require('inherits')
  6048. function generate (packet, opts) {
  6049. var stream = new Accumulator()
  6050. writeToStream(packet, stream, opts)
  6051. return stream.concat()
  6052. }
  6053. function Accumulator () {
  6054. this._array = new Array(20)
  6055. this._i = 0
  6056. }
  6057. inherits(Accumulator, EE)
  6058. Accumulator.prototype.write = function (chunk) {
  6059. this._array[this._i++] = chunk
  6060. return true
  6061. }
  6062. Accumulator.prototype.concat = function () {
  6063. var length = 0
  6064. var lengths = new Array(this._array.length)
  6065. var list = this._array
  6066. var pos = 0
  6067. var i
  6068. var result
  6069. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6070. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  6071. else lengths[i] = Buffer.byteLength(list[i])
  6072. length += lengths[i]
  6073. }
  6074. result = Buffer.allocUnsafe(length)
  6075. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6076. if (typeof list[i] !== 'string') {
  6077. list[i].copy(result, pos)
  6078. pos += lengths[i]
  6079. } else {
  6080. result.write(list[i], pos)
  6081. pos += lengths[i]
  6082. }
  6083. }
  6084. return result
  6085. }
  6086. module.exports = generate
  6087. },{"./writeToStream":89,"events":13,"inherits":80,"safe-buffer":110}],84:[function(require,module,exports){
  6088. 'use strict'
  6089. exports.parser = require('./parser')
  6090. exports.generate = require('./generate')
  6091. exports.writeToStream = require('./writeToStream')
  6092. },{"./generate":83,"./parser":88,"./writeToStream":89}],85:[function(require,module,exports){
  6093. var DuplexStream = require('readable-stream/duplex')
  6094. , util = require('util')
  6095. , Buffer = require('safe-buffer').Buffer
  6096. function BufferList (callback) {
  6097. if (!(this instanceof BufferList))
  6098. return new BufferList(callback)
  6099. this._bufs = []
  6100. this.length = 0
  6101. if (typeof callback == 'function') {
  6102. this._callback = callback
  6103. var piper = function piper (err) {
  6104. if (this._callback) {
  6105. this._callback(err)
  6106. this._callback = null
  6107. }
  6108. }.bind(this)
  6109. this.on('pipe', function onPipe (src) {
  6110. src.on('error', piper)
  6111. })
  6112. this.on('unpipe', function onUnpipe (src) {
  6113. src.removeListener('error', piper)
  6114. })
  6115. } else {
  6116. this.append(callback)
  6117. }
  6118. DuplexStream.call(this)
  6119. }
  6120. util.inherits(BufferList, DuplexStream)
  6121. BufferList.prototype._offset = function _offset (offset) {
  6122. var tot = 0, i = 0, _t
  6123. if (offset === 0) return [ 0, 0 ]
  6124. for (; i < this._bufs.length; i++) {
  6125. _t = tot + this._bufs[i].length
  6126. if (offset < _t || i == this._bufs.length - 1)
  6127. return [ i, offset - tot ]
  6128. tot = _t
  6129. }
  6130. }
  6131. BufferList.prototype.append = function append (buf) {
  6132. var i = 0
  6133. if (Buffer.isBuffer(buf)) {
  6134. this._appendBuffer(buf);
  6135. } else if (Array.isArray(buf)) {
  6136. for (; i < buf.length; i++)
  6137. this.append(buf[i])
  6138. } else if (buf instanceof BufferList) {
  6139. // unwrap argument into individual BufferLists
  6140. for (; i < buf._bufs.length; i++)
  6141. this.append(buf._bufs[i])
  6142. } else if (buf != null) {
  6143. // coerce number arguments to strings, since Buffer(number) does
  6144. // uninitialized memory allocation
  6145. if (typeof buf == 'number')
  6146. buf = buf.toString()
  6147. this._appendBuffer(Buffer.from(buf));
  6148. }
  6149. return this
  6150. }
  6151. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  6152. this._bufs.push(buf)
  6153. this.length += buf.length
  6154. }
  6155. BufferList.prototype._write = function _write (buf, encoding, callback) {
  6156. this._appendBuffer(buf)
  6157. if (typeof callback == 'function')
  6158. callback()
  6159. }
  6160. BufferList.prototype._read = function _read (size) {
  6161. if (!this.length)
  6162. return this.push(null)
  6163. size = Math.min(size, this.length)
  6164. this.push(this.slice(0, size))
  6165. this.consume(size)
  6166. }
  6167. BufferList.prototype.end = function end (chunk) {
  6168. DuplexStream.prototype.end.call(this, chunk)
  6169. if (this._callback) {
  6170. this._callback(null, this.slice())
  6171. this._callback = null
  6172. }
  6173. }
  6174. BufferList.prototype.get = function get (index) {
  6175. return this.slice(index, index + 1)[0]
  6176. }
  6177. BufferList.prototype.slice = function slice (start, end) {
  6178. if (typeof start == 'number' && start < 0)
  6179. start += this.length
  6180. if (typeof end == 'number' && end < 0)
  6181. end += this.length
  6182. return this.copy(null, 0, start, end)
  6183. }
  6184. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  6185. if (typeof srcStart != 'number' || srcStart < 0)
  6186. srcStart = 0
  6187. if (typeof srcEnd != 'number' || srcEnd > this.length)
  6188. srcEnd = this.length
  6189. if (srcStart >= this.length)
  6190. return dst || Buffer.alloc(0)
  6191. if (srcEnd <= 0)
  6192. return dst || Buffer.alloc(0)
  6193. var copy = !!dst
  6194. , off = this._offset(srcStart)
  6195. , len = srcEnd - srcStart
  6196. , bytes = len
  6197. , bufoff = (copy && dstStart) || 0
  6198. , start = off[1]
  6199. , l
  6200. , i
  6201. // copy/slice everything
  6202. if (srcStart === 0 && srcEnd == this.length) {
  6203. if (!copy) { // slice, but full concat if multiple buffers
  6204. return this._bufs.length === 1
  6205. ? this._bufs[0]
  6206. : Buffer.concat(this._bufs, this.length)
  6207. }
  6208. // copy, need to copy individual buffers
  6209. for (i = 0; i < this._bufs.length; i++) {
  6210. this._bufs[i].copy(dst, bufoff)
  6211. bufoff += this._bufs[i].length
  6212. }
  6213. return dst
  6214. }
  6215. // easy, cheap case where it's a subset of one of the buffers
  6216. if (bytes <= this._bufs[off[0]].length - start) {
  6217. return copy
  6218. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  6219. : this._bufs[off[0]].slice(start, start + bytes)
  6220. }
  6221. if (!copy) // a slice, we need something to copy in to
  6222. dst = Buffer.allocUnsafe(len)
  6223. for (i = off[0]; i < this._bufs.length; i++) {
  6224. l = this._bufs[i].length - start
  6225. if (bytes > l) {
  6226. this._bufs[i].copy(dst, bufoff, start)
  6227. } else {
  6228. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  6229. break
  6230. }
  6231. bufoff += l
  6232. bytes -= l
  6233. if (start)
  6234. start = 0
  6235. }
  6236. return dst
  6237. }
  6238. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  6239. start = start || 0
  6240. end = end || this.length
  6241. if (start < 0)
  6242. start += this.length
  6243. if (end < 0)
  6244. end += this.length
  6245. var startOffset = this._offset(start)
  6246. , endOffset = this._offset(end)
  6247. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  6248. if (endOffset[1] == 0)
  6249. buffers.pop()
  6250. else
  6251. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  6252. if (startOffset[1] != 0)
  6253. buffers[0] = buffers[0].slice(startOffset[1])
  6254. return new BufferList(buffers)
  6255. }
  6256. BufferList.prototype.toString = function toString (encoding, start, end) {
  6257. return this.slice(start, end).toString(encoding)
  6258. }
  6259. BufferList.prototype.consume = function consume (bytes) {
  6260. while (this._bufs.length) {
  6261. if (bytes >= this._bufs[0].length) {
  6262. bytes -= this._bufs[0].length
  6263. this.length -= this._bufs[0].length
  6264. this._bufs.shift()
  6265. } else {
  6266. this._bufs[0] = this._bufs[0].slice(bytes)
  6267. this.length -= bytes
  6268. break
  6269. }
  6270. }
  6271. return this
  6272. }
  6273. BufferList.prototype.duplicate = function duplicate () {
  6274. var i = 0
  6275. , copy = new BufferList()
  6276. for (; i < this._bufs.length; i++)
  6277. copy.append(this._bufs[i])
  6278. return copy
  6279. }
  6280. BufferList.prototype.destroy = function destroy () {
  6281. this._bufs.length = 0
  6282. this.length = 0
  6283. this.push(null)
  6284. }
  6285. ;(function () {
  6286. var methods = {
  6287. 'readDoubleBE' : 8
  6288. , 'readDoubleLE' : 8
  6289. , 'readFloatBE' : 4
  6290. , 'readFloatLE' : 4
  6291. , 'readInt32BE' : 4
  6292. , 'readInt32LE' : 4
  6293. , 'readUInt32BE' : 4
  6294. , 'readUInt32LE' : 4
  6295. , 'readInt16BE' : 2
  6296. , 'readInt16LE' : 2
  6297. , 'readUInt16BE' : 2
  6298. , 'readUInt16LE' : 2
  6299. , 'readInt8' : 1
  6300. , 'readUInt8' : 1
  6301. }
  6302. for (var m in methods) {
  6303. (function (m) {
  6304. BufferList.prototype[m] = function (offset) {
  6305. return this.slice(offset, offset + methods[m])[m](0)
  6306. }
  6307. }(m))
  6308. }
  6309. }())
  6310. module.exports = BufferList
  6311. },{"readable-stream/duplex":97,"safe-buffer":110,"util":117}],86:[function(require,module,exports){
  6312. 'use strict'
  6313. var Buffer = require('safe-buffer').Buffer
  6314. var max = 65536
  6315. var cache = {}
  6316. function generateBuffer (i) {
  6317. var buffer = Buffer.allocUnsafe(2)
  6318. buffer.writeUInt8(i >> 8, 0)
  6319. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  6320. return buffer
  6321. }
  6322. function generateCache () {
  6323. for (var i = 0; i < max; i++) {
  6324. cache[i] = generateBuffer(i)
  6325. }
  6326. }
  6327. /**
  6328. * calcVariableByteIntLength - calculate the variable byte integer
  6329. * length field
  6330. *
  6331. * @api private
  6332. */
  6333. function calcVariableByteIntLength (length) {
  6334. if (length >= 0 && length < 128) return 1
  6335. else if (length >= 128 && length < 16384) return 2
  6336. else if (length >= 16384 && length < 2097152) return 3
  6337. else if (length >= 2097152 && length < 268435456) return 4
  6338. else return 0
  6339. }
  6340. function genBufVariableByteInt (num) {
  6341. var digit = 0
  6342. var pos = 0
  6343. var length = calcVariableByteIntLength(num)
  6344. var buffer = Buffer.allocUnsafe(length)
  6345. do {
  6346. digit = num % 128 | 0
  6347. num = num / 128 | 0
  6348. if (num > 0) digit = digit | 0x80
  6349. buffer.writeUInt8(digit, pos++)
  6350. } while (num > 0)
  6351. return {
  6352. data: buffer,
  6353. length: length
  6354. }
  6355. }
  6356. function generate4ByteBuffer (num) {
  6357. var buffer = Buffer.allocUnsafe(4)
  6358. buffer.writeUInt32BE(num, 0)
  6359. return buffer
  6360. }
  6361. module.exports = {
  6362. cache: cache,
  6363. generateCache: generateCache,
  6364. generateNumber: generateBuffer,
  6365. genBufVariableByteInt: genBufVariableByteInt,
  6366. generate4ByteBuffer: generate4ByteBuffer
  6367. }
  6368. },{"safe-buffer":110}],87:[function(require,module,exports){
  6369. function Packet () {
  6370. this.cmd = null
  6371. this.retain = false
  6372. this.qos = 0
  6373. this.dup = false
  6374. this.length = -1
  6375. this.topic = null
  6376. this.payload = null
  6377. }
  6378. module.exports = Packet
  6379. },{}],88:[function(require,module,exports){
  6380. 'use strict'
  6381. var bl = require('bl')
  6382. var inherits = require('inherits')
  6383. var EE = require('events').EventEmitter
  6384. var Packet = require('./packet')
  6385. var constants = require('./constants')
  6386. function Parser (opt) {
  6387. if (!(this instanceof Parser)) return new Parser(opt)
  6388. this.settings = opt || {}
  6389. this._states = [
  6390. '_parseHeader',
  6391. '_parseLength',
  6392. '_parsePayload',
  6393. '_newPacket'
  6394. ]
  6395. this._resetState()
  6396. }
  6397. inherits(Parser, EE)
  6398. Parser.prototype._resetState = function () {
  6399. this.packet = new Packet()
  6400. this.error = null
  6401. this._list = bl()
  6402. this._stateCounter = 0
  6403. }
  6404. Parser.prototype.parse = function (buf) {
  6405. if (this.error) this._resetState()
  6406. this._list.append(buf)
  6407. while ((this.packet.length !== -1 || this._list.length > 0) &&
  6408. this[this._states[this._stateCounter]]() &&
  6409. !this.error) {
  6410. this._stateCounter++
  6411. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  6412. }
  6413. return this._list.length
  6414. }
  6415. Parser.prototype._parseHeader = function () {
  6416. // There is at least one byte in the buffer
  6417. var zero = this._list.readUInt8(0)
  6418. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  6419. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  6420. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  6421. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  6422. this._list.consume(1)
  6423. return true
  6424. }
  6425. Parser.prototype._parseLength = function () {
  6426. // There is at least one byte in the list
  6427. var result = this._parseVarByteNum(true)
  6428. if (result) {
  6429. this.packet.length = result.value
  6430. this._list.consume(result.bytes)
  6431. }
  6432. return !!result
  6433. }
  6434. Parser.prototype._parsePayload = function () {
  6435. var result = false
  6436. // Do we have a payload? Do we have enough data to complete the payload?
  6437. // PINGs have no payload
  6438. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  6439. this._pos = 0
  6440. switch (this.packet.cmd) {
  6441. case 'connect':
  6442. this._parseConnect()
  6443. break
  6444. case 'connack':
  6445. this._parseConnack()
  6446. break
  6447. case 'publish':
  6448. this._parsePublish()
  6449. break
  6450. case 'puback':
  6451. case 'pubrec':
  6452. case 'pubrel':
  6453. case 'pubcomp':
  6454. this._parseConfirmation()
  6455. break
  6456. case 'subscribe':
  6457. this._parseSubscribe()
  6458. break
  6459. case 'suback':
  6460. this._parseSuback()
  6461. break
  6462. case 'unsubscribe':
  6463. this._parseUnsubscribe()
  6464. break
  6465. case 'unsuback':
  6466. this._parseUnsuback()
  6467. break
  6468. case 'pingreq':
  6469. case 'pingresp':
  6470. // These are empty, nothing to do
  6471. break
  6472. case 'disconnect':
  6473. this._parseDisconnect()
  6474. break
  6475. case 'auth':
  6476. this._parseAuth()
  6477. break
  6478. default:
  6479. this._emitError(new Error('Not supported'))
  6480. }
  6481. result = true
  6482. }
  6483. return result
  6484. }
  6485. Parser.prototype._parseConnect = function () {
  6486. var protocolId // Protocol ID
  6487. var clientId // Client ID
  6488. var topic // Will topic
  6489. var payload // Will payload
  6490. var password // Password
  6491. var username // Username
  6492. var flags = {}
  6493. var packet = this.packet
  6494. // Parse protocolId
  6495. protocolId = this._parseString()
  6496. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  6497. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  6498. return this._emitError(new Error('Invalid protocolId'))
  6499. }
  6500. packet.protocolId = protocolId
  6501. // Parse constants version number
  6502. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  6503. packet.protocolVersion = this._list.readUInt8(this._pos)
  6504. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  6505. return this._emitError(new Error('Invalid protocol version'))
  6506. }
  6507. this._pos++
  6508. if (this._pos >= this._list.length) {
  6509. return this._emitError(new Error('Packet too short'))
  6510. }
  6511. // Parse connect flags
  6512. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  6513. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  6514. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  6515. if (flags.will) {
  6516. packet.will = {}
  6517. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  6518. packet.will.qos = (this._list.readUInt8(this._pos) &
  6519. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  6520. }
  6521. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  6522. this._pos++
  6523. // Parse keepalive
  6524. packet.keepalive = this._parseNum()
  6525. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  6526. // parse properties
  6527. if (packet.protocolVersion === 5) {
  6528. var properties = this._parseProperties()
  6529. if (Object.getOwnPropertyNames(properties).length) {
  6530. packet.properties = properties
  6531. }
  6532. }
  6533. // Parse clientId
  6534. clientId = this._parseString()
  6535. if (clientId === null) return this._emitError(new Error('Packet too short'))
  6536. packet.clientId = clientId
  6537. if (flags.will) {
  6538. if (packet.protocolVersion === 5) {
  6539. var willProperties = this._parseProperties()
  6540. if (Object.getOwnPropertyNames(willProperties).length) {
  6541. packet.will.properties = willProperties
  6542. }
  6543. }
  6544. // Parse will topic
  6545. topic = this._parseString()
  6546. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  6547. packet.will.topic = topic
  6548. // Parse will payload
  6549. payload = this._parseBuffer()
  6550. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  6551. packet.will.payload = payload
  6552. }
  6553. // Parse username
  6554. if (flags.username) {
  6555. username = this._parseString()
  6556. if (username === null) return this._emitError(new Error('Cannot parse username'))
  6557. packet.username = username
  6558. }
  6559. // Parse password
  6560. if (flags.password) {
  6561. password = this._parseBuffer()
  6562. if (password === null) return this._emitError(new Error('Cannot parse password'))
  6563. packet.password = password
  6564. }
  6565. // need for right parse auth packet and self set up
  6566. this.settings = packet
  6567. return packet
  6568. }
  6569. Parser.prototype._parseConnack = function () {
  6570. var packet = this.packet
  6571. if (this._list.length < 2) return null
  6572. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  6573. if (this.settings.protocolVersion === 5) {
  6574. packet.reasonCode = this._list.readUInt8(this._pos++)
  6575. } else {
  6576. packet.returnCode = this._list.readUInt8(this._pos++)
  6577. }
  6578. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  6579. // mqtt 5 properties
  6580. if (this.settings.protocolVersion === 5) {
  6581. var properties = this._parseProperties()
  6582. if (Object.getOwnPropertyNames(properties).length) {
  6583. packet.properties = properties
  6584. }
  6585. }
  6586. }
  6587. Parser.prototype._parsePublish = function () {
  6588. var packet = this.packet
  6589. packet.topic = this._parseString()
  6590. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  6591. // Parse messageId
  6592. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  6593. // Properties mqtt 5
  6594. if (this.settings.protocolVersion === 5) {
  6595. var properties = this._parseProperties()
  6596. if (Object.getOwnPropertyNames(properties).length) {
  6597. packet.properties = properties
  6598. }
  6599. }
  6600. packet.payload = this._list.slice(this._pos, packet.length)
  6601. }
  6602. Parser.prototype._parseSubscribe = function () {
  6603. var packet = this.packet
  6604. var topic
  6605. var options
  6606. var qos
  6607. var rh
  6608. var rap
  6609. var nl
  6610. var subscription
  6611. if (packet.qos !== 1) {
  6612. return this._emitError(new Error('Wrong subscribe header'))
  6613. }
  6614. packet.subscriptions = []
  6615. if (!this._parseMessageId()) { return }
  6616. // Properties mqtt 5
  6617. if (this.settings.protocolVersion === 5) {
  6618. var properties = this._parseProperties()
  6619. if (Object.getOwnPropertyNames(properties).length) {
  6620. packet.properties = properties
  6621. }
  6622. }
  6623. while (this._pos < packet.length) {
  6624. // Parse topic
  6625. topic = this._parseString()
  6626. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  6627. options = this._parseByte()
  6628. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  6629. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  6630. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  6631. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  6632. subscription = { topic: topic, qos: qos }
  6633. // mqtt 5 options
  6634. if (this.settings.protocolVersion === 5) {
  6635. subscription.nl = nl
  6636. subscription.rap = rap
  6637. subscription.rh = rh
  6638. }
  6639. // Push pair to subscriptions
  6640. packet.subscriptions.push(subscription)
  6641. }
  6642. }
  6643. Parser.prototype._parseSuback = function () {
  6644. var packet = this.packet
  6645. this.packet.granted = []
  6646. if (!this._parseMessageId()) { return }
  6647. // Properties mqtt 5
  6648. if (this.settings.protocolVersion === 5) {
  6649. var properties = this._parseProperties()
  6650. if (Object.getOwnPropertyNames(properties).length) {
  6651. packet.properties = properties
  6652. }
  6653. }
  6654. // Parse granted QoSes
  6655. while (this._pos < this.packet.length) {
  6656. this.packet.granted.push(this._list.readUInt8(this._pos++))
  6657. }
  6658. }
  6659. Parser.prototype._parseUnsubscribe = function () {
  6660. var packet = this.packet
  6661. packet.unsubscriptions = []
  6662. // Parse messageId
  6663. if (!this._parseMessageId()) { return }
  6664. // Properties mqtt 5
  6665. if (this.settings.protocolVersion === 5) {
  6666. var properties = this._parseProperties()
  6667. if (Object.getOwnPropertyNames(properties).length) {
  6668. packet.properties = properties
  6669. }
  6670. }
  6671. while (this._pos < packet.length) {
  6672. var topic
  6673. // Parse topic
  6674. topic = this._parseString()
  6675. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  6676. // Push topic to unsubscriptions
  6677. packet.unsubscriptions.push(topic)
  6678. }
  6679. }
  6680. Parser.prototype._parseUnsuback = function () {
  6681. var packet = this.packet
  6682. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  6683. // Properties mqtt 5
  6684. if (this.settings.protocolVersion === 5) {
  6685. var properties = this._parseProperties()
  6686. if (Object.getOwnPropertyNames(properties).length) {
  6687. packet.properties = properties
  6688. }
  6689. // Parse granted QoSes
  6690. packet.granted = []
  6691. while (this._pos < this.packet.length) {
  6692. this.packet.granted.push(this._list.readUInt8(this._pos++))
  6693. }
  6694. }
  6695. }
  6696. // parse packets like puback, pubrec, pubrel, pubcomp
  6697. Parser.prototype._parseConfirmation = function () {
  6698. var packet = this.packet
  6699. this._parseMessageId()
  6700. if (this.settings.protocolVersion === 5) {
  6701. if (packet.length > 2) {
  6702. // response code
  6703. packet.reasonCode = this._parseByte()
  6704. // properies mqtt 5
  6705. var properties = this._parseProperties()
  6706. if (Object.getOwnPropertyNames(properties).length) {
  6707. packet.properties = properties
  6708. }
  6709. }
  6710. }
  6711. return true
  6712. }
  6713. // parse disconnect packet
  6714. Parser.prototype._parseDisconnect = function () {
  6715. var packet = this.packet
  6716. if (this.settings.protocolVersion === 5) {
  6717. // response code
  6718. packet.reasonCode = this._parseByte()
  6719. // properies mqtt 5
  6720. var properties = this._parseProperties()
  6721. if (Object.getOwnPropertyNames(properties).length) {
  6722. packet.properties = properties
  6723. }
  6724. }
  6725. return true
  6726. }
  6727. // parse auth packet
  6728. Parser.prototype._parseAuth = function () {
  6729. var packet = this.packet
  6730. if (this.settings.protocolVersion !== 5) {
  6731. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  6732. }
  6733. // response code
  6734. packet.reasonCode = this._parseByte()
  6735. // properies mqtt 5
  6736. var properties = this._parseProperties()
  6737. if (Object.getOwnPropertyNames(properties).length) {
  6738. packet.properties = properties
  6739. }
  6740. return true
  6741. }
  6742. Parser.prototype._parseMessageId = function () {
  6743. var packet = this.packet
  6744. packet.messageId = this._parseNum()
  6745. if (packet.messageId === null) {
  6746. this._emitError(new Error('Cannot parse messageId'))
  6747. return false
  6748. }
  6749. return true
  6750. }
  6751. Parser.prototype._parseString = function (maybeBuffer) {
  6752. var length = this._parseNum()
  6753. var result
  6754. var end = length + this._pos
  6755. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  6756. result = this._list.toString('utf8', this._pos, end)
  6757. this._pos += length
  6758. return result
  6759. }
  6760. Parser.prototype._parseStringPair = function () {
  6761. return {
  6762. name: this._parseString(),
  6763. value: this._parseString()
  6764. }
  6765. }
  6766. Parser.prototype._parseBuffer = function () {
  6767. var length = this._parseNum()
  6768. var result
  6769. var end = length + this._pos
  6770. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  6771. result = this._list.slice(this._pos, end)
  6772. this._pos += length
  6773. return result
  6774. }
  6775. Parser.prototype._parseNum = function () {
  6776. if (this._list.length - this._pos < 2) return -1
  6777. var result = this._list.readUInt16BE(this._pos)
  6778. this._pos += 2
  6779. return result
  6780. }
  6781. Parser.prototype._parse4ByteNum = function () {
  6782. if (this._list.length - this._pos < 4) return -1
  6783. var result = this._list.readUInt32BE(this._pos)
  6784. this._pos += 4
  6785. return result
  6786. }
  6787. Parser.prototype._parseVarByteNum = function (fullInfoFlag) {
  6788. var bytes = 0
  6789. var mul = 1
  6790. var length = 0
  6791. var result = true
  6792. var current
  6793. var padding = this._pos ? this._pos : 0
  6794. while (bytes < 5) {
  6795. current = this._list.readUInt8(padding + bytes++)
  6796. length += mul * (current & constants.LENGTH_MASK)
  6797. mul *= 0x80
  6798. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  6799. if (this._list.length <= bytes) {
  6800. result = false
  6801. break
  6802. }
  6803. }
  6804. if (padding) {
  6805. this._pos += bytes
  6806. }
  6807. result = result
  6808. ? fullInfoFlag ? {
  6809. bytes: bytes,
  6810. value: length
  6811. } : length
  6812. : false
  6813. return result
  6814. }
  6815. Parser.prototype._parseByte = function () {
  6816. var result = this._list.readUInt8(this._pos)
  6817. this._pos++
  6818. return result
  6819. }
  6820. Parser.prototype._parseByType = function (type) {
  6821. switch (type) {
  6822. case 'byte': {
  6823. return this._parseByte() !== 0
  6824. }
  6825. case 'int8': {
  6826. return this._parseByte()
  6827. }
  6828. case 'int16': {
  6829. return this._parseNum()
  6830. }
  6831. case 'int32': {
  6832. return this._parse4ByteNum()
  6833. }
  6834. case 'var': {
  6835. return this._parseVarByteNum()
  6836. }
  6837. case 'string': {
  6838. return this._parseString()
  6839. }
  6840. case 'pair': {
  6841. return this._parseStringPair()
  6842. }
  6843. case 'binary': {
  6844. return this._parseBuffer()
  6845. }
  6846. }
  6847. }
  6848. Parser.prototype._parseProperties = function () {
  6849. var length = this._parseVarByteNum()
  6850. var start = this._pos
  6851. var end = start + length
  6852. var result = {}
  6853. while (this._pos < end) {
  6854. var type = this._parseByte()
  6855. var name = constants.propertiesCodes[type]
  6856. if (!name) {
  6857. this._emitError(new Error('Unknown property'))
  6858. return false
  6859. }
  6860. // user properties process
  6861. if (name === 'userProperties') {
  6862. if (!result[name]) {
  6863. result[name] = {}
  6864. }
  6865. var currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  6866. result[name][currentUserProperty.name] = currentUserProperty.value
  6867. continue
  6868. }
  6869. result[name] = this._parseByType(constants.propertiesTypes[name])
  6870. }
  6871. return result
  6872. }
  6873. Parser.prototype._newPacket = function () {
  6874. if (this.packet) {
  6875. this._list.consume(this.packet.length)
  6876. this.emit('packet', this.packet)
  6877. }
  6878. this.packet = new Packet()
  6879. this._pos = 0
  6880. return true
  6881. }
  6882. Parser.prototype._emitError = function (err) {
  6883. this.error = err
  6884. this.emit('error', err)
  6885. }
  6886. module.exports = Parser
  6887. },{"./constants":82,"./packet":87,"bl":85,"events":13,"inherits":80}],89:[function(require,module,exports){
  6888. 'use strict'
  6889. var protocol = require('./constants')
  6890. var Buffer = require('safe-buffer').Buffer
  6891. var empty = Buffer.allocUnsafe(0)
  6892. var zeroBuf = Buffer.from([0])
  6893. var numbers = require('./numbers')
  6894. var nextTick = require('process-nextick-args').nextTick
  6895. var numCache = numbers.cache
  6896. var generateNumber = numbers.generateNumber
  6897. var generateCache = numbers.generateCache
  6898. var genBufVariableByteInt = numbers.genBufVariableByteInt
  6899. var generate4ByteBuffer = numbers.generate4ByteBuffer
  6900. var writeNumber = writeNumberCached
  6901. var toGenerate = true
  6902. function generate (packet, stream, opts) {
  6903. if (stream.cork) {
  6904. stream.cork()
  6905. nextTick(uncork, stream)
  6906. }
  6907. if (toGenerate) {
  6908. toGenerate = false
  6909. generateCache()
  6910. }
  6911. switch (packet.cmd) {
  6912. case 'connect':
  6913. return connect(packet, stream, opts)
  6914. case 'connack':
  6915. return connack(packet, stream, opts)
  6916. case 'publish':
  6917. return publish(packet, stream, opts)
  6918. case 'puback':
  6919. case 'pubrec':
  6920. case 'pubrel':
  6921. case 'pubcomp':
  6922. return confirmation(packet, stream, opts)
  6923. case 'subscribe':
  6924. return subscribe(packet, stream, opts)
  6925. case 'suback':
  6926. return suback(packet, stream, opts)
  6927. case 'unsubscribe':
  6928. return unsubscribe(packet, stream, opts)
  6929. case 'unsuback':
  6930. return unsuback(packet, stream, opts)
  6931. case 'pingreq':
  6932. case 'pingresp':
  6933. return emptyPacket(packet, stream, opts)
  6934. case 'disconnect':
  6935. return disconnect(packet, stream, opts)
  6936. case 'auth':
  6937. return auth(packet, stream, opts)
  6938. default:
  6939. stream.emit('error', new Error('Unknown command'))
  6940. return false
  6941. }
  6942. }
  6943. /**
  6944. * Controls numbers cache.
  6945. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  6946. */
  6947. Object.defineProperty(generate, 'cacheNumbers', {
  6948. get: function () {
  6949. return writeNumber === writeNumberCached
  6950. },
  6951. set: function (value) {
  6952. if (value) {
  6953. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  6954. writeNumber = writeNumberCached
  6955. } else {
  6956. toGenerate = false
  6957. writeNumber = writeNumberGenerated
  6958. }
  6959. }
  6960. })
  6961. function uncork (stream) {
  6962. stream.uncork()
  6963. }
  6964. function connect (packet, stream, opts) {
  6965. var settings = packet || {}
  6966. var protocolId = settings.protocolId || 'MQTT'
  6967. var protocolVersion = settings.protocolVersion || 4
  6968. var will = settings.will
  6969. var clean = settings.clean
  6970. var keepalive = settings.keepalive || 0
  6971. var clientId = settings.clientId || ''
  6972. var username = settings.username
  6973. var password = settings.password
  6974. /* mqtt5 new oprions */
  6975. var properties = settings.properties
  6976. if (clean === undefined) clean = true
  6977. var length = 0
  6978. // Must be a string and non-falsy
  6979. if (!protocolId ||
  6980. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  6981. stream.emit('error', new Error('Invalid protocolId'))
  6982. return false
  6983. } else length += protocolId.length + 2
  6984. // Must be 3 or 4 or 5
  6985. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  6986. stream.emit('error', new Error('Invalid protocol version'))
  6987. return false
  6988. } else length += 1
  6989. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  6990. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  6991. (clientId || protocolVersion === 4) && (clientId || clean)) {
  6992. length += clientId.length + 2
  6993. } else {
  6994. if (protocolVersion < 4) {
  6995. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  6996. return false
  6997. }
  6998. if ((clean * 1) === 0) {
  6999. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  7000. return false
  7001. }
  7002. }
  7003. // Must be a two byte number
  7004. if (typeof keepalive !== 'number' ||
  7005. keepalive < 0 ||
  7006. keepalive > 65535 ||
  7007. keepalive % 1 !== 0) {
  7008. stream.emit('error', new Error('Invalid keepalive'))
  7009. return false
  7010. } else length += 2
  7011. // Connect flags
  7012. length += 1
  7013. // Properties
  7014. if (protocolVersion === 5) {
  7015. var propertiesData = getProperties(stream, properties)
  7016. length += propertiesData.length
  7017. }
  7018. // If will exists...
  7019. if (will) {
  7020. // It must be an object
  7021. if (typeof will !== 'object') {
  7022. stream.emit('error', new Error('Invalid will'))
  7023. return false
  7024. }
  7025. // It must have topic typeof string
  7026. if (!will.topic || typeof will.topic !== 'string') {
  7027. stream.emit('error', new Error('Invalid will topic'))
  7028. return false
  7029. } else {
  7030. length += Buffer.byteLength(will.topic) + 2
  7031. }
  7032. // Payload
  7033. if (will.payload) {
  7034. if (will.payload.length >= 0) {
  7035. if (typeof will.payload === 'string') {
  7036. length += Buffer.byteLength(will.payload) + 2
  7037. } else {
  7038. length += will.payload.length + 2
  7039. }
  7040. } else {
  7041. stream.emit('error', new Error('Invalid will payload'))
  7042. return false
  7043. }
  7044. // will properties
  7045. var willProperties = {}
  7046. if (protocolVersion === 5) {
  7047. willProperties = getProperties(stream, will.properties)
  7048. length += willProperties.length
  7049. }
  7050. }
  7051. }
  7052. // Username
  7053. var providedUsername = false
  7054. if (username != null) {
  7055. if (isStringOrBuffer(username)) {
  7056. providedUsername = true
  7057. length += Buffer.byteLength(username) + 2
  7058. } else {
  7059. stream.emit('error', new Error('Invalid username'))
  7060. return false
  7061. }
  7062. }
  7063. // Password
  7064. if (password != null) {
  7065. if (!providedUsername) {
  7066. stream.emit('error', new Error('Username is required to use password'))
  7067. return false
  7068. }
  7069. if (isStringOrBuffer(password)) {
  7070. length += byteLength(password) + 2
  7071. } else {
  7072. stream.emit('error', new Error('Invalid password'))
  7073. return false
  7074. }
  7075. }
  7076. // Generate header
  7077. stream.write(protocol.CONNECT_HEADER)
  7078. // Generate length
  7079. writeVarByteInt(stream, length)
  7080. // Generate protocol ID
  7081. writeStringOrBuffer(stream, protocolId)
  7082. stream.write(
  7083. protocolVersion === 4
  7084. ? protocol.VERSION4
  7085. : protocolVersion === 5
  7086. ? protocol.VERSION5
  7087. : protocol.VERSION3
  7088. )
  7089. // Connect flags
  7090. var flags = 0
  7091. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  7092. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  7093. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  7094. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  7095. flags |= will ? protocol.WILL_FLAG_MASK : 0
  7096. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  7097. stream.write(Buffer.from([flags]))
  7098. // Keepalive
  7099. writeNumber(stream, keepalive)
  7100. // Properties
  7101. if (protocolVersion === 5) {
  7102. propertiesData.write()
  7103. }
  7104. // Client ID
  7105. writeStringOrBuffer(stream, clientId)
  7106. // Will
  7107. if (will) {
  7108. if (protocolVersion === 5) {
  7109. willProperties.write()
  7110. }
  7111. writeString(stream, will.topic)
  7112. writeStringOrBuffer(stream, will.payload)
  7113. }
  7114. // Username and password
  7115. if (username != null) {
  7116. writeStringOrBuffer(stream, username)
  7117. }
  7118. if (password != null) {
  7119. writeStringOrBuffer(stream, password)
  7120. }
  7121. // This is a small packet that happens only once on a stream
  7122. // We assume the stream is always free to receive more data after this
  7123. return true
  7124. }
  7125. function connack (packet, stream, opts) {
  7126. var version = opts ? opts.protocolVersion : 4
  7127. var settings = packet || {}
  7128. var rc = version === 5 ? settings.reasonCode : settings.returnCode
  7129. var properties = settings.properties
  7130. var length = 2 // length of rc and sessionHeader
  7131. // Check return code
  7132. if (typeof rc !== 'number') {
  7133. stream.emit('error', new Error('Invalid return code'))
  7134. return false
  7135. }
  7136. // mqtt5 properties
  7137. var propertiesData = null
  7138. if (version === 5) {
  7139. propertiesData = getProperties(stream, properties)
  7140. length += propertiesData.length
  7141. }
  7142. stream.write(protocol.CONNACK_HEADER)
  7143. // length
  7144. writeVarByteInt(stream, length)
  7145. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  7146. stream.write(Buffer.from([rc]))
  7147. if (propertiesData != null) {
  7148. propertiesData.write()
  7149. }
  7150. return true
  7151. }
  7152. function publish (packet, stream, opts) {
  7153. var version = opts ? opts.protocolVersion : 4
  7154. var settings = packet || {}
  7155. var qos = settings.qos || 0
  7156. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  7157. var topic = settings.topic
  7158. var payload = settings.payload || empty
  7159. var id = settings.messageId
  7160. var properties = settings.properties
  7161. var length = 0
  7162. // Topic must be a non-empty string or Buffer
  7163. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  7164. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  7165. else {
  7166. stream.emit('error', new Error('Invalid topic'))
  7167. return false
  7168. }
  7169. // Get the payload length
  7170. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  7171. else length += payload.length
  7172. // Message ID must a number if qos > 0
  7173. if (qos && typeof id !== 'number') {
  7174. stream.emit('error', new Error('Invalid messageId'))
  7175. return false
  7176. } else if (qos) length += 2
  7177. // mqtt5 properties
  7178. var propertiesData = null
  7179. if (version === 5) {
  7180. propertiesData = getProperties(stream, properties)
  7181. length += propertiesData.length
  7182. }
  7183. // Header
  7184. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  7185. // Remaining length
  7186. writeVarByteInt(stream, length)
  7187. // Topic
  7188. writeNumber(stream, byteLength(topic))
  7189. stream.write(topic)
  7190. // Message ID
  7191. if (qos > 0) writeNumber(stream, id)
  7192. // Properties
  7193. if (propertiesData != null) {
  7194. propertiesData.write()
  7195. }
  7196. // Payload
  7197. return stream.write(payload)
  7198. }
  7199. /* Puback, pubrec, pubrel and pubcomp */
  7200. function confirmation (packet, stream, opts) {
  7201. var version = opts ? opts.protocolVersion : 4
  7202. var settings = packet || {}
  7203. var type = settings.cmd || 'puback'
  7204. var id = settings.messageId
  7205. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  7206. var qos = 0
  7207. var reasonCode = settings.reasonCode
  7208. var properties = settings.properties
  7209. var length = version === 5 ? 3 : 2
  7210. if (type === 'pubrel') qos = 1
  7211. // Check message ID
  7212. if (typeof id !== 'number') {
  7213. stream.emit('error', new Error('Invalid messageId'))
  7214. return false
  7215. }
  7216. // properies mqtt 5
  7217. var propertiesData = null
  7218. if (version === 5) {
  7219. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7220. if (!propertiesData) { return false }
  7221. length += propertiesData.length
  7222. }
  7223. // Header
  7224. stream.write(protocol.ACKS[type][qos][dup][0])
  7225. // Length
  7226. writeVarByteInt(stream, length)
  7227. // Message ID
  7228. writeNumber(stream, id)
  7229. // reason code in header
  7230. if (version === 5) {
  7231. stream.write(Buffer.from([reasonCode]))
  7232. }
  7233. // properies mqtt 5
  7234. if (propertiesData !== null) {
  7235. propertiesData.write()
  7236. }
  7237. return true
  7238. }
  7239. function subscribe (packet, stream, opts) {
  7240. var version = opts ? opts.protocolVersion : 4
  7241. var settings = packet || {}
  7242. var dup = settings.dup ? protocol.DUP_MASK : 0
  7243. var id = settings.messageId
  7244. var subs = settings.subscriptions
  7245. var properties = settings.properties
  7246. var length = 0
  7247. // Check message ID
  7248. if (typeof id !== 'number') {
  7249. stream.emit('error', new Error('Invalid messageId'))
  7250. return false
  7251. } else length += 2
  7252. // properies mqtt 5
  7253. var propertiesData = null
  7254. if (version === 5) {
  7255. propertiesData = getProperties(stream, properties)
  7256. length += propertiesData.length
  7257. }
  7258. // Check subscriptions
  7259. if (typeof subs === 'object' && subs.length) {
  7260. for (var i = 0; i < subs.length; i += 1) {
  7261. var itopic = subs[i].topic
  7262. var iqos = subs[i].qos
  7263. if (typeof itopic !== 'string') {
  7264. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  7265. return false
  7266. }
  7267. if (typeof iqos !== 'number') {
  7268. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  7269. return false
  7270. }
  7271. if (version === 5) {
  7272. var nl = subs[i].nl || false
  7273. if (typeof nl !== 'boolean') {
  7274. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  7275. return false
  7276. }
  7277. var rap = subs[i].rap || false
  7278. if (typeof rap !== 'boolean') {
  7279. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  7280. return false
  7281. }
  7282. var rh = subs[i].rh || 0
  7283. if (typeof rh !== 'number' || rh > 2) {
  7284. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  7285. return false
  7286. }
  7287. }
  7288. length += Buffer.byteLength(itopic) + 2 + 1
  7289. }
  7290. } else {
  7291. stream.emit('error', new Error('Invalid subscriptions'))
  7292. return false
  7293. }
  7294. // Generate header
  7295. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  7296. // Generate length
  7297. writeVarByteInt(stream, length)
  7298. // Generate message ID
  7299. writeNumber(stream, id)
  7300. // properies mqtt 5
  7301. if (propertiesData !== null) {
  7302. propertiesData.write()
  7303. }
  7304. var result = true
  7305. // Generate subs
  7306. for (var j = 0; j < subs.length; j++) {
  7307. var sub = subs[j]
  7308. var jtopic = sub.topic
  7309. var jqos = sub.qos
  7310. var jnl = +sub.nl
  7311. var jrap = +sub.rap
  7312. var jrh = sub.rh
  7313. var joptions
  7314. // Write topic string
  7315. writeString(stream, jtopic)
  7316. // options process
  7317. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  7318. if (version === 5) {
  7319. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  7320. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  7321. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  7322. }
  7323. // Write options
  7324. result = stream.write(Buffer.from([joptions]))
  7325. }
  7326. return result
  7327. }
  7328. function suback (packet, stream, opts) {
  7329. var version = opts ? opts.protocolVersion : 4
  7330. var settings = packet || {}
  7331. var id = settings.messageId
  7332. var granted = settings.granted
  7333. var properties = settings.properties
  7334. var length = 0
  7335. // Check message ID
  7336. if (typeof id !== 'number') {
  7337. stream.emit('error', new Error('Invalid messageId'))
  7338. return false
  7339. } else length += 2
  7340. // Check granted qos vector
  7341. if (typeof granted === 'object' && granted.length) {
  7342. for (var i = 0; i < granted.length; i += 1) {
  7343. if (typeof granted[i] !== 'number') {
  7344. stream.emit('error', new Error('Invalid qos vector'))
  7345. return false
  7346. }
  7347. length += 1
  7348. }
  7349. } else {
  7350. stream.emit('error', new Error('Invalid qos vector'))
  7351. return false
  7352. }
  7353. // properies mqtt 5
  7354. var propertiesData = null
  7355. if (version === 5) {
  7356. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7357. if (!propertiesData) { return false }
  7358. length += propertiesData.length
  7359. }
  7360. // header
  7361. stream.write(protocol.SUBACK_HEADER)
  7362. // Length
  7363. writeVarByteInt(stream, length)
  7364. // Message ID
  7365. writeNumber(stream, id)
  7366. // properies mqtt 5
  7367. if (propertiesData !== null) {
  7368. propertiesData.write()
  7369. }
  7370. return stream.write(Buffer.from(granted))
  7371. }
  7372. function unsubscribe (packet, stream, opts) {
  7373. var version = opts ? opts.protocolVersion : 4
  7374. var settings = packet || {}
  7375. var id = settings.messageId
  7376. var dup = settings.dup ? protocol.DUP_MASK : 0
  7377. var unsubs = settings.unsubscriptions
  7378. var properties = settings.properties
  7379. var length = 0
  7380. // Check message ID
  7381. if (typeof id !== 'number') {
  7382. stream.emit('error', new Error('Invalid messageId'))
  7383. return false
  7384. } else {
  7385. length += 2
  7386. }
  7387. // Check unsubs
  7388. if (typeof unsubs === 'object' && unsubs.length) {
  7389. for (var i = 0; i < unsubs.length; i += 1) {
  7390. if (typeof unsubs[i] !== 'string') {
  7391. stream.emit('error', new Error('Invalid unsubscriptions'))
  7392. return false
  7393. }
  7394. length += Buffer.byteLength(unsubs[i]) + 2
  7395. }
  7396. } else {
  7397. stream.emit('error', new Error('Invalid unsubscriptions'))
  7398. return false
  7399. }
  7400. // properies mqtt 5
  7401. var propertiesData = null
  7402. if (version === 5) {
  7403. propertiesData = getProperties(stream, properties)
  7404. length += propertiesData.length
  7405. }
  7406. // Header
  7407. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  7408. // Length
  7409. writeVarByteInt(stream, length)
  7410. // Message ID
  7411. writeNumber(stream, id)
  7412. // properies mqtt 5
  7413. if (propertiesData !== null) {
  7414. propertiesData.write()
  7415. }
  7416. // Unsubs
  7417. var result = true
  7418. for (var j = 0; j < unsubs.length; j++) {
  7419. result = writeString(stream, unsubs[j])
  7420. }
  7421. return result
  7422. }
  7423. function unsuback (packet, stream, opts) {
  7424. var version = opts ? opts.protocolVersion : 4
  7425. var settings = packet || {}
  7426. var id = settings.messageId
  7427. var dup = settings.dup ? protocol.DUP_MASK : 0
  7428. var granted = settings.granted
  7429. var properties = settings.properties
  7430. var type = settings.cmd
  7431. var qos = 0
  7432. var length = 2
  7433. // Check message ID
  7434. if (typeof id !== 'number') {
  7435. stream.emit('error', new Error('Invalid messageId'))
  7436. return false
  7437. }
  7438. // Check granted
  7439. if (version === 5) {
  7440. if (typeof granted === 'object' && granted.length) {
  7441. for (var i = 0; i < granted.length; i += 1) {
  7442. if (typeof granted[i] !== 'number') {
  7443. stream.emit('error', new Error('Invalid qos vector'))
  7444. return false
  7445. }
  7446. length += 1
  7447. }
  7448. } else {
  7449. stream.emit('error', new Error('Invalid qos vector'))
  7450. return false
  7451. }
  7452. }
  7453. // properies mqtt 5
  7454. var propertiesData = null
  7455. if (version === 5) {
  7456. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7457. if (!propertiesData) { return false }
  7458. length += propertiesData.length
  7459. }
  7460. // Header
  7461. stream.write(protocol.ACKS[type][qos][dup][0])
  7462. // Length
  7463. writeVarByteInt(stream, length)
  7464. // Message ID
  7465. writeNumber(stream, id)
  7466. // properies mqtt 5
  7467. if (propertiesData !== null) {
  7468. propertiesData.write()
  7469. }
  7470. // payload
  7471. if (version === 5) {
  7472. stream.write(Buffer.from(granted))
  7473. }
  7474. return true
  7475. }
  7476. function emptyPacket (packet, stream, opts) {
  7477. return stream.write(protocol.EMPTY[packet.cmd])
  7478. }
  7479. function disconnect (packet, stream, opts) {
  7480. var version = opts ? opts.protocolVersion : 4
  7481. var settings = packet || {}
  7482. var reasonCode = settings.reasonCode
  7483. var properties = settings.properties
  7484. var length = version === 5 ? 1 : 0
  7485. // properies mqtt 5
  7486. var propertiesData = null
  7487. if (version === 5) {
  7488. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7489. if (!propertiesData) { return false }
  7490. length += propertiesData.length
  7491. }
  7492. // Header
  7493. stream.write(Buffer.from([protocol.codes['disconnect'] << 4]))
  7494. // Length
  7495. writeVarByteInt(stream, length)
  7496. // reason code in header
  7497. if (version === 5) {
  7498. stream.write(Buffer.from([reasonCode]))
  7499. }
  7500. // properies mqtt 5
  7501. if (propertiesData !== null) {
  7502. propertiesData.write()
  7503. }
  7504. return true
  7505. }
  7506. function auth (packet, stream, opts) {
  7507. var version = opts ? opts.protocolVersion : 4
  7508. var settings = packet || {}
  7509. var reasonCode = settings.reasonCode
  7510. var properties = settings.properties
  7511. var length = version === 5 ? 1 : 0
  7512. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  7513. // properies mqtt 5
  7514. var propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  7515. if (!propertiesData) { return false }
  7516. length += propertiesData.length
  7517. // Header
  7518. stream.write(Buffer.from([protocol.codes['auth'] << 4]))
  7519. // Length
  7520. writeVarByteInt(stream, length)
  7521. // reason code in header
  7522. stream.write(Buffer.from([reasonCode]))
  7523. // properies mqtt 5
  7524. if (propertiesData !== null) {
  7525. propertiesData.write()
  7526. }
  7527. return true
  7528. }
  7529. /**
  7530. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  7531. *
  7532. * @param <Buffer> buffer - destination
  7533. * @param <Number> pos - offset
  7534. * @param <Number> length - length (>0)
  7535. * @returns <Number> number of bytes written
  7536. *
  7537. * @api private
  7538. */
  7539. var varByteIntCache = {}
  7540. function writeVarByteInt (stream, num) {
  7541. var buffer = varByteIntCache[num]
  7542. if (!buffer) {
  7543. buffer = genBufVariableByteInt(num).data
  7544. if (num < 16384) varByteIntCache[num] = buffer
  7545. }
  7546. stream.write(buffer)
  7547. }
  7548. /**
  7549. * writeString - write a utf8 string to the buffer
  7550. *
  7551. * @param <Buffer> buffer - destination
  7552. * @param <Number> pos - offset
  7553. * @param <String> string - string to write
  7554. * @return <Number> number of bytes written
  7555. *
  7556. * @api private
  7557. */
  7558. function writeString (stream, string) {
  7559. var strlen = Buffer.byteLength(string)
  7560. writeNumber(stream, strlen)
  7561. stream.write(string, 'utf8')
  7562. }
  7563. /**
  7564. * writeStringPair - write a utf8 string pairs to the buffer
  7565. *
  7566. * @param <Buffer> buffer - destination
  7567. * @param <String> name - string name to write
  7568. * @param <String> value - string value to write
  7569. * @return <Number> number of bytes written
  7570. *
  7571. * @api private
  7572. */
  7573. function writeStringPair (stream, name, value) {
  7574. writeString(stream, name)
  7575. writeString(stream, value)
  7576. }
  7577. /**
  7578. * writeNumber - write a two byte number to the buffer
  7579. *
  7580. * @param <Buffer> buffer - destination
  7581. * @param <Number> pos - offset
  7582. * @param <String> number - number to write
  7583. * @return <Number> number of bytes written
  7584. *
  7585. * @api private
  7586. */
  7587. function writeNumberCached (stream, number) {
  7588. return stream.write(numCache[number])
  7589. }
  7590. function writeNumberGenerated (stream, number) {
  7591. return stream.write(generateNumber(number))
  7592. }
  7593. function write4ByteNumber (stream, number) {
  7594. return stream.write(generate4ByteBuffer(number))
  7595. }
  7596. /**
  7597. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  7598. *
  7599. * @param <Buffer> buffer - destination
  7600. * @param <Number> pos - offset
  7601. * @param <String> toWrite - String or Buffer
  7602. * @return <Number> number of bytes written
  7603. */
  7604. function writeStringOrBuffer (stream, toWrite) {
  7605. if (typeof toWrite === 'string') {
  7606. writeString(stream, toWrite)
  7607. } else if (toWrite) {
  7608. writeNumber(stream, toWrite.length)
  7609. stream.write(toWrite)
  7610. } else writeNumber(stream, 0)
  7611. }
  7612. function getProperties (stream, properties) {
  7613. /* connect properties */
  7614. if (typeof properties !== 'object' || properties.length != null) {
  7615. return {
  7616. length: 1,
  7617. write: function () {
  7618. writeProperties(stream, {}, 0)
  7619. }
  7620. }
  7621. }
  7622. var propertiesLength = 0
  7623. function getLengthProperty (name) {
  7624. var type = protocol.propertiesTypes[name]
  7625. var value = properties[name]
  7626. var length = 0
  7627. switch (type) {
  7628. case 'byte': {
  7629. if (typeof value !== 'boolean') {
  7630. stream.emit('error', new Error('Invalid ' + name))
  7631. return false
  7632. }
  7633. length += 1 + 1
  7634. break
  7635. }
  7636. case 'int8': {
  7637. if (typeof value !== 'number') {
  7638. stream.emit('error', new Error('Invalid ' + name))
  7639. return false
  7640. }
  7641. length += 1 + 1
  7642. break
  7643. }
  7644. case 'binary': {
  7645. if (value && value === null) {
  7646. stream.emit('error', new Error('Invalid ' + name))
  7647. return false
  7648. }
  7649. length += 1 + Buffer.byteLength(value) + 2
  7650. break
  7651. }
  7652. case 'int16': {
  7653. if (typeof value !== 'number') {
  7654. stream.emit('error', new Error('Invalid ' + name))
  7655. return false
  7656. }
  7657. length += 1 + 2
  7658. break
  7659. }
  7660. case 'int32': {
  7661. if (typeof value !== 'number') {
  7662. stream.emit('error', new Error('Invalid ' + name))
  7663. return false
  7664. }
  7665. length += 1 + 4
  7666. break
  7667. }
  7668. case 'var': {
  7669. if (typeof value !== 'number') {
  7670. stream.emit('error', new Error('Invalid ' + name))
  7671. return false
  7672. }
  7673. length += 1 + genBufVariableByteInt(value).length
  7674. break
  7675. }
  7676. case 'string': {
  7677. if (typeof value !== 'string') {
  7678. stream.emit('error', new Error('Invalid ' + name))
  7679. return false
  7680. }
  7681. length += 1 + 2 + Buffer.byteLength(value.toString())
  7682. break
  7683. }
  7684. case 'pair': {
  7685. if (typeof value !== 'object') {
  7686. stream.emit('error', new Error('Invalid ' + name))
  7687. return false
  7688. }
  7689. length += Object.getOwnPropertyNames(value).reduce(function (result, name) {
  7690. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  7691. return result
  7692. }, 0)
  7693. break
  7694. }
  7695. default: {
  7696. stream.emit('error', new Error('Invalid property ' + name))
  7697. return false
  7698. }
  7699. }
  7700. return length
  7701. }
  7702. if (properties) {
  7703. for (var propName in properties) {
  7704. var propLength = getLengthProperty(propName)
  7705. if (!propLength) return false
  7706. propertiesLength += propLength
  7707. }
  7708. }
  7709. var propertiesLengthLength = genBufVariableByteInt(propertiesLength).length
  7710. return {
  7711. length: propertiesLengthLength + propertiesLength,
  7712. write: function () {
  7713. writeProperties(stream, properties, propertiesLength)
  7714. }
  7715. }
  7716. }
  7717. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  7718. var mayEmptyProps = ['reasonString', 'userProperties']
  7719. var maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  7720. var propertiesData = getProperties(stream, properties)
  7721. if (maximumPacketSize) {
  7722. while (length + propertiesData.length > maximumPacketSize) {
  7723. var currentMayEmptyProp = mayEmptyProps.shift()
  7724. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  7725. delete properties[currentMayEmptyProp]
  7726. propertiesData = getProperties(stream, properties)
  7727. } else {
  7728. return false
  7729. }
  7730. }
  7731. }
  7732. return propertiesData
  7733. }
  7734. function writeProperties (stream, properties, propertiesLength) {
  7735. /* write properties to stream */
  7736. writeVarByteInt(stream, propertiesLength)
  7737. for (var propName in properties) {
  7738. if (properties.hasOwnProperty(propName) && properties[propName] !== null) {
  7739. var value = properties[propName]
  7740. var type = protocol.propertiesTypes[propName]
  7741. switch (type) {
  7742. case 'byte': {
  7743. stream.write(Buffer.from([protocol.properties[propName]]))
  7744. stream.write(Buffer.from([+value]))
  7745. break
  7746. }
  7747. case 'int8': {
  7748. stream.write(Buffer.from([protocol.properties[propName]]))
  7749. stream.write(Buffer.from([value]))
  7750. break
  7751. }
  7752. case 'binary': {
  7753. stream.write(Buffer.from([protocol.properties[propName]]))
  7754. writeStringOrBuffer(stream, value)
  7755. break
  7756. }
  7757. case 'int16': {
  7758. stream.write(Buffer.from([protocol.properties[propName]]))
  7759. writeNumber(stream, value)
  7760. break
  7761. }
  7762. case 'int32': {
  7763. stream.write(Buffer.from([protocol.properties[propName]]))
  7764. write4ByteNumber(stream, value)
  7765. break
  7766. }
  7767. case 'var': {
  7768. stream.write(Buffer.from([protocol.properties[propName]]))
  7769. writeVarByteInt(stream, value)
  7770. break
  7771. }
  7772. case 'string': {
  7773. stream.write(Buffer.from([protocol.properties[propName]]))
  7774. writeString(stream, value)
  7775. break
  7776. }
  7777. case 'pair': {
  7778. Object.getOwnPropertyNames(value).forEach(function (name) {
  7779. stream.write(Buffer.from([protocol.properties[propName]]))
  7780. writeStringPair(stream, name.toString(), value[name].toString())
  7781. })
  7782. break
  7783. }
  7784. default: {
  7785. stream.emit('error', new Error('Invalid property ' + propName))
  7786. return false
  7787. }
  7788. }
  7789. }
  7790. }
  7791. }
  7792. function byteLength (bufOrString) {
  7793. if (!bufOrString) return 0
  7794. else if (bufOrString instanceof Buffer) return bufOrString.length
  7795. else return Buffer.byteLength(bufOrString)
  7796. }
  7797. function isStringOrBuffer (field) {
  7798. return typeof field === 'string' || field instanceof Buffer
  7799. }
  7800. module.exports = generate
  7801. },{"./constants":82,"./numbers":86,"process-nextick-args":91,"safe-buffer":110}],90:[function(require,module,exports){
  7802. var wrappy = require('wrappy')
  7803. module.exports = wrappy(once)
  7804. module.exports.strict = wrappy(onceStrict)
  7805. once.proto = once(function () {
  7806. Object.defineProperty(Function.prototype, 'once', {
  7807. value: function () {
  7808. return once(this)
  7809. },
  7810. configurable: true
  7811. })
  7812. Object.defineProperty(Function.prototype, 'onceStrict', {
  7813. value: function () {
  7814. return onceStrict(this)
  7815. },
  7816. configurable: true
  7817. })
  7818. })
  7819. function once (fn) {
  7820. var f = function () {
  7821. if (f.called) return f.value
  7822. f.called = true
  7823. return f.value = fn.apply(this, arguments)
  7824. }
  7825. f.called = false
  7826. return f
  7827. }
  7828. function onceStrict (fn) {
  7829. var f = function () {
  7830. if (f.called)
  7831. throw new Error(f.onceError)
  7832. f.called = true
  7833. return f.value = fn.apply(this, arguments)
  7834. }
  7835. var name = fn.name || 'Function wrapped with `once`'
  7836. f.onceError = name + " shouldn't be called more than once"
  7837. f.called = false
  7838. return f
  7839. }
  7840. },{"wrappy":120}],91:[function(require,module,exports){
  7841. (function (process){
  7842. 'use strict';
  7843. if (!process.version ||
  7844. process.version.indexOf('v0.') === 0 ||
  7845. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  7846. module.exports = { nextTick: nextTick };
  7847. } else {
  7848. module.exports = process
  7849. }
  7850. function nextTick(fn, arg1, arg2, arg3) {
  7851. if (typeof fn !== 'function') {
  7852. throw new TypeError('"callback" argument must be a function');
  7853. }
  7854. var len = arguments.length;
  7855. var args, i;
  7856. switch (len) {
  7857. case 0:
  7858. case 1:
  7859. return process.nextTick(fn);
  7860. case 2:
  7861. return process.nextTick(function afterTickOne() {
  7862. fn.call(null, arg1);
  7863. });
  7864. case 3:
  7865. return process.nextTick(function afterTickTwo() {
  7866. fn.call(null, arg1, arg2);
  7867. });
  7868. case 4:
  7869. return process.nextTick(function afterTickThree() {
  7870. fn.call(null, arg1, arg2, arg3);
  7871. });
  7872. default:
  7873. args = new Array(len - 1);
  7874. i = 0;
  7875. while (i < args.length) {
  7876. args[i++] = arguments[i];
  7877. }
  7878. return process.nextTick(function afterTick() {
  7879. fn.apply(null, args);
  7880. });
  7881. }
  7882. }
  7883. }).call(this,require('_process'))
  7884. },{"_process":92}],92:[function(require,module,exports){
  7885. // shim for using process in browser
  7886. var process = module.exports = {};
  7887. // cached from whatever global is present so that test runners that stub it
  7888. // don't break things. But we need to wrap it in a try catch in case it is
  7889. // wrapped in strict mode code which doesn't define any globals. It's inside a
  7890. // function because try/catches deoptimize in certain engines.
  7891. var cachedSetTimeout;
  7892. var cachedClearTimeout;
  7893. function defaultSetTimout() {
  7894. throw new Error('setTimeout has not been defined');
  7895. }
  7896. function defaultClearTimeout () {
  7897. throw new Error('clearTimeout has not been defined');
  7898. }
  7899. (function () {
  7900. try {
  7901. if (typeof setTimeout === 'function') {
  7902. cachedSetTimeout = setTimeout;
  7903. } else {
  7904. cachedSetTimeout = defaultSetTimout;
  7905. }
  7906. } catch (e) {
  7907. cachedSetTimeout = defaultSetTimout;
  7908. }
  7909. try {
  7910. if (typeof clearTimeout === 'function') {
  7911. cachedClearTimeout = clearTimeout;
  7912. } else {
  7913. cachedClearTimeout = defaultClearTimeout;
  7914. }
  7915. } catch (e) {
  7916. cachedClearTimeout = defaultClearTimeout;
  7917. }
  7918. } ())
  7919. function runTimeout(fun) {
  7920. if (cachedSetTimeout === setTimeout) {
  7921. //normal enviroments in sane situations
  7922. return setTimeout(fun, 0);
  7923. }
  7924. // if setTimeout wasn't available but was latter defined
  7925. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  7926. cachedSetTimeout = setTimeout;
  7927. return setTimeout(fun, 0);
  7928. }
  7929. try {
  7930. // when when somebody has screwed with setTimeout but no I.E. maddness
  7931. return cachedSetTimeout(fun, 0);
  7932. } catch(e){
  7933. try {
  7934. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7935. return cachedSetTimeout.call(null, fun, 0);
  7936. } catch(e){
  7937. // 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
  7938. return cachedSetTimeout.call(this, fun, 0);
  7939. }
  7940. }
  7941. }
  7942. function runClearTimeout(marker) {
  7943. if (cachedClearTimeout === clearTimeout) {
  7944. //normal enviroments in sane situations
  7945. return clearTimeout(marker);
  7946. }
  7947. // if clearTimeout wasn't available but was latter defined
  7948. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  7949. cachedClearTimeout = clearTimeout;
  7950. return clearTimeout(marker);
  7951. }
  7952. try {
  7953. // when when somebody has screwed with setTimeout but no I.E. maddness
  7954. return cachedClearTimeout(marker);
  7955. } catch (e){
  7956. try {
  7957. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7958. return cachedClearTimeout.call(null, marker);
  7959. } catch (e){
  7960. // 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.
  7961. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  7962. return cachedClearTimeout.call(this, marker);
  7963. }
  7964. }
  7965. }
  7966. var queue = [];
  7967. var draining = false;
  7968. var currentQueue;
  7969. var queueIndex = -1;
  7970. function cleanUpNextTick() {
  7971. if (!draining || !currentQueue) {
  7972. return;
  7973. }
  7974. draining = false;
  7975. if (currentQueue.length) {
  7976. queue = currentQueue.concat(queue);
  7977. } else {
  7978. queueIndex = -1;
  7979. }
  7980. if (queue.length) {
  7981. drainQueue();
  7982. }
  7983. }
  7984. function drainQueue() {
  7985. if (draining) {
  7986. return;
  7987. }
  7988. var timeout = runTimeout(cleanUpNextTick);
  7989. draining = true;
  7990. var len = queue.length;
  7991. while(len) {
  7992. currentQueue = queue;
  7993. queue = [];
  7994. while (++queueIndex < len) {
  7995. if (currentQueue) {
  7996. currentQueue[queueIndex].run();
  7997. }
  7998. }
  7999. queueIndex = -1;
  8000. len = queue.length;
  8001. }
  8002. currentQueue = null;
  8003. draining = false;
  8004. runClearTimeout(timeout);
  8005. }
  8006. process.nextTick = function (fun) {
  8007. var args = new Array(arguments.length - 1);
  8008. if (arguments.length > 1) {
  8009. for (var i = 1; i < arguments.length; i++) {
  8010. args[i - 1] = arguments[i];
  8011. }
  8012. }
  8013. queue.push(new Item(fun, args));
  8014. if (queue.length === 1 && !draining) {
  8015. runTimeout(drainQueue);
  8016. }
  8017. };
  8018. // v8 likes predictible objects
  8019. function Item(fun, array) {
  8020. this.fun = fun;
  8021. this.array = array;
  8022. }
  8023. Item.prototype.run = function () {
  8024. this.fun.apply(null, this.array);
  8025. };
  8026. process.title = 'browser';
  8027. process.browser = true;
  8028. process.env = {};
  8029. process.argv = [];
  8030. process.version = ''; // empty string to avoid regexp issues
  8031. process.versions = {};
  8032. function noop() {}
  8033. process.on = noop;
  8034. process.addListener = noop;
  8035. process.once = noop;
  8036. process.off = noop;
  8037. process.removeListener = noop;
  8038. process.removeAllListeners = noop;
  8039. process.emit = noop;
  8040. process.prependListener = noop;
  8041. process.prependOnceListener = noop;
  8042. process.listeners = function (name) { return [] }
  8043. process.binding = function (name) {
  8044. throw new Error('process.binding is not supported');
  8045. };
  8046. process.cwd = function () { return '/' };
  8047. process.chdir = function (dir) {
  8048. throw new Error('process.chdir is not supported');
  8049. };
  8050. process.umask = function() { return 0; };
  8051. },{}],93:[function(require,module,exports){
  8052. (function (global){
  8053. /*! https://mths.be/punycode v1.4.1 by @mathias */
  8054. ;(function(root) {
  8055. /** Detect free variables */
  8056. var freeExports = typeof exports == 'object' && exports &&
  8057. !exports.nodeType && exports;
  8058. var freeModule = typeof module == 'object' && module &&
  8059. !module.nodeType && module;
  8060. var freeGlobal = typeof global == 'object' && global;
  8061. if (
  8062. freeGlobal.global === freeGlobal ||
  8063. freeGlobal.window === freeGlobal ||
  8064. freeGlobal.self === freeGlobal
  8065. ) {
  8066. root = freeGlobal;
  8067. }
  8068. /**
  8069. * The `punycode` object.
  8070. * @name punycode
  8071. * @type Object
  8072. */
  8073. var punycode,
  8074. /** Highest positive signed 32-bit float value */
  8075. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  8076. /** Bootstring parameters */
  8077. base = 36,
  8078. tMin = 1,
  8079. tMax = 26,
  8080. skew = 38,
  8081. damp = 700,
  8082. initialBias = 72,
  8083. initialN = 128, // 0x80
  8084. delimiter = '-', // '\x2D'
  8085. /** Regular expressions */
  8086. regexPunycode = /^xn--/,
  8087. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  8088. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  8089. /** Error messages */
  8090. errors = {
  8091. 'overflow': 'Overflow: input needs wider integers to process',
  8092. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  8093. 'invalid-input': 'Invalid input'
  8094. },
  8095. /** Convenience shortcuts */
  8096. baseMinusTMin = base - tMin,
  8097. floor = Math.floor,
  8098. stringFromCharCode = String.fromCharCode,
  8099. /** Temporary variable */
  8100. key;
  8101. /*--------------------------------------------------------------------------*/
  8102. /**
  8103. * A generic error utility function.
  8104. * @private
  8105. * @param {String} type The error type.
  8106. * @returns {Error} Throws a `RangeError` with the applicable error message.
  8107. */
  8108. function error(type) {
  8109. throw new RangeError(errors[type]);
  8110. }
  8111. /**
  8112. * A generic `Array#map` utility function.
  8113. * @private
  8114. * @param {Array} array The array to iterate over.
  8115. * @param {Function} callback The function that gets called for every array
  8116. * item.
  8117. * @returns {Array} A new array of values returned by the callback function.
  8118. */
  8119. function map(array, fn) {
  8120. var length = array.length;
  8121. var result = [];
  8122. while (length--) {
  8123. result[length] = fn(array[length]);
  8124. }
  8125. return result;
  8126. }
  8127. /**
  8128. * A simple `Array#map`-like wrapper to work with domain name strings or email
  8129. * addresses.
  8130. * @private
  8131. * @param {String} domain The domain name or email address.
  8132. * @param {Function} callback The function that gets called for every
  8133. * character.
  8134. * @returns {Array} A new string of characters returned by the callback
  8135. * function.
  8136. */
  8137. function mapDomain(string, fn) {
  8138. var parts = string.split('@');
  8139. var result = '';
  8140. if (parts.length > 1) {
  8141. // In email addresses, only the domain name should be punycoded. Leave
  8142. // the local part (i.e. everything up to `@`) intact.
  8143. result = parts[0] + '@';
  8144. string = parts[1];
  8145. }
  8146. // Avoid `split(regex)` for IE8 compatibility. See #17.
  8147. string = string.replace(regexSeparators, '\x2E');
  8148. var labels = string.split('.');
  8149. var encoded = map(labels, fn).join('.');
  8150. return result + encoded;
  8151. }
  8152. /**
  8153. * Creates an array containing the numeric code points of each Unicode
  8154. * character in the string. While JavaScript uses UCS-2 internally,
  8155. * this function will convert a pair of surrogate halves (each of which
  8156. * UCS-2 exposes as separate characters) into a single code point,
  8157. * matching UTF-16.
  8158. * @see `punycode.ucs2.encode`
  8159. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8160. * @memberOf punycode.ucs2
  8161. * @name decode
  8162. * @param {String} string The Unicode input string (UCS-2).
  8163. * @returns {Array} The new array of code points.
  8164. */
  8165. function ucs2decode(string) {
  8166. var output = [],
  8167. counter = 0,
  8168. length = string.length,
  8169. value,
  8170. extra;
  8171. while (counter < length) {
  8172. value = string.charCodeAt(counter++);
  8173. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  8174. // high surrogate, and there is a next character
  8175. extra = string.charCodeAt(counter++);
  8176. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  8177. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  8178. } else {
  8179. // unmatched surrogate; only append this code unit, in case the next
  8180. // code unit is the high surrogate of a surrogate pair
  8181. output.push(value);
  8182. counter--;
  8183. }
  8184. } else {
  8185. output.push(value);
  8186. }
  8187. }
  8188. return output;
  8189. }
  8190. /**
  8191. * Creates a string based on an array of numeric code points.
  8192. * @see `punycode.ucs2.decode`
  8193. * @memberOf punycode.ucs2
  8194. * @name encode
  8195. * @param {Array} codePoints The array of numeric code points.
  8196. * @returns {String} The new Unicode string (UCS-2).
  8197. */
  8198. function ucs2encode(array) {
  8199. return map(array, function(value) {
  8200. var output = '';
  8201. if (value > 0xFFFF) {
  8202. value -= 0x10000;
  8203. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  8204. value = 0xDC00 | value & 0x3FF;
  8205. }
  8206. output += stringFromCharCode(value);
  8207. return output;
  8208. }).join('');
  8209. }
  8210. /**
  8211. * Converts a basic code point into a digit/integer.
  8212. * @see `digitToBasic()`
  8213. * @private
  8214. * @param {Number} codePoint The basic numeric code point value.
  8215. * @returns {Number} The numeric value of a basic code point (for use in
  8216. * representing integers) in the range `0` to `base - 1`, or `base` if
  8217. * the code point does not represent a value.
  8218. */
  8219. function basicToDigit(codePoint) {
  8220. if (codePoint - 48 < 10) {
  8221. return codePoint - 22;
  8222. }
  8223. if (codePoint - 65 < 26) {
  8224. return codePoint - 65;
  8225. }
  8226. if (codePoint - 97 < 26) {
  8227. return codePoint - 97;
  8228. }
  8229. return base;
  8230. }
  8231. /**
  8232. * Converts a digit/integer into a basic code point.
  8233. * @see `basicToDigit()`
  8234. * @private
  8235. * @param {Number} digit The numeric value of a basic code point.
  8236. * @returns {Number} The basic code point whose value (when used for
  8237. * representing integers) is `digit`, which needs to be in the range
  8238. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  8239. * used; else, the lowercase form is used. The behavior is undefined
  8240. * if `flag` is non-zero and `digit` has no uppercase form.
  8241. */
  8242. function digitToBasic(digit, flag) {
  8243. // 0..25 map to ASCII a..z or A..Z
  8244. // 26..35 map to ASCII 0..9
  8245. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  8246. }
  8247. /**
  8248. * Bias adaptation function as per section 3.4 of RFC 3492.
  8249. * https://tools.ietf.org/html/rfc3492#section-3.4
  8250. * @private
  8251. */
  8252. function adapt(delta, numPoints, firstTime) {
  8253. var k = 0;
  8254. delta = firstTime ? floor(delta / damp) : delta >> 1;
  8255. delta += floor(delta / numPoints);
  8256. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  8257. delta = floor(delta / baseMinusTMin);
  8258. }
  8259. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  8260. }
  8261. /**
  8262. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  8263. * symbols.
  8264. * @memberOf punycode
  8265. * @param {String} input The Punycode string of ASCII-only symbols.
  8266. * @returns {String} The resulting string of Unicode symbols.
  8267. */
  8268. function decode(input) {
  8269. // Don't use UCS-2
  8270. var output = [],
  8271. inputLength = input.length,
  8272. out,
  8273. i = 0,
  8274. n = initialN,
  8275. bias = initialBias,
  8276. basic,
  8277. j,
  8278. index,
  8279. oldi,
  8280. w,
  8281. k,
  8282. digit,
  8283. t,
  8284. /** Cached calculation results */
  8285. baseMinusT;
  8286. // Handle the basic code points: let `basic` be the number of input code
  8287. // points before the last delimiter, or `0` if there is none, then copy
  8288. // the first basic code points to the output.
  8289. basic = input.lastIndexOf(delimiter);
  8290. if (basic < 0) {
  8291. basic = 0;
  8292. }
  8293. for (j = 0; j < basic; ++j) {
  8294. // if it's not a basic code point
  8295. if (input.charCodeAt(j) >= 0x80) {
  8296. error('not-basic');
  8297. }
  8298. output.push(input.charCodeAt(j));
  8299. }
  8300. // Main decoding loop: start just after the last delimiter if any basic code
  8301. // points were copied; start at the beginning otherwise.
  8302. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  8303. // `index` is the index of the next character to be consumed.
  8304. // Decode a generalized variable-length integer into `delta`,
  8305. // which gets added to `i`. The overflow checking is easier
  8306. // if we increase `i` as we go, then subtract off its starting
  8307. // value at the end to obtain `delta`.
  8308. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  8309. if (index >= inputLength) {
  8310. error('invalid-input');
  8311. }
  8312. digit = basicToDigit(input.charCodeAt(index++));
  8313. if (digit >= base || digit > floor((maxInt - i) / w)) {
  8314. error('overflow');
  8315. }
  8316. i += digit * w;
  8317. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  8318. if (digit < t) {
  8319. break;
  8320. }
  8321. baseMinusT = base - t;
  8322. if (w > floor(maxInt / baseMinusT)) {
  8323. error('overflow');
  8324. }
  8325. w *= baseMinusT;
  8326. }
  8327. out = output.length + 1;
  8328. bias = adapt(i - oldi, out, oldi == 0);
  8329. // `i` was supposed to wrap around from `out` to `0`,
  8330. // incrementing `n` each time, so we'll fix that now:
  8331. if (floor(i / out) > maxInt - n) {
  8332. error('overflow');
  8333. }
  8334. n += floor(i / out);
  8335. i %= out;
  8336. // Insert `n` at position `i` of the output
  8337. output.splice(i++, 0, n);
  8338. }
  8339. return ucs2encode(output);
  8340. }
  8341. /**
  8342. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  8343. * Punycode string of ASCII-only symbols.
  8344. * @memberOf punycode
  8345. * @param {String} input The string of Unicode symbols.
  8346. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  8347. */
  8348. function encode(input) {
  8349. var n,
  8350. delta,
  8351. handledCPCount,
  8352. basicLength,
  8353. bias,
  8354. j,
  8355. m,
  8356. q,
  8357. k,
  8358. t,
  8359. currentValue,
  8360. output = [],
  8361. /** `inputLength` will hold the number of code points in `input`. */
  8362. inputLength,
  8363. /** Cached calculation results */
  8364. handledCPCountPlusOne,
  8365. baseMinusT,
  8366. qMinusT;
  8367. // Convert the input in UCS-2 to Unicode
  8368. input = ucs2decode(input);
  8369. // Cache the length
  8370. inputLength = input.length;
  8371. // Initialize the state
  8372. n = initialN;
  8373. delta = 0;
  8374. bias = initialBias;
  8375. // Handle the basic code points
  8376. for (j = 0; j < inputLength; ++j) {
  8377. currentValue = input[j];
  8378. if (currentValue < 0x80) {
  8379. output.push(stringFromCharCode(currentValue));
  8380. }
  8381. }
  8382. handledCPCount = basicLength = output.length;
  8383. // `handledCPCount` is the number of code points that have been handled;
  8384. // `basicLength` is the number of basic code points.
  8385. // Finish the basic string - if it is not empty - with a delimiter
  8386. if (basicLength) {
  8387. output.push(delimiter);
  8388. }
  8389. // Main encoding loop:
  8390. while (handledCPCount < inputLength) {
  8391. // All non-basic code points < n have been handled already. Find the next
  8392. // larger one:
  8393. for (m = maxInt, j = 0; j < inputLength; ++j) {
  8394. currentValue = input[j];
  8395. if (currentValue >= n && currentValue < m) {
  8396. m = currentValue;
  8397. }
  8398. }
  8399. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  8400. // but guard against overflow
  8401. handledCPCountPlusOne = handledCPCount + 1;
  8402. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  8403. error('overflow');
  8404. }
  8405. delta += (m - n) * handledCPCountPlusOne;
  8406. n = m;
  8407. for (j = 0; j < inputLength; ++j) {
  8408. currentValue = input[j];
  8409. if (currentValue < n && ++delta > maxInt) {
  8410. error('overflow');
  8411. }
  8412. if (currentValue == n) {
  8413. // Represent delta as a generalized variable-length integer
  8414. for (q = delta, k = base; /* no condition */; k += base) {
  8415. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  8416. if (q < t) {
  8417. break;
  8418. }
  8419. qMinusT = q - t;
  8420. baseMinusT = base - t;
  8421. output.push(
  8422. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  8423. );
  8424. q = floor(qMinusT / baseMinusT);
  8425. }
  8426. output.push(stringFromCharCode(digitToBasic(q, 0)));
  8427. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  8428. delta = 0;
  8429. ++handledCPCount;
  8430. }
  8431. }
  8432. ++delta;
  8433. ++n;
  8434. }
  8435. return output.join('');
  8436. }
  8437. /**
  8438. * Converts a Punycode string representing a domain name or an email address
  8439. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  8440. * it doesn't matter if you call it on a string that has already been
  8441. * converted to Unicode.
  8442. * @memberOf punycode
  8443. * @param {String} input The Punycoded domain name or email address to
  8444. * convert to Unicode.
  8445. * @returns {String} The Unicode representation of the given Punycode
  8446. * string.
  8447. */
  8448. function toUnicode(input) {
  8449. return mapDomain(input, function(string) {
  8450. return regexPunycode.test(string)
  8451. ? decode(string.slice(4).toLowerCase())
  8452. : string;
  8453. });
  8454. }
  8455. /**
  8456. * Converts a Unicode string representing a domain name or an email address to
  8457. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  8458. * i.e. it doesn't matter if you call it with a domain that's already in
  8459. * ASCII.
  8460. * @memberOf punycode
  8461. * @param {String} input The domain name or email address to convert, as a
  8462. * Unicode string.
  8463. * @returns {String} The Punycode representation of the given domain name or
  8464. * email address.
  8465. */
  8466. function toASCII(input) {
  8467. return mapDomain(input, function(string) {
  8468. return regexNonASCII.test(string)
  8469. ? 'xn--' + encode(string)
  8470. : string;
  8471. });
  8472. }
  8473. /*--------------------------------------------------------------------------*/
  8474. /** Define the public API */
  8475. punycode = {
  8476. /**
  8477. * A string representing the current Punycode.js version number.
  8478. * @memberOf punycode
  8479. * @type String
  8480. */
  8481. 'version': '1.4.1',
  8482. /**
  8483. * An object of methods to convert from JavaScript's internal character
  8484. * representation (UCS-2) to Unicode code points, and back.
  8485. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8486. * @memberOf punycode
  8487. * @type Object
  8488. */
  8489. 'ucs2': {
  8490. 'decode': ucs2decode,
  8491. 'encode': ucs2encode
  8492. },
  8493. 'decode': decode,
  8494. 'encode': encode,
  8495. 'toASCII': toASCII,
  8496. 'toUnicode': toUnicode
  8497. };
  8498. /** Expose `punycode` */
  8499. // Some AMD build optimizers, like r.js, check for specific condition patterns
  8500. // like the following:
  8501. if (
  8502. typeof define == 'function' &&
  8503. typeof define.amd == 'object' &&
  8504. define.amd
  8505. ) {
  8506. define('punycode', function() {
  8507. return punycode;
  8508. });
  8509. } else if (freeExports && freeModule) {
  8510. if (module.exports == freeExports) {
  8511. // in Node.js, io.js, or RingoJS v0.8.0+
  8512. freeModule.exports = punycode;
  8513. } else {
  8514. // in Narwhal or RingoJS v0.7.0-
  8515. for (key in punycode) {
  8516. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  8517. }
  8518. }
  8519. } else {
  8520. // in Rhino or a web browser
  8521. root.punycode = punycode;
  8522. }
  8523. }(this));
  8524. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8525. },{}],94:[function(require,module,exports){
  8526. // Copyright Joyent, Inc. and other Node contributors.
  8527. //
  8528. // Permission is hereby granted, free of charge, to any person obtaining a
  8529. // copy of this software and associated documentation files (the
  8530. // "Software"), to deal in the Software without restriction, including
  8531. // without limitation the rights to use, copy, modify, merge, publish,
  8532. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8533. // persons to whom the Software is furnished to do so, subject to the
  8534. // following conditions:
  8535. //
  8536. // The above copyright notice and this permission notice shall be included
  8537. // in all copies or substantial portions of the Software.
  8538. //
  8539. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8540. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8541. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8542. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8543. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8544. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8545. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8546. 'use strict';
  8547. // If obj.hasOwnProperty has been overridden, then calling
  8548. // obj.hasOwnProperty(prop) will break.
  8549. // See: https://github.com/joyent/node/issues/1707
  8550. function hasOwnProperty(obj, prop) {
  8551. return Object.prototype.hasOwnProperty.call(obj, prop);
  8552. }
  8553. module.exports = function(qs, sep, eq, options) {
  8554. sep = sep || '&';
  8555. eq = eq || '=';
  8556. var obj = {};
  8557. if (typeof qs !== 'string' || qs.length === 0) {
  8558. return obj;
  8559. }
  8560. var regexp = /\+/g;
  8561. qs = qs.split(sep);
  8562. var maxKeys = 1000;
  8563. if (options && typeof options.maxKeys === 'number') {
  8564. maxKeys = options.maxKeys;
  8565. }
  8566. var len = qs.length;
  8567. // maxKeys <= 0 means that we should not limit keys count
  8568. if (maxKeys > 0 && len > maxKeys) {
  8569. len = maxKeys;
  8570. }
  8571. for (var i = 0; i < len; ++i) {
  8572. var x = qs[i].replace(regexp, '%20'),
  8573. idx = x.indexOf(eq),
  8574. kstr, vstr, k, v;
  8575. if (idx >= 0) {
  8576. kstr = x.substr(0, idx);
  8577. vstr = x.substr(idx + 1);
  8578. } else {
  8579. kstr = x;
  8580. vstr = '';
  8581. }
  8582. k = decodeURIComponent(kstr);
  8583. v = decodeURIComponent(vstr);
  8584. if (!hasOwnProperty(obj, k)) {
  8585. obj[k] = v;
  8586. } else if (isArray(obj[k])) {
  8587. obj[k].push(v);
  8588. } else {
  8589. obj[k] = [obj[k], v];
  8590. }
  8591. }
  8592. return obj;
  8593. };
  8594. var isArray = Array.isArray || function (xs) {
  8595. return Object.prototype.toString.call(xs) === '[object Array]';
  8596. };
  8597. },{}],95:[function(require,module,exports){
  8598. // Copyright Joyent, Inc. and other Node contributors.
  8599. //
  8600. // Permission is hereby granted, free of charge, to any person obtaining a
  8601. // copy of this software and associated documentation files (the
  8602. // "Software"), to deal in the Software without restriction, including
  8603. // without limitation the rights to use, copy, modify, merge, publish,
  8604. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8605. // persons to whom the Software is furnished to do so, subject to the
  8606. // following conditions:
  8607. //
  8608. // The above copyright notice and this permission notice shall be included
  8609. // in all copies or substantial portions of the Software.
  8610. //
  8611. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8612. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8613. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8614. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8615. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8616. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8617. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8618. 'use strict';
  8619. var stringifyPrimitive = function(v) {
  8620. switch (typeof v) {
  8621. case 'string':
  8622. return v;
  8623. case 'boolean':
  8624. return v ? 'true' : 'false';
  8625. case 'number':
  8626. return isFinite(v) ? v : '';
  8627. default:
  8628. return '';
  8629. }
  8630. };
  8631. module.exports = function(obj, sep, eq, name) {
  8632. sep = sep || '&';
  8633. eq = eq || '=';
  8634. if (obj === null) {
  8635. obj = undefined;
  8636. }
  8637. if (typeof obj === 'object') {
  8638. return map(objectKeys(obj), function(k) {
  8639. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  8640. if (isArray(obj[k])) {
  8641. return map(obj[k], function(v) {
  8642. return ks + encodeURIComponent(stringifyPrimitive(v));
  8643. }).join(sep);
  8644. } else {
  8645. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  8646. }
  8647. }).join(sep);
  8648. }
  8649. if (!name) return '';
  8650. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  8651. encodeURIComponent(stringifyPrimitive(obj));
  8652. };
  8653. var isArray = Array.isArray || function (xs) {
  8654. return Object.prototype.toString.call(xs) === '[object Array]';
  8655. };
  8656. function map (xs, f) {
  8657. if (xs.map) return xs.map(f);
  8658. var res = [];
  8659. for (var i = 0; i < xs.length; i++) {
  8660. res.push(f(xs[i], i));
  8661. }
  8662. return res;
  8663. }
  8664. var objectKeys = Object.keys || function (obj) {
  8665. var res = [];
  8666. for (var key in obj) {
  8667. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  8668. }
  8669. return res;
  8670. };
  8671. },{}],96:[function(require,module,exports){
  8672. 'use strict';
  8673. exports.decode = exports.parse = require('./decode');
  8674. exports.encode = exports.stringify = require('./encode');
  8675. },{"./decode":94,"./encode":95}],97:[function(require,module,exports){
  8676. module.exports = require('./lib/_stream_duplex.js');
  8677. },{"./lib/_stream_duplex.js":98}],98:[function(require,module,exports){
  8678. // Copyright Joyent, Inc. and other Node contributors.
  8679. //
  8680. // Permission is hereby granted, free of charge, to any person obtaining a
  8681. // copy of this software and associated documentation files (the
  8682. // "Software"), to deal in the Software without restriction, including
  8683. // without limitation the rights to use, copy, modify, merge, publish,
  8684. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8685. // persons to whom the Software is furnished to do so, subject to the
  8686. // following conditions:
  8687. //
  8688. // The above copyright notice and this permission notice shall be included
  8689. // in all copies or substantial portions of the Software.
  8690. //
  8691. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8692. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8693. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8694. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8695. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8696. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8697. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8698. // a duplex stream is just a stream that is both readable and writable.
  8699. // Since JS doesn't have multiple prototypal inheritance, this class
  8700. // prototypally inherits from Readable, and then parasitically from
  8701. // Writable.
  8702. 'use strict';
  8703. /*<replacement>*/
  8704. var pna = require('process-nextick-args');
  8705. /*</replacement>*/
  8706. /*<replacement>*/
  8707. var objectKeys = Object.keys || function (obj) {
  8708. var keys = [];
  8709. for (var key in obj) {
  8710. keys.push(key);
  8711. }return keys;
  8712. };
  8713. /*</replacement>*/
  8714. module.exports = Duplex;
  8715. /*<replacement>*/
  8716. var util = require('core-util-is');
  8717. util.inherits = require('inherits');
  8718. /*</replacement>*/
  8719. var Readable = require('./_stream_readable');
  8720. var Writable = require('./_stream_writable');
  8721. util.inherits(Duplex, Readable);
  8722. {
  8723. // avoid scope creep, the keys array can then be collected
  8724. var keys = objectKeys(Writable.prototype);
  8725. for (var v = 0; v < keys.length; v++) {
  8726. var method = keys[v];
  8727. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  8728. }
  8729. }
  8730. function Duplex(options) {
  8731. if (!(this instanceof Duplex)) return new Duplex(options);
  8732. Readable.call(this, options);
  8733. Writable.call(this, options);
  8734. if (options && options.readable === false) this.readable = false;
  8735. if (options && options.writable === false) this.writable = false;
  8736. this.allowHalfOpen = true;
  8737. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  8738. this.once('end', onend);
  8739. }
  8740. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  8741. // making it explicit this property is not enumerable
  8742. // because otherwise some prototype manipulation in
  8743. // userland will fail
  8744. enumerable: false,
  8745. get: function () {
  8746. return this._writableState.highWaterMark;
  8747. }
  8748. });
  8749. // the no-half-open enforcer
  8750. function onend() {
  8751. // if we allow half-open state, or if the writable side ended,
  8752. // then we're ok.
  8753. if (this.allowHalfOpen || this._writableState.ended) return;
  8754. // no more data can be written.
  8755. // But allow more writes to happen in this tick.
  8756. pna.nextTick(onEndNT, this);
  8757. }
  8758. function onEndNT(self) {
  8759. self.end();
  8760. }
  8761. Object.defineProperty(Duplex.prototype, 'destroyed', {
  8762. get: function () {
  8763. if (this._readableState === undefined || this._writableState === undefined) {
  8764. return false;
  8765. }
  8766. return this._readableState.destroyed && this._writableState.destroyed;
  8767. },
  8768. set: function (value) {
  8769. // we ignore the value if the stream
  8770. // has not been initialized yet
  8771. if (this._readableState === undefined || this._writableState === undefined) {
  8772. return;
  8773. }
  8774. // backward compatibility, the user is explicitly
  8775. // managing destroyed
  8776. this._readableState.destroyed = value;
  8777. this._writableState.destroyed = value;
  8778. }
  8779. });
  8780. Duplex.prototype._destroy = function (err, cb) {
  8781. this.push(null);
  8782. this.end();
  8783. pna.nextTick(cb, err);
  8784. };
  8785. },{"./_stream_readable":100,"./_stream_writable":102,"core-util-is":14,"inherits":80,"process-nextick-args":91}],99:[function(require,module,exports){
  8786. // Copyright Joyent, Inc. and other Node contributors.
  8787. //
  8788. // Permission is hereby granted, free of charge, to any person obtaining a
  8789. // copy of this software and associated documentation files (the
  8790. // "Software"), to deal in the Software without restriction, including
  8791. // without limitation the rights to use, copy, modify, merge, publish,
  8792. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8793. // persons to whom the Software is furnished to do so, subject to the
  8794. // following conditions:
  8795. //
  8796. // The above copyright notice and this permission notice shall be included
  8797. // in all copies or substantial portions of the Software.
  8798. //
  8799. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8800. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8801. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8802. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8803. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8804. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8805. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8806. // a passthrough stream.
  8807. // basically just the most minimal sort of Transform stream.
  8808. // Every written chunk gets output as-is.
  8809. 'use strict';
  8810. module.exports = PassThrough;
  8811. var Transform = require('./_stream_transform');
  8812. /*<replacement>*/
  8813. var util = require('core-util-is');
  8814. util.inherits = require('inherits');
  8815. /*</replacement>*/
  8816. util.inherits(PassThrough, Transform);
  8817. function PassThrough(options) {
  8818. if (!(this instanceof PassThrough)) return new PassThrough(options);
  8819. Transform.call(this, options);
  8820. }
  8821. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  8822. cb(null, chunk);
  8823. };
  8824. },{"./_stream_transform":101,"core-util-is":14,"inherits":80}],100:[function(require,module,exports){
  8825. (function (process,global){
  8826. // Copyright Joyent, Inc. and other Node contributors.
  8827. //
  8828. // Permission is hereby granted, free of charge, to any person obtaining a
  8829. // copy of this software and associated documentation files (the
  8830. // "Software"), to deal in the Software without restriction, including
  8831. // without limitation the rights to use, copy, modify, merge, publish,
  8832. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8833. // persons to whom the Software is furnished to do so, subject to the
  8834. // following conditions:
  8835. //
  8836. // The above copyright notice and this permission notice shall be included
  8837. // in all copies or substantial portions of the Software.
  8838. //
  8839. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8840. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8841. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8842. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8843. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8844. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8845. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8846. 'use strict';
  8847. /*<replacement>*/
  8848. var pna = require('process-nextick-args');
  8849. /*</replacement>*/
  8850. module.exports = Readable;
  8851. /*<replacement>*/
  8852. var isArray = require('isarray');
  8853. /*</replacement>*/
  8854. /*<replacement>*/
  8855. var Duplex;
  8856. /*</replacement>*/
  8857. Readable.ReadableState = ReadableState;
  8858. /*<replacement>*/
  8859. var EE = require('events').EventEmitter;
  8860. var EElistenerCount = function (emitter, type) {
  8861. return emitter.listeners(type).length;
  8862. };
  8863. /*</replacement>*/
  8864. /*<replacement>*/
  8865. var Stream = require('./internal/streams/stream');
  8866. /*</replacement>*/
  8867. /*<replacement>*/
  8868. var Buffer = require('safe-buffer').Buffer;
  8869. var OurUint8Array = global.Uint8Array || function () {};
  8870. function _uint8ArrayToBuffer(chunk) {
  8871. return Buffer.from(chunk);
  8872. }
  8873. function _isUint8Array(obj) {
  8874. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  8875. }
  8876. /*</replacement>*/
  8877. /*<replacement>*/
  8878. var util = require('core-util-is');
  8879. util.inherits = require('inherits');
  8880. /*</replacement>*/
  8881. /*<replacement>*/
  8882. var debugUtil = require('util');
  8883. var debug = void 0;
  8884. if (debugUtil && debugUtil.debuglog) {
  8885. debug = debugUtil.debuglog('stream');
  8886. } else {
  8887. debug = function () {};
  8888. }
  8889. /*</replacement>*/
  8890. var BufferList = require('./internal/streams/BufferList');
  8891. var destroyImpl = require('./internal/streams/destroy');
  8892. var StringDecoder;
  8893. util.inherits(Readable, Stream);
  8894. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  8895. function prependListener(emitter, event, fn) {
  8896. // Sadly this is not cacheable as some libraries bundle their own
  8897. // event emitter implementation with them.
  8898. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  8899. // This is a hack to make sure that our error handler is attached before any
  8900. // userland ones. NEVER DO THIS. This is here only because this code needs
  8901. // to continue to work with older versions of Node.js that do not include
  8902. // the prependListener() method. The goal is to eventually remove this hack.
  8903. 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]];
  8904. }
  8905. function ReadableState(options, stream) {
  8906. Duplex = Duplex || require('./_stream_duplex');
  8907. options = options || {};
  8908. // Duplex streams are both readable and writable, but share
  8909. // the same options object.
  8910. // However, some cases require setting options to different
  8911. // values for the readable and the writable sides of the duplex stream.
  8912. // These options can be provided separately as readableXXX and writableXXX.
  8913. var isDuplex = stream instanceof Duplex;
  8914. // object stream flag. Used to make read(n) ignore n and to
  8915. // make all the buffer merging and length checks go away
  8916. this.objectMode = !!options.objectMode;
  8917. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  8918. // the point at which it stops calling _read() to fill the buffer
  8919. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  8920. var hwm = options.highWaterMark;
  8921. var readableHwm = options.readableHighWaterMark;
  8922. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  8923. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  8924. // cast to ints.
  8925. this.highWaterMark = Math.floor(this.highWaterMark);
  8926. // A linked list is used to store data chunks instead of an array because the
  8927. // linked list can remove elements from the beginning faster than
  8928. // array.shift()
  8929. this.buffer = new BufferList();
  8930. this.length = 0;
  8931. this.pipes = null;
  8932. this.pipesCount = 0;
  8933. this.flowing = null;
  8934. this.ended = false;
  8935. this.endEmitted = false;
  8936. this.reading = false;
  8937. // a flag to be able to tell if the event 'readable'/'data' is emitted
  8938. // immediately, or on a later tick. We set this to true at first, because
  8939. // any actions that shouldn't happen until "later" should generally also
  8940. // not happen before the first read call.
  8941. this.sync = true;
  8942. // whenever we return null, then we set a flag to say
  8943. // that we're awaiting a 'readable' event emission.
  8944. this.needReadable = false;
  8945. this.emittedReadable = false;
  8946. this.readableListening = false;
  8947. this.resumeScheduled = false;
  8948. // has it been destroyed
  8949. this.destroyed = false;
  8950. // Crypto is kind of old and crusty. Historically, its default string
  8951. // encoding is 'binary' so we have to make this configurable.
  8952. // Everything else in the universe uses 'utf8', though.
  8953. this.defaultEncoding = options.defaultEncoding || 'utf8';
  8954. // the number of writers that are awaiting a drain event in .pipe()s
  8955. this.awaitDrain = 0;
  8956. // if true, a maybeReadMore has been scheduled
  8957. this.readingMore = false;
  8958. this.decoder = null;
  8959. this.encoding = null;
  8960. if (options.encoding) {
  8961. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  8962. this.decoder = new StringDecoder(options.encoding);
  8963. this.encoding = options.encoding;
  8964. }
  8965. }
  8966. function Readable(options) {
  8967. Duplex = Duplex || require('./_stream_duplex');
  8968. if (!(this instanceof Readable)) return new Readable(options);
  8969. this._readableState = new ReadableState(options, this);
  8970. // legacy
  8971. this.readable = true;
  8972. if (options) {
  8973. if (typeof options.read === 'function') this._read = options.read;
  8974. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  8975. }
  8976. Stream.call(this);
  8977. }
  8978. Object.defineProperty(Readable.prototype, 'destroyed', {
  8979. get: function () {
  8980. if (this._readableState === undefined) {
  8981. return false;
  8982. }
  8983. return this._readableState.destroyed;
  8984. },
  8985. set: function (value) {
  8986. // we ignore the value if the stream
  8987. // has not been initialized yet
  8988. if (!this._readableState) {
  8989. return;
  8990. }
  8991. // backward compatibility, the user is explicitly
  8992. // managing destroyed
  8993. this._readableState.destroyed = value;
  8994. }
  8995. });
  8996. Readable.prototype.destroy = destroyImpl.destroy;
  8997. Readable.prototype._undestroy = destroyImpl.undestroy;
  8998. Readable.prototype._destroy = function (err, cb) {
  8999. this.push(null);
  9000. cb(err);
  9001. };
  9002. // Manually shove something into the read() buffer.
  9003. // This returns true if the highWaterMark has not been hit yet,
  9004. // similar to how Writable.write() returns true if you should
  9005. // write() some more.
  9006. Readable.prototype.push = function (chunk, encoding) {
  9007. var state = this._readableState;
  9008. var skipChunkCheck;
  9009. if (!state.objectMode) {
  9010. if (typeof chunk === 'string') {
  9011. encoding = encoding || state.defaultEncoding;
  9012. if (encoding !== state.encoding) {
  9013. chunk = Buffer.from(chunk, encoding);
  9014. encoding = '';
  9015. }
  9016. skipChunkCheck = true;
  9017. }
  9018. } else {
  9019. skipChunkCheck = true;
  9020. }
  9021. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  9022. };
  9023. // Unshift should *always* be something directly out of read()
  9024. Readable.prototype.unshift = function (chunk) {
  9025. return readableAddChunk(this, chunk, null, true, false);
  9026. };
  9027. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  9028. var state = stream._readableState;
  9029. if (chunk === null) {
  9030. state.reading = false;
  9031. onEofChunk(stream, state);
  9032. } else {
  9033. var er;
  9034. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  9035. if (er) {
  9036. stream.emit('error', er);
  9037. } else if (state.objectMode || chunk && chunk.length > 0) {
  9038. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  9039. chunk = _uint8ArrayToBuffer(chunk);
  9040. }
  9041. if (addToFront) {
  9042. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  9043. } else if (state.ended) {
  9044. stream.emit('error', new Error('stream.push() after EOF'));
  9045. } else {
  9046. state.reading = false;
  9047. if (state.decoder && !encoding) {
  9048. chunk = state.decoder.write(chunk);
  9049. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  9050. } else {
  9051. addChunk(stream, state, chunk, false);
  9052. }
  9053. }
  9054. } else if (!addToFront) {
  9055. state.reading = false;
  9056. }
  9057. }
  9058. return needMoreData(state);
  9059. }
  9060. function addChunk(stream, state, chunk, addToFront) {
  9061. if (state.flowing && state.length === 0 && !state.sync) {
  9062. stream.emit('data', chunk);
  9063. stream.read(0);
  9064. } else {
  9065. // update the buffer info.
  9066. state.length += state.objectMode ? 1 : chunk.length;
  9067. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  9068. if (state.needReadable) emitReadable(stream);
  9069. }
  9070. maybeReadMore(stream, state);
  9071. }
  9072. function chunkInvalid(state, chunk) {
  9073. var er;
  9074. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  9075. er = new TypeError('Invalid non-string/buffer chunk');
  9076. }
  9077. return er;
  9078. }
  9079. // if it's past the high water mark, we can push in some more.
  9080. // Also, if we have no data yet, we can stand some
  9081. // more bytes. This is to work around cases where hwm=0,
  9082. // such as the repl. Also, if the push() triggered a
  9083. // readable event, and the user called read(largeNumber) such that
  9084. // needReadable was set, then we ought to push more, so that another
  9085. // 'readable' event will be triggered.
  9086. function needMoreData(state) {
  9087. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  9088. }
  9089. Readable.prototype.isPaused = function () {
  9090. return this._readableState.flowing === false;
  9091. };
  9092. // backwards compatibility.
  9093. Readable.prototype.setEncoding = function (enc) {
  9094. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9095. this._readableState.decoder = new StringDecoder(enc);
  9096. this._readableState.encoding = enc;
  9097. return this;
  9098. };
  9099. // Don't raise the hwm > 8MB
  9100. var MAX_HWM = 0x800000;
  9101. function computeNewHighWaterMark(n) {
  9102. if (n >= MAX_HWM) {
  9103. n = MAX_HWM;
  9104. } else {
  9105. // Get the next highest power of 2 to prevent increasing hwm excessively in
  9106. // tiny amounts
  9107. n--;
  9108. n |= n >>> 1;
  9109. n |= n >>> 2;
  9110. n |= n >>> 4;
  9111. n |= n >>> 8;
  9112. n |= n >>> 16;
  9113. n++;
  9114. }
  9115. return n;
  9116. }
  9117. // This function is designed to be inlinable, so please take care when making
  9118. // changes to the function body.
  9119. function howMuchToRead(n, state) {
  9120. if (n <= 0 || state.length === 0 && state.ended) return 0;
  9121. if (state.objectMode) return 1;
  9122. if (n !== n) {
  9123. // Only flow one buffer at a time
  9124. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  9125. }
  9126. // If we're asking for more than the current hwm, then raise the hwm.
  9127. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  9128. if (n <= state.length) return n;
  9129. // Don't have enough
  9130. if (!state.ended) {
  9131. state.needReadable = true;
  9132. return 0;
  9133. }
  9134. return state.length;
  9135. }
  9136. // you can override either this method, or the async _read(n) below.
  9137. Readable.prototype.read = function (n) {
  9138. debug('read', n);
  9139. n = parseInt(n, 10);
  9140. var state = this._readableState;
  9141. var nOrig = n;
  9142. if (n !== 0) state.emittedReadable = false;
  9143. // if we're doing read(0) to trigger a readable event, but we
  9144. // already have a bunch of data in the buffer, then just trigger
  9145. // the 'readable' event and move on.
  9146. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  9147. debug('read: emitReadable', state.length, state.ended);
  9148. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  9149. return null;
  9150. }
  9151. n = howMuchToRead(n, state);
  9152. // if we've ended, and we're now clear, then finish it up.
  9153. if (n === 0 && state.ended) {
  9154. if (state.length === 0) endReadable(this);
  9155. return null;
  9156. }
  9157. // All the actual chunk generation logic needs to be
  9158. // *below* the call to _read. The reason is that in certain
  9159. // synthetic stream cases, such as passthrough streams, _read
  9160. // may be a completely synchronous operation which may change
  9161. // the state of the read buffer, providing enough data when
  9162. // before there was *not* enough.
  9163. //
  9164. // So, the steps are:
  9165. // 1. Figure out what the state of things will be after we do
  9166. // a read from the buffer.
  9167. //
  9168. // 2. If that resulting state will trigger a _read, then call _read.
  9169. // Note that this may be asynchronous, or synchronous. Yes, it is
  9170. // deeply ugly to write APIs this way, but that still doesn't mean
  9171. // that the Readable class should behave improperly, as streams are
  9172. // designed to be sync/async agnostic.
  9173. // Take note if the _read call is sync or async (ie, if the read call
  9174. // has returned yet), so that we know whether or not it's safe to emit
  9175. // 'readable' etc.
  9176. //
  9177. // 3. Actually pull the requested chunks out of the buffer and return.
  9178. // if we need a readable event, then we need to do some reading.
  9179. var doRead = state.needReadable;
  9180. debug('need readable', doRead);
  9181. // if we currently have less than the highWaterMark, then also read some
  9182. if (state.length === 0 || state.length - n < state.highWaterMark) {
  9183. doRead = true;
  9184. debug('length less than watermark', doRead);
  9185. }
  9186. // however, if we've ended, then there's no point, and if we're already
  9187. // reading, then it's unnecessary.
  9188. if (state.ended || state.reading) {
  9189. doRead = false;
  9190. debug('reading or ended', doRead);
  9191. } else if (doRead) {
  9192. debug('do read');
  9193. state.reading = true;
  9194. state.sync = true;
  9195. // if the length is currently zero, then we *need* a readable event.
  9196. if (state.length === 0) state.needReadable = true;
  9197. // call internal read method
  9198. this._read(state.highWaterMark);
  9199. state.sync = false;
  9200. // If _read pushed data synchronously, then `reading` will be false,
  9201. // and we need to re-evaluate how much data we can return to the user.
  9202. if (!state.reading) n = howMuchToRead(nOrig, state);
  9203. }
  9204. var ret;
  9205. if (n > 0) ret = fromList(n, state);else ret = null;
  9206. if (ret === null) {
  9207. state.needReadable = true;
  9208. n = 0;
  9209. } else {
  9210. state.length -= n;
  9211. }
  9212. if (state.length === 0) {
  9213. // If we have nothing in the buffer, then we want to know
  9214. // as soon as we *do* get something into the buffer.
  9215. if (!state.ended) state.needReadable = true;
  9216. // If we tried to read() past the EOF, then emit end on the next tick.
  9217. if (nOrig !== n && state.ended) endReadable(this);
  9218. }
  9219. if (ret !== null) this.emit('data', ret);
  9220. return ret;
  9221. };
  9222. function onEofChunk(stream, state) {
  9223. if (state.ended) return;
  9224. if (state.decoder) {
  9225. var chunk = state.decoder.end();
  9226. if (chunk && chunk.length) {
  9227. state.buffer.push(chunk);
  9228. state.length += state.objectMode ? 1 : chunk.length;
  9229. }
  9230. }
  9231. state.ended = true;
  9232. // emit 'readable' now to make sure it gets picked up.
  9233. emitReadable(stream);
  9234. }
  9235. // Don't emit readable right away in sync mode, because this can trigger
  9236. // another read() call => stack overflow. This way, it might trigger
  9237. // a nextTick recursion warning, but that's not so bad.
  9238. function emitReadable(stream) {
  9239. var state = stream._readableState;
  9240. state.needReadable = false;
  9241. if (!state.emittedReadable) {
  9242. debug('emitReadable', state.flowing);
  9243. state.emittedReadable = true;
  9244. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  9245. }
  9246. }
  9247. function emitReadable_(stream) {
  9248. debug('emit readable');
  9249. stream.emit('readable');
  9250. flow(stream);
  9251. }
  9252. // at this point, the user has presumably seen the 'readable' event,
  9253. // and called read() to consume some data. that may have triggered
  9254. // in turn another _read(n) call, in which case reading = true if
  9255. // it's in progress.
  9256. // However, if we're not ended, or reading, and the length < hwm,
  9257. // then go ahead and try to read some more preemptively.
  9258. function maybeReadMore(stream, state) {
  9259. if (!state.readingMore) {
  9260. state.readingMore = true;
  9261. pna.nextTick(maybeReadMore_, stream, state);
  9262. }
  9263. }
  9264. function maybeReadMore_(stream, state) {
  9265. var len = state.length;
  9266. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  9267. debug('maybeReadMore read 0');
  9268. stream.read(0);
  9269. if (len === state.length)
  9270. // didn't get any data, stop spinning.
  9271. break;else len = state.length;
  9272. }
  9273. state.readingMore = false;
  9274. }
  9275. // abstract method. to be overridden in specific implementation classes.
  9276. // call cb(er, data) where data is <= n in length.
  9277. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  9278. // arbitrary, and perhaps not very meaningful.
  9279. Readable.prototype._read = function (n) {
  9280. this.emit('error', new Error('_read() is not implemented'));
  9281. };
  9282. Readable.prototype.pipe = function (dest, pipeOpts) {
  9283. var src = this;
  9284. var state = this._readableState;
  9285. switch (state.pipesCount) {
  9286. case 0:
  9287. state.pipes = dest;
  9288. break;
  9289. case 1:
  9290. state.pipes = [state.pipes, dest];
  9291. break;
  9292. default:
  9293. state.pipes.push(dest);
  9294. break;
  9295. }
  9296. state.pipesCount += 1;
  9297. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  9298. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  9299. var endFn = doEnd ? onend : unpipe;
  9300. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  9301. dest.on('unpipe', onunpipe);
  9302. function onunpipe(readable, unpipeInfo) {
  9303. debug('onunpipe');
  9304. if (readable === src) {
  9305. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  9306. unpipeInfo.hasUnpiped = true;
  9307. cleanup();
  9308. }
  9309. }
  9310. }
  9311. function onend() {
  9312. debug('onend');
  9313. dest.end();
  9314. }
  9315. // when the dest drains, it reduces the awaitDrain counter
  9316. // on the source. This would be more elegant with a .once()
  9317. // handler in flow(), but adding and removing repeatedly is
  9318. // too slow.
  9319. var ondrain = pipeOnDrain(src);
  9320. dest.on('drain', ondrain);
  9321. var cleanedUp = false;
  9322. function cleanup() {
  9323. debug('cleanup');
  9324. // cleanup event handlers once the pipe is broken
  9325. dest.removeListener('close', onclose);
  9326. dest.removeListener('finish', onfinish);
  9327. dest.removeListener('drain', ondrain);
  9328. dest.removeListener('error', onerror);
  9329. dest.removeListener('unpipe', onunpipe);
  9330. src.removeListener('end', onend);
  9331. src.removeListener('end', unpipe);
  9332. src.removeListener('data', ondata);
  9333. cleanedUp = true;
  9334. // if the reader is waiting for a drain event from this
  9335. // specific writer, then it would cause it to never start
  9336. // flowing again.
  9337. // So, if this is awaiting a drain, then we just call it now.
  9338. // If we don't know, then assume that we are waiting for one.
  9339. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  9340. }
  9341. // If the user pushes more data while we're writing to dest then we'll end up
  9342. // in ondata again. However, we only want to increase awaitDrain once because
  9343. // dest will only emit one 'drain' event for the multiple writes.
  9344. // => Introduce a guard on increasing awaitDrain.
  9345. var increasedAwaitDrain = false;
  9346. src.on('data', ondata);
  9347. function ondata(chunk) {
  9348. debug('ondata');
  9349. increasedAwaitDrain = false;
  9350. var ret = dest.write(chunk);
  9351. if (false === ret && !increasedAwaitDrain) {
  9352. // If the user unpiped during `dest.write()`, it is possible
  9353. // to get stuck in a permanently paused state if that write
  9354. // also returned false.
  9355. // => Check whether `dest` is still a piping destination.
  9356. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  9357. debug('false write response, pause', src._readableState.awaitDrain);
  9358. src._readableState.awaitDrain++;
  9359. increasedAwaitDrain = true;
  9360. }
  9361. src.pause();
  9362. }
  9363. }
  9364. // if the dest has an error, then stop piping into it.
  9365. // however, don't suppress the throwing behavior for this.
  9366. function onerror(er) {
  9367. debug('onerror', er);
  9368. unpipe();
  9369. dest.removeListener('error', onerror);
  9370. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  9371. }
  9372. // Make sure our error handler is attached before userland ones.
  9373. prependListener(dest, 'error', onerror);
  9374. // Both close and finish should trigger unpipe, but only once.
  9375. function onclose() {
  9376. dest.removeListener('finish', onfinish);
  9377. unpipe();
  9378. }
  9379. dest.once('close', onclose);
  9380. function onfinish() {
  9381. debug('onfinish');
  9382. dest.removeListener('close', onclose);
  9383. unpipe();
  9384. }
  9385. dest.once('finish', onfinish);
  9386. function unpipe() {
  9387. debug('unpipe');
  9388. src.unpipe(dest);
  9389. }
  9390. // tell the dest that it's being piped to
  9391. dest.emit('pipe', src);
  9392. // start the flow if it hasn't been started already.
  9393. if (!state.flowing) {
  9394. debug('pipe resume');
  9395. src.resume();
  9396. }
  9397. return dest;
  9398. };
  9399. function pipeOnDrain(src) {
  9400. return function () {
  9401. var state = src._readableState;
  9402. debug('pipeOnDrain', state.awaitDrain);
  9403. if (state.awaitDrain) state.awaitDrain--;
  9404. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  9405. state.flowing = true;
  9406. flow(src);
  9407. }
  9408. };
  9409. }
  9410. Readable.prototype.unpipe = function (dest) {
  9411. var state = this._readableState;
  9412. var unpipeInfo = { hasUnpiped: false };
  9413. // if we're not piping anywhere, then do nothing.
  9414. if (state.pipesCount === 0) return this;
  9415. // just one destination. most common case.
  9416. if (state.pipesCount === 1) {
  9417. // passed in one, but it's not the right one.
  9418. if (dest && dest !== state.pipes) return this;
  9419. if (!dest) dest = state.pipes;
  9420. // got a match.
  9421. state.pipes = null;
  9422. state.pipesCount = 0;
  9423. state.flowing = false;
  9424. if (dest) dest.emit('unpipe', this, unpipeInfo);
  9425. return this;
  9426. }
  9427. // slow case. multiple pipe destinations.
  9428. if (!dest) {
  9429. // remove all.
  9430. var dests = state.pipes;
  9431. var len = state.pipesCount;
  9432. state.pipes = null;
  9433. state.pipesCount = 0;
  9434. state.flowing = false;
  9435. for (var i = 0; i < len; i++) {
  9436. dests[i].emit('unpipe', this, unpipeInfo);
  9437. }return this;
  9438. }
  9439. // try to find the right one.
  9440. var index = indexOf(state.pipes, dest);
  9441. if (index === -1) return this;
  9442. state.pipes.splice(index, 1);
  9443. state.pipesCount -= 1;
  9444. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  9445. dest.emit('unpipe', this, unpipeInfo);
  9446. return this;
  9447. };
  9448. // set up data events if they are asked for
  9449. // Ensure readable listeners eventually get something
  9450. Readable.prototype.on = function (ev, fn) {
  9451. var res = Stream.prototype.on.call(this, ev, fn);
  9452. if (ev === 'data') {
  9453. // Start flowing on next tick if stream isn't explicitly paused
  9454. if (this._readableState.flowing !== false) this.resume();
  9455. } else if (ev === 'readable') {
  9456. var state = this._readableState;
  9457. if (!state.endEmitted && !state.readableListening) {
  9458. state.readableListening = state.needReadable = true;
  9459. state.emittedReadable = false;
  9460. if (!state.reading) {
  9461. pna.nextTick(nReadingNextTick, this);
  9462. } else if (state.length) {
  9463. emitReadable(this);
  9464. }
  9465. }
  9466. }
  9467. return res;
  9468. };
  9469. Readable.prototype.addListener = Readable.prototype.on;
  9470. function nReadingNextTick(self) {
  9471. debug('readable nexttick read 0');
  9472. self.read(0);
  9473. }
  9474. // pause() and resume() are remnants of the legacy readable stream API
  9475. // If the user uses them, then switch into old mode.
  9476. Readable.prototype.resume = function () {
  9477. var state = this._readableState;
  9478. if (!state.flowing) {
  9479. debug('resume');
  9480. state.flowing = true;
  9481. resume(this, state);
  9482. }
  9483. return this;
  9484. };
  9485. function resume(stream, state) {
  9486. if (!state.resumeScheduled) {
  9487. state.resumeScheduled = true;
  9488. pna.nextTick(resume_, stream, state);
  9489. }
  9490. }
  9491. function resume_(stream, state) {
  9492. if (!state.reading) {
  9493. debug('resume read 0');
  9494. stream.read(0);
  9495. }
  9496. state.resumeScheduled = false;
  9497. state.awaitDrain = 0;
  9498. stream.emit('resume');
  9499. flow(stream);
  9500. if (state.flowing && !state.reading) stream.read(0);
  9501. }
  9502. Readable.prototype.pause = function () {
  9503. debug('call pause flowing=%j', this._readableState.flowing);
  9504. if (false !== this._readableState.flowing) {
  9505. debug('pause');
  9506. this._readableState.flowing = false;
  9507. this.emit('pause');
  9508. }
  9509. return this;
  9510. };
  9511. function flow(stream) {
  9512. var state = stream._readableState;
  9513. debug('flow', state.flowing);
  9514. while (state.flowing && stream.read() !== null) {}
  9515. }
  9516. // wrap an old-style stream as the async data source.
  9517. // This is *not* part of the readable stream interface.
  9518. // It is an ugly unfortunate mess of history.
  9519. Readable.prototype.wrap = function (stream) {
  9520. var _this = this;
  9521. var state = this._readableState;
  9522. var paused = false;
  9523. stream.on('end', function () {
  9524. debug('wrapped end');
  9525. if (state.decoder && !state.ended) {
  9526. var chunk = state.decoder.end();
  9527. if (chunk && chunk.length) _this.push(chunk);
  9528. }
  9529. _this.push(null);
  9530. });
  9531. stream.on('data', function (chunk) {
  9532. debug('wrapped data');
  9533. if (state.decoder) chunk = state.decoder.write(chunk);
  9534. // don't skip over falsy values in objectMode
  9535. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  9536. var ret = _this.push(chunk);
  9537. if (!ret) {
  9538. paused = true;
  9539. stream.pause();
  9540. }
  9541. });
  9542. // proxy all the other methods.
  9543. // important when wrapping filters and duplexes.
  9544. for (var i in stream) {
  9545. if (this[i] === undefined && typeof stream[i] === 'function') {
  9546. this[i] = function (method) {
  9547. return function () {
  9548. return stream[method].apply(stream, arguments);
  9549. };
  9550. }(i);
  9551. }
  9552. }
  9553. // proxy certain important events.
  9554. for (var n = 0; n < kProxyEvents.length; n++) {
  9555. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  9556. }
  9557. // when we try to consume some more bytes, simply unpause the
  9558. // underlying stream.
  9559. this._read = function (n) {
  9560. debug('wrapped _read', n);
  9561. if (paused) {
  9562. paused = false;
  9563. stream.resume();
  9564. }
  9565. };
  9566. return this;
  9567. };
  9568. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  9569. // making it explicit this property is not enumerable
  9570. // because otherwise some prototype manipulation in
  9571. // userland will fail
  9572. enumerable: false,
  9573. get: function () {
  9574. return this._readableState.highWaterMark;
  9575. }
  9576. });
  9577. // exposed for testing purposes only.
  9578. Readable._fromList = fromList;
  9579. // Pluck off n bytes from an array of buffers.
  9580. // Length is the combined lengths of all the buffers in the list.
  9581. // This function is designed to be inlinable, so please take care when making
  9582. // changes to the function body.
  9583. function fromList(n, state) {
  9584. // nothing buffered
  9585. if (state.length === 0) return null;
  9586. var ret;
  9587. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  9588. // read it all, truncate the list
  9589. 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);
  9590. state.buffer.clear();
  9591. } else {
  9592. // read part of list
  9593. ret = fromListPartial(n, state.buffer, state.decoder);
  9594. }
  9595. return ret;
  9596. }
  9597. // Extracts only enough buffered data to satisfy the amount requested.
  9598. // This function is designed to be inlinable, so please take care when making
  9599. // changes to the function body.
  9600. function fromListPartial(n, list, hasStrings) {
  9601. var ret;
  9602. if (n < list.head.data.length) {
  9603. // slice is the same for buffers and strings
  9604. ret = list.head.data.slice(0, n);
  9605. list.head.data = list.head.data.slice(n);
  9606. } else if (n === list.head.data.length) {
  9607. // first chunk is a perfect match
  9608. ret = list.shift();
  9609. } else {
  9610. // result spans more than one buffer
  9611. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  9612. }
  9613. return ret;
  9614. }
  9615. // Copies a specified amount of characters from the list of buffered data
  9616. // chunks.
  9617. // This function is designed to be inlinable, so please take care when making
  9618. // changes to the function body.
  9619. function copyFromBufferString(n, list) {
  9620. var p = list.head;
  9621. var c = 1;
  9622. var ret = p.data;
  9623. n -= ret.length;
  9624. while (p = p.next) {
  9625. var str = p.data;
  9626. var nb = n > str.length ? str.length : n;
  9627. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  9628. n -= nb;
  9629. if (n === 0) {
  9630. if (nb === str.length) {
  9631. ++c;
  9632. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9633. } else {
  9634. list.head = p;
  9635. p.data = str.slice(nb);
  9636. }
  9637. break;
  9638. }
  9639. ++c;
  9640. }
  9641. list.length -= c;
  9642. return ret;
  9643. }
  9644. // Copies a specified amount of bytes from the list of buffered data chunks.
  9645. // This function is designed to be inlinable, so please take care when making
  9646. // changes to the function body.
  9647. function copyFromBuffer(n, list) {
  9648. var ret = Buffer.allocUnsafe(n);
  9649. var p = list.head;
  9650. var c = 1;
  9651. p.data.copy(ret);
  9652. n -= p.data.length;
  9653. while (p = p.next) {
  9654. var buf = p.data;
  9655. var nb = n > buf.length ? buf.length : n;
  9656. buf.copy(ret, ret.length - n, 0, nb);
  9657. n -= nb;
  9658. if (n === 0) {
  9659. if (nb === buf.length) {
  9660. ++c;
  9661. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9662. } else {
  9663. list.head = p;
  9664. p.data = buf.slice(nb);
  9665. }
  9666. break;
  9667. }
  9668. ++c;
  9669. }
  9670. list.length -= c;
  9671. return ret;
  9672. }
  9673. function endReadable(stream) {
  9674. var state = stream._readableState;
  9675. // If we get here before consuming all the bytes, then that is a
  9676. // bug in node. Should never happen.
  9677. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  9678. if (!state.endEmitted) {
  9679. state.ended = true;
  9680. pna.nextTick(endReadableNT, state, stream);
  9681. }
  9682. }
  9683. function endReadableNT(state, stream) {
  9684. // Check that we didn't get one last unshift.
  9685. if (!state.endEmitted && state.length === 0) {
  9686. state.endEmitted = true;
  9687. stream.readable = false;
  9688. stream.emit('end');
  9689. }
  9690. }
  9691. function indexOf(xs, x) {
  9692. for (var i = 0, l = xs.length; i < l; i++) {
  9693. if (xs[i] === x) return i;
  9694. }
  9695. return -1;
  9696. }
  9697. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9698. },{"./_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){
  9699. // Copyright Joyent, Inc. and other Node contributors.
  9700. //
  9701. // Permission is hereby granted, free of charge, to any person obtaining a
  9702. // copy of this software and associated documentation files (the
  9703. // "Software"), to deal in the Software without restriction, including
  9704. // without limitation the rights to use, copy, modify, merge, publish,
  9705. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9706. // persons to whom the Software is furnished to do so, subject to the
  9707. // following conditions:
  9708. //
  9709. // The above copyright notice and this permission notice shall be included
  9710. // in all copies or substantial portions of the Software.
  9711. //
  9712. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9713. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9714. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9715. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9716. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9717. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9718. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9719. // a transform stream is a readable/writable stream where you do
  9720. // something with the data. Sometimes it's called a "filter",
  9721. // but that's not a great name for it, since that implies a thing where
  9722. // some bits pass through, and others are simply ignored. (That would
  9723. // be a valid example of a transform, of course.)
  9724. //
  9725. // While the output is causally related to the input, it's not a
  9726. // necessarily symmetric or synchronous transformation. For example,
  9727. // a zlib stream might take multiple plain-text writes(), and then
  9728. // emit a single compressed chunk some time in the future.
  9729. //
  9730. // Here's how this works:
  9731. //
  9732. // The Transform stream has all the aspects of the readable and writable
  9733. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  9734. // internally, and returns false if there's a lot of pending writes
  9735. // buffered up. When you call read(), that calls _read(n) until
  9736. // there's enough pending readable data buffered up.
  9737. //
  9738. // In a transform stream, the written data is placed in a buffer. When
  9739. // _read(n) is called, it transforms the queued up data, calling the
  9740. // buffered _write cb's as it consumes chunks. If consuming a single
  9741. // written chunk would result in multiple output chunks, then the first
  9742. // outputted bit calls the readcb, and subsequent chunks just go into
  9743. // the read buffer, and will cause it to emit 'readable' if necessary.
  9744. //
  9745. // This way, back-pressure is actually determined by the reading side,
  9746. // since _read has to be called to start processing a new chunk. However,
  9747. // a pathological inflate type of transform can cause excessive buffering
  9748. // here. For example, imagine a stream where every byte of input is
  9749. // interpreted as an integer from 0-255, and then results in that many
  9750. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  9751. // 1kb of data being output. In this case, you could write a very small
  9752. // amount of input, and end up with a very large amount of output. In
  9753. // such a pathological inflating mechanism, there'd be no way to tell
  9754. // the system to stop doing the transform. A single 4MB write could
  9755. // cause the system to run out of memory.
  9756. //
  9757. // However, even in such a pathological case, only a single written chunk
  9758. // would be consumed, and then the rest would wait (un-transformed) until
  9759. // the results of the previous transformed chunk were consumed.
  9760. 'use strict';
  9761. module.exports = Transform;
  9762. var Duplex = require('./_stream_duplex');
  9763. /*<replacement>*/
  9764. var util = require('core-util-is');
  9765. util.inherits = require('inherits');
  9766. /*</replacement>*/
  9767. util.inherits(Transform, Duplex);
  9768. function afterTransform(er, data) {
  9769. var ts = this._transformState;
  9770. ts.transforming = false;
  9771. var cb = ts.writecb;
  9772. if (!cb) {
  9773. return this.emit('error', new Error('write callback called multiple times'));
  9774. }
  9775. ts.writechunk = null;
  9776. ts.writecb = null;
  9777. if (data != null) // single equals check for both `null` and `undefined`
  9778. this.push(data);
  9779. cb(er);
  9780. var rs = this._readableState;
  9781. rs.reading = false;
  9782. if (rs.needReadable || rs.length < rs.highWaterMark) {
  9783. this._read(rs.highWaterMark);
  9784. }
  9785. }
  9786. function Transform(options) {
  9787. if (!(this instanceof Transform)) return new Transform(options);
  9788. Duplex.call(this, options);
  9789. this._transformState = {
  9790. afterTransform: afterTransform.bind(this),
  9791. needTransform: false,
  9792. transforming: false,
  9793. writecb: null,
  9794. writechunk: null,
  9795. writeencoding: null
  9796. };
  9797. // start out asking for a readable event once data is transformed.
  9798. this._readableState.needReadable = true;
  9799. // we have implemented the _read method, and done the other things
  9800. // that Readable wants before the first _read call, so unset the
  9801. // sync guard flag.
  9802. this._readableState.sync = false;
  9803. if (options) {
  9804. if (typeof options.transform === 'function') this._transform = options.transform;
  9805. if (typeof options.flush === 'function') this._flush = options.flush;
  9806. }
  9807. // When the writable side finishes, then flush out anything remaining.
  9808. this.on('prefinish', prefinish);
  9809. }
  9810. function prefinish() {
  9811. var _this = this;
  9812. if (typeof this._flush === 'function') {
  9813. this._flush(function (er, data) {
  9814. done(_this, er, data);
  9815. });
  9816. } else {
  9817. done(this, null, null);
  9818. }
  9819. }
  9820. Transform.prototype.push = function (chunk, encoding) {
  9821. this._transformState.needTransform = false;
  9822. return Duplex.prototype.push.call(this, chunk, encoding);
  9823. };
  9824. // This is the part where you do stuff!
  9825. // override this function in implementation classes.
  9826. // 'chunk' is an input chunk.
  9827. //
  9828. // Call `push(newChunk)` to pass along transformed output
  9829. // to the readable side. You may call 'push' zero or more times.
  9830. //
  9831. // Call `cb(err)` when you are done with this chunk. If you pass
  9832. // an error, then that'll put the hurt on the whole operation. If you
  9833. // never call cb(), then you'll never get another chunk.
  9834. Transform.prototype._transform = function (chunk, encoding, cb) {
  9835. throw new Error('_transform() is not implemented');
  9836. };
  9837. Transform.prototype._write = function (chunk, encoding, cb) {
  9838. var ts = this._transformState;
  9839. ts.writecb = cb;
  9840. ts.writechunk = chunk;
  9841. ts.writeencoding = encoding;
  9842. if (!ts.transforming) {
  9843. var rs = this._readableState;
  9844. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  9845. }
  9846. };
  9847. // Doesn't matter what the args are here.
  9848. // _transform does all the work.
  9849. // That we got here means that the readable side wants more data.
  9850. Transform.prototype._read = function (n) {
  9851. var ts = this._transformState;
  9852. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  9853. ts.transforming = true;
  9854. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  9855. } else {
  9856. // mark that we need a transform, so that any data that comes in
  9857. // will get processed, now that we've asked for it.
  9858. ts.needTransform = true;
  9859. }
  9860. };
  9861. Transform.prototype._destroy = function (err, cb) {
  9862. var _this2 = this;
  9863. Duplex.prototype._destroy.call(this, err, function (err2) {
  9864. cb(err2);
  9865. _this2.emit('close');
  9866. });
  9867. };
  9868. function done(stream, er, data) {
  9869. if (er) return stream.emit('error', er);
  9870. if (data != null) // single equals check for both `null` and `undefined`
  9871. stream.push(data);
  9872. // if there's nothing in the write buffer, then that means
  9873. // that nothing more will ever be provided
  9874. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  9875. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  9876. return stream.push(null);
  9877. }
  9878. },{"./_stream_duplex":98,"core-util-is":14,"inherits":80}],102:[function(require,module,exports){
  9879. (function (process,global,setImmediate){
  9880. // Copyright Joyent, Inc. and other Node contributors.
  9881. //
  9882. // Permission is hereby granted, free of charge, to any person obtaining a
  9883. // copy of this software and associated documentation files (the
  9884. // "Software"), to deal in the Software without restriction, including
  9885. // without limitation the rights to use, copy, modify, merge, publish,
  9886. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9887. // persons to whom the Software is furnished to do so, subject to the
  9888. // following conditions:
  9889. //
  9890. // The above copyright notice and this permission notice shall be included
  9891. // in all copies or substantial portions of the Software.
  9892. //
  9893. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9894. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9895. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9896. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9897. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9898. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9899. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9900. // A bit simpler than readable streams.
  9901. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  9902. // the drain event emission and buffering.
  9903. 'use strict';
  9904. /*<replacement>*/
  9905. var pna = require('process-nextick-args');
  9906. /*</replacement>*/
  9907. module.exports = Writable;
  9908. /* <replacement> */
  9909. function WriteReq(chunk, encoding, cb) {
  9910. this.chunk = chunk;
  9911. this.encoding = encoding;
  9912. this.callback = cb;
  9913. this.next = null;
  9914. }
  9915. // It seems a linked list but it is not
  9916. // there will be only 2 of these for each stream
  9917. function CorkedRequest(state) {
  9918. var _this = this;
  9919. this.next = null;
  9920. this.entry = null;
  9921. this.finish = function () {
  9922. onCorkedFinish(_this, state);
  9923. };
  9924. }
  9925. /* </replacement> */
  9926. /*<replacement>*/
  9927. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  9928. /*</replacement>*/
  9929. /*<replacement>*/
  9930. var Duplex;
  9931. /*</replacement>*/
  9932. Writable.WritableState = WritableState;
  9933. /*<replacement>*/
  9934. var util = require('core-util-is');
  9935. util.inherits = require('inherits');
  9936. /*</replacement>*/
  9937. /*<replacement>*/
  9938. var internalUtil = {
  9939. deprecate: require('util-deprecate')
  9940. };
  9941. /*</replacement>*/
  9942. /*<replacement>*/
  9943. var Stream = require('./internal/streams/stream');
  9944. /*</replacement>*/
  9945. /*<replacement>*/
  9946. var Buffer = require('safe-buffer').Buffer;
  9947. var OurUint8Array = global.Uint8Array || function () {};
  9948. function _uint8ArrayToBuffer(chunk) {
  9949. return Buffer.from(chunk);
  9950. }
  9951. function _isUint8Array(obj) {
  9952. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  9953. }
  9954. /*</replacement>*/
  9955. var destroyImpl = require('./internal/streams/destroy');
  9956. util.inherits(Writable, Stream);
  9957. function nop() {}
  9958. function WritableState(options, stream) {
  9959. Duplex = Duplex || require('./_stream_duplex');
  9960. options = options || {};
  9961. // Duplex streams are both readable and writable, but share
  9962. // the same options object.
  9963. // However, some cases require setting options to different
  9964. // values for the readable and the writable sides of the duplex stream.
  9965. // These options can be provided separately as readableXXX and writableXXX.
  9966. var isDuplex = stream instanceof Duplex;
  9967. // object stream flag to indicate whether or not this stream
  9968. // contains buffers or objects.
  9969. this.objectMode = !!options.objectMode;
  9970. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  9971. // the point at which write() starts returning false
  9972. // Note: 0 is a valid value, means that we always return false if
  9973. // the entire buffer is not flushed immediately on write()
  9974. var hwm = options.highWaterMark;
  9975. var writableHwm = options.writableHighWaterMark;
  9976. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  9977. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  9978. // cast to ints.
  9979. this.highWaterMark = Math.floor(this.highWaterMark);
  9980. // if _final has been called
  9981. this.finalCalled = false;
  9982. // drain event flag.
  9983. this.needDrain = false;
  9984. // at the start of calling end()
  9985. this.ending = false;
  9986. // when end() has been called, and returned
  9987. this.ended = false;
  9988. // when 'finish' is emitted
  9989. this.finished = false;
  9990. // has it been destroyed
  9991. this.destroyed = false;
  9992. // should we decode strings into buffers before passing to _write?
  9993. // this is here so that some node-core streams can optimize string
  9994. // handling at a lower level.
  9995. var noDecode = options.decodeStrings === false;
  9996. this.decodeStrings = !noDecode;
  9997. // Crypto is kind of old and crusty. Historically, its default string
  9998. // encoding is 'binary' so we have to make this configurable.
  9999. // Everything else in the universe uses 'utf8', though.
  10000. this.defaultEncoding = options.defaultEncoding || 'utf8';
  10001. // not an actual buffer we keep track of, but a measurement
  10002. // of how much we're waiting to get pushed to some underlying
  10003. // socket or file.
  10004. this.length = 0;
  10005. // a flag to see when we're in the middle of a write.
  10006. this.writing = false;
  10007. // when true all writes will be buffered until .uncork() call
  10008. this.corked = 0;
  10009. // a flag to be able to tell if the onwrite cb is called immediately,
  10010. // or on a later tick. We set this to true at first, because any
  10011. // actions that shouldn't happen until "later" should generally also
  10012. // not happen before the first write call.
  10013. this.sync = true;
  10014. // a flag to know if we're processing previously buffered items, which
  10015. // may call the _write() callback in the same tick, so that we don't
  10016. // end up in an overlapped onwrite situation.
  10017. this.bufferProcessing = false;
  10018. // the callback that's passed to _write(chunk,cb)
  10019. this.onwrite = function (er) {
  10020. onwrite(stream, er);
  10021. };
  10022. // the callback that the user supplies to write(chunk,encoding,cb)
  10023. this.writecb = null;
  10024. // the amount that is being written when _write is called.
  10025. this.writelen = 0;
  10026. this.bufferedRequest = null;
  10027. this.lastBufferedRequest = null;
  10028. // number of pending user-supplied write callbacks
  10029. // this must be 0 before 'finish' can be emitted
  10030. this.pendingcb = 0;
  10031. // emit prefinish if the only thing we're waiting for is _write cbs
  10032. // This is relevant for synchronous Transform streams
  10033. this.prefinished = false;
  10034. // True if the error was already emitted and should not be thrown again
  10035. this.errorEmitted = false;
  10036. // count buffered requests
  10037. this.bufferedRequestCount = 0;
  10038. // allocate the first CorkedRequest, there is always
  10039. // one allocated and free to use, and we maintain at most two
  10040. this.corkedRequestsFree = new CorkedRequest(this);
  10041. }
  10042. WritableState.prototype.getBuffer = function getBuffer() {
  10043. var current = this.bufferedRequest;
  10044. var out = [];
  10045. while (current) {
  10046. out.push(current);
  10047. current = current.next;
  10048. }
  10049. return out;
  10050. };
  10051. (function () {
  10052. try {
  10053. Object.defineProperty(WritableState.prototype, 'buffer', {
  10054. get: internalUtil.deprecate(function () {
  10055. return this.getBuffer();
  10056. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  10057. });
  10058. } catch (_) {}
  10059. })();
  10060. // Test _writableState for inheritance to account for Duplex streams,
  10061. // whose prototype chain only points to Readable.
  10062. var realHasInstance;
  10063. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  10064. realHasInstance = Function.prototype[Symbol.hasInstance];
  10065. Object.defineProperty(Writable, Symbol.hasInstance, {
  10066. value: function (object) {
  10067. if (realHasInstance.call(this, object)) return true;
  10068. if (this !== Writable) return false;
  10069. return object && object._writableState instanceof WritableState;
  10070. }
  10071. });
  10072. } else {
  10073. realHasInstance = function (object) {
  10074. return object instanceof this;
  10075. };
  10076. }
  10077. function Writable(options) {
  10078. Duplex = Duplex || require('./_stream_duplex');
  10079. // Writable ctor is applied to Duplexes, too.
  10080. // `realHasInstance` is necessary because using plain `instanceof`
  10081. // would return false, as no `_writableState` property is attached.
  10082. // Trying to use the custom `instanceof` for Writable here will also break the
  10083. // Node.js LazyTransform implementation, which has a non-trivial getter for
  10084. // `_writableState` that would lead to infinite recursion.
  10085. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  10086. return new Writable(options);
  10087. }
  10088. this._writableState = new WritableState(options, this);
  10089. // legacy.
  10090. this.writable = true;
  10091. if (options) {
  10092. if (typeof options.write === 'function') this._write = options.write;
  10093. if (typeof options.writev === 'function') this._writev = options.writev;
  10094. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  10095. if (typeof options.final === 'function') this._final = options.final;
  10096. }
  10097. Stream.call(this);
  10098. }
  10099. // Otherwise people can pipe Writable streams, which is just wrong.
  10100. Writable.prototype.pipe = function () {
  10101. this.emit('error', new Error('Cannot pipe, not readable'));
  10102. };
  10103. function writeAfterEnd(stream, cb) {
  10104. var er = new Error('write after end');
  10105. // TODO: defer error events consistently everywhere, not just the cb
  10106. stream.emit('error', er);
  10107. pna.nextTick(cb, er);
  10108. }
  10109. // Checks that a user-supplied chunk is valid, especially for the particular
  10110. // mode the stream is in. Currently this means that `null` is never accepted
  10111. // and undefined/non-string values are only allowed in object mode.
  10112. function validChunk(stream, state, chunk, cb) {
  10113. var valid = true;
  10114. var er = false;
  10115. if (chunk === null) {
  10116. er = new TypeError('May not write null values to stream');
  10117. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  10118. er = new TypeError('Invalid non-string/buffer chunk');
  10119. }
  10120. if (er) {
  10121. stream.emit('error', er);
  10122. pna.nextTick(cb, er);
  10123. valid = false;
  10124. }
  10125. return valid;
  10126. }
  10127. Writable.prototype.write = function (chunk, encoding, cb) {
  10128. var state = this._writableState;
  10129. var ret = false;
  10130. var isBuf = !state.objectMode && _isUint8Array(chunk);
  10131. if (isBuf && !Buffer.isBuffer(chunk)) {
  10132. chunk = _uint8ArrayToBuffer(chunk);
  10133. }
  10134. if (typeof encoding === 'function') {
  10135. cb = encoding;
  10136. encoding = null;
  10137. }
  10138. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  10139. if (typeof cb !== 'function') cb = nop;
  10140. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  10141. state.pendingcb++;
  10142. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  10143. }
  10144. return ret;
  10145. };
  10146. Writable.prototype.cork = function () {
  10147. var state = this._writableState;
  10148. state.corked++;
  10149. };
  10150. Writable.prototype.uncork = function () {
  10151. var state = this._writableState;
  10152. if (state.corked) {
  10153. state.corked--;
  10154. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  10155. }
  10156. };
  10157. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  10158. // node::ParseEncoding() requires lower case.
  10159. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  10160. 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);
  10161. this._writableState.defaultEncoding = encoding;
  10162. return this;
  10163. };
  10164. function decodeChunk(state, chunk, encoding) {
  10165. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  10166. chunk = Buffer.from(chunk, encoding);
  10167. }
  10168. return chunk;
  10169. }
  10170. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  10171. // making it explicit this property is not enumerable
  10172. // because otherwise some prototype manipulation in
  10173. // userland will fail
  10174. enumerable: false,
  10175. get: function () {
  10176. return this._writableState.highWaterMark;
  10177. }
  10178. });
  10179. // if we're already writing something, then just put this
  10180. // in the queue, and wait our turn. Otherwise, call _write
  10181. // If we return false, then we need a drain event, so set that flag.
  10182. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  10183. if (!isBuf) {
  10184. var newChunk = decodeChunk(state, chunk, encoding);
  10185. if (chunk !== newChunk) {
  10186. isBuf = true;
  10187. encoding = 'buffer';
  10188. chunk = newChunk;
  10189. }
  10190. }
  10191. var len = state.objectMode ? 1 : chunk.length;
  10192. state.length += len;
  10193. var ret = state.length < state.highWaterMark;
  10194. // we must ensure that previous needDrain will not be reset to false.
  10195. if (!ret) state.needDrain = true;
  10196. if (state.writing || state.corked) {
  10197. var last = state.lastBufferedRequest;
  10198. state.lastBufferedRequest = {
  10199. chunk: chunk,
  10200. encoding: encoding,
  10201. isBuf: isBuf,
  10202. callback: cb,
  10203. next: null
  10204. };
  10205. if (last) {
  10206. last.next = state.lastBufferedRequest;
  10207. } else {
  10208. state.bufferedRequest = state.lastBufferedRequest;
  10209. }
  10210. state.bufferedRequestCount += 1;
  10211. } else {
  10212. doWrite(stream, state, false, len, chunk, encoding, cb);
  10213. }
  10214. return ret;
  10215. }
  10216. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  10217. state.writelen = len;
  10218. state.writecb = cb;
  10219. state.writing = true;
  10220. state.sync = true;
  10221. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  10222. state.sync = false;
  10223. }
  10224. function onwriteError(stream, state, sync, er, cb) {
  10225. --state.pendingcb;
  10226. if (sync) {
  10227. // defer the callback if we are being called synchronously
  10228. // to avoid piling up things on the stack
  10229. pna.nextTick(cb, er);
  10230. // this can emit finish, and it will always happen
  10231. // after error
  10232. pna.nextTick(finishMaybe, stream, state);
  10233. stream._writableState.errorEmitted = true;
  10234. stream.emit('error', er);
  10235. } else {
  10236. // the caller expect this to happen before if
  10237. // it is async
  10238. cb(er);
  10239. stream._writableState.errorEmitted = true;
  10240. stream.emit('error', er);
  10241. // this can emit finish, but finish must
  10242. // always follow error
  10243. finishMaybe(stream, state);
  10244. }
  10245. }
  10246. function onwriteStateUpdate(state) {
  10247. state.writing = false;
  10248. state.writecb = null;
  10249. state.length -= state.writelen;
  10250. state.writelen = 0;
  10251. }
  10252. function onwrite(stream, er) {
  10253. var state = stream._writableState;
  10254. var sync = state.sync;
  10255. var cb = state.writecb;
  10256. onwriteStateUpdate(state);
  10257. if (er) onwriteError(stream, state, sync, er, cb);else {
  10258. // Check if we're actually ready to finish, but don't emit yet
  10259. var finished = needFinish(state);
  10260. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  10261. clearBuffer(stream, state);
  10262. }
  10263. if (sync) {
  10264. /*<replacement>*/
  10265. asyncWrite(afterWrite, stream, state, finished, cb);
  10266. /*</replacement>*/
  10267. } else {
  10268. afterWrite(stream, state, finished, cb);
  10269. }
  10270. }
  10271. }
  10272. function afterWrite(stream, state, finished, cb) {
  10273. if (!finished) onwriteDrain(stream, state);
  10274. state.pendingcb--;
  10275. cb();
  10276. finishMaybe(stream, state);
  10277. }
  10278. // Must force callback to be called on nextTick, so that we don't
  10279. // emit 'drain' before the write() consumer gets the 'false' return
  10280. // value, and has a chance to attach a 'drain' listener.
  10281. function onwriteDrain(stream, state) {
  10282. if (state.length === 0 && state.needDrain) {
  10283. state.needDrain = false;
  10284. stream.emit('drain');
  10285. }
  10286. }
  10287. // if there's something in the buffer waiting, then process it
  10288. function clearBuffer(stream, state) {
  10289. state.bufferProcessing = true;
  10290. var entry = state.bufferedRequest;
  10291. if (stream._writev && entry && entry.next) {
  10292. // Fast case, write everything using _writev()
  10293. var l = state.bufferedRequestCount;
  10294. var buffer = new Array(l);
  10295. var holder = state.corkedRequestsFree;
  10296. holder.entry = entry;
  10297. var count = 0;
  10298. var allBuffers = true;
  10299. while (entry) {
  10300. buffer[count] = entry;
  10301. if (!entry.isBuf) allBuffers = false;
  10302. entry = entry.next;
  10303. count += 1;
  10304. }
  10305. buffer.allBuffers = allBuffers;
  10306. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  10307. // doWrite is almost always async, defer these to save a bit of time
  10308. // as the hot path ends with doWrite
  10309. state.pendingcb++;
  10310. state.lastBufferedRequest = null;
  10311. if (holder.next) {
  10312. state.corkedRequestsFree = holder.next;
  10313. holder.next = null;
  10314. } else {
  10315. state.corkedRequestsFree = new CorkedRequest(state);
  10316. }
  10317. state.bufferedRequestCount = 0;
  10318. } else {
  10319. // Slow case, write chunks one-by-one
  10320. while (entry) {
  10321. var chunk = entry.chunk;
  10322. var encoding = entry.encoding;
  10323. var cb = entry.callback;
  10324. var len = state.objectMode ? 1 : chunk.length;
  10325. doWrite(stream, state, false, len, chunk, encoding, cb);
  10326. entry = entry.next;
  10327. state.bufferedRequestCount--;
  10328. // if we didn't call the onwrite immediately, then
  10329. // it means that we need to wait until it does.
  10330. // also, that means that the chunk and cb are currently
  10331. // being processed, so move the buffer counter past them.
  10332. if (state.writing) {
  10333. break;
  10334. }
  10335. }
  10336. if (entry === null) state.lastBufferedRequest = null;
  10337. }
  10338. state.bufferedRequest = entry;
  10339. state.bufferProcessing = false;
  10340. }
  10341. Writable.prototype._write = function (chunk, encoding, cb) {
  10342. cb(new Error('_write() is not implemented'));
  10343. };
  10344. Writable.prototype._writev = null;
  10345. Writable.prototype.end = function (chunk, encoding, cb) {
  10346. var state = this._writableState;
  10347. if (typeof chunk === 'function') {
  10348. cb = chunk;
  10349. chunk = null;
  10350. encoding = null;
  10351. } else if (typeof encoding === 'function') {
  10352. cb = encoding;
  10353. encoding = null;
  10354. }
  10355. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  10356. // .end() fully uncorks
  10357. if (state.corked) {
  10358. state.corked = 1;
  10359. this.uncork();
  10360. }
  10361. // ignore unnecessary end() calls.
  10362. if (!state.ending && !state.finished) endWritable(this, state, cb);
  10363. };
  10364. function needFinish(state) {
  10365. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  10366. }
  10367. function callFinal(stream, state) {
  10368. stream._final(function (err) {
  10369. state.pendingcb--;
  10370. if (err) {
  10371. stream.emit('error', err);
  10372. }
  10373. state.prefinished = true;
  10374. stream.emit('prefinish');
  10375. finishMaybe(stream, state);
  10376. });
  10377. }
  10378. function prefinish(stream, state) {
  10379. if (!state.prefinished && !state.finalCalled) {
  10380. if (typeof stream._final === 'function') {
  10381. state.pendingcb++;
  10382. state.finalCalled = true;
  10383. pna.nextTick(callFinal, stream, state);
  10384. } else {
  10385. state.prefinished = true;
  10386. stream.emit('prefinish');
  10387. }
  10388. }
  10389. }
  10390. function finishMaybe(stream, state) {
  10391. var need = needFinish(state);
  10392. if (need) {
  10393. prefinish(stream, state);
  10394. if (state.pendingcb === 0) {
  10395. state.finished = true;
  10396. stream.emit('finish');
  10397. }
  10398. }
  10399. return need;
  10400. }
  10401. function endWritable(stream, state, cb) {
  10402. state.ending = true;
  10403. finishMaybe(stream, state);
  10404. if (cb) {
  10405. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  10406. }
  10407. state.ended = true;
  10408. stream.writable = false;
  10409. }
  10410. function onCorkedFinish(corkReq, state, err) {
  10411. var entry = corkReq.entry;
  10412. corkReq.entry = null;
  10413. while (entry) {
  10414. var cb = entry.callback;
  10415. state.pendingcb--;
  10416. cb(err);
  10417. entry = entry.next;
  10418. }
  10419. if (state.corkedRequestsFree) {
  10420. state.corkedRequestsFree.next = corkReq;
  10421. } else {
  10422. state.corkedRequestsFree = corkReq;
  10423. }
  10424. }
  10425. Object.defineProperty(Writable.prototype, 'destroyed', {
  10426. get: function () {
  10427. if (this._writableState === undefined) {
  10428. return false;
  10429. }
  10430. return this._writableState.destroyed;
  10431. },
  10432. set: function (value) {
  10433. // we ignore the value if the stream
  10434. // has not been initialized yet
  10435. if (!this._writableState) {
  10436. return;
  10437. }
  10438. // backward compatibility, the user is explicitly
  10439. // managing destroyed
  10440. this._writableState.destroyed = value;
  10441. }
  10442. });
  10443. Writable.prototype.destroy = destroyImpl.destroy;
  10444. Writable.prototype._undestroy = destroyImpl.undestroy;
  10445. Writable.prototype._destroy = function (err, cb) {
  10446. this.end();
  10447. cb(err);
  10448. };
  10449. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  10450. },{"./_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){
  10451. 'use strict';
  10452. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10453. var Buffer = require('safe-buffer').Buffer;
  10454. var util = require('util');
  10455. function copyBuffer(src, target, offset) {
  10456. src.copy(target, offset);
  10457. }
  10458. module.exports = function () {
  10459. function BufferList() {
  10460. _classCallCheck(this, BufferList);
  10461. this.head = null;
  10462. this.tail = null;
  10463. this.length = 0;
  10464. }
  10465. BufferList.prototype.push = function push(v) {
  10466. var entry = { data: v, next: null };
  10467. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  10468. this.tail = entry;
  10469. ++this.length;
  10470. };
  10471. BufferList.prototype.unshift = function unshift(v) {
  10472. var entry = { data: v, next: this.head };
  10473. if (this.length === 0) this.tail = entry;
  10474. this.head = entry;
  10475. ++this.length;
  10476. };
  10477. BufferList.prototype.shift = function shift() {
  10478. if (this.length === 0) return;
  10479. var ret = this.head.data;
  10480. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  10481. --this.length;
  10482. return ret;
  10483. };
  10484. BufferList.prototype.clear = function clear() {
  10485. this.head = this.tail = null;
  10486. this.length = 0;
  10487. };
  10488. BufferList.prototype.join = function join(s) {
  10489. if (this.length === 0) return '';
  10490. var p = this.head;
  10491. var ret = '' + p.data;
  10492. while (p = p.next) {
  10493. ret += s + p.data;
  10494. }return ret;
  10495. };
  10496. BufferList.prototype.concat = function concat(n) {
  10497. if (this.length === 0) return Buffer.alloc(0);
  10498. if (this.length === 1) return this.head.data;
  10499. var ret = Buffer.allocUnsafe(n >>> 0);
  10500. var p = this.head;
  10501. var i = 0;
  10502. while (p) {
  10503. copyBuffer(p.data, ret, i);
  10504. i += p.data.length;
  10505. p = p.next;
  10506. }
  10507. return ret;
  10508. };
  10509. return BufferList;
  10510. }();
  10511. if (util && util.inspect && util.inspect.custom) {
  10512. module.exports.prototype[util.inspect.custom] = function () {
  10513. var obj = util.inspect({ length: this.length });
  10514. return this.constructor.name + ' ' + obj;
  10515. };
  10516. }
  10517. },{"safe-buffer":110,"util":11}],104:[function(require,module,exports){
  10518. 'use strict';
  10519. /*<replacement>*/
  10520. var pna = require('process-nextick-args');
  10521. /*</replacement>*/
  10522. // undocumented cb() API, needed for core, not for public API
  10523. function destroy(err, cb) {
  10524. var _this = this;
  10525. var readableDestroyed = this._readableState && this._readableState.destroyed;
  10526. var writableDestroyed = this._writableState && this._writableState.destroyed;
  10527. if (readableDestroyed || writableDestroyed) {
  10528. if (cb) {
  10529. cb(err);
  10530. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  10531. pna.nextTick(emitErrorNT, this, err);
  10532. }
  10533. return this;
  10534. }
  10535. // we set destroyed to true before firing error callbacks in order
  10536. // to make it re-entrance safe in case destroy() is called within callbacks
  10537. if (this._readableState) {
  10538. this._readableState.destroyed = true;
  10539. }
  10540. // if this is a duplex stream mark the writable part as destroyed as well
  10541. if (this._writableState) {
  10542. this._writableState.destroyed = true;
  10543. }
  10544. this._destroy(err || null, function (err) {
  10545. if (!cb && err) {
  10546. pna.nextTick(emitErrorNT, _this, err);
  10547. if (_this._writableState) {
  10548. _this._writableState.errorEmitted = true;
  10549. }
  10550. } else if (cb) {
  10551. cb(err);
  10552. }
  10553. });
  10554. return this;
  10555. }
  10556. function undestroy() {
  10557. if (this._readableState) {
  10558. this._readableState.destroyed = false;
  10559. this._readableState.reading = false;
  10560. this._readableState.ended = false;
  10561. this._readableState.endEmitted = false;
  10562. }
  10563. if (this._writableState) {
  10564. this._writableState.destroyed = false;
  10565. this._writableState.ended = false;
  10566. this._writableState.ending = false;
  10567. this._writableState.finished = false;
  10568. this._writableState.errorEmitted = false;
  10569. }
  10570. }
  10571. function emitErrorNT(self, err) {
  10572. self.emit('error', err);
  10573. }
  10574. module.exports = {
  10575. destroy: destroy,
  10576. undestroy: undestroy
  10577. };
  10578. },{"process-nextick-args":91}],105:[function(require,module,exports){
  10579. module.exports = require('events').EventEmitter;
  10580. },{"events":13}],106:[function(require,module,exports){
  10581. var toString = {}.toString;
  10582. module.exports = Array.isArray || function (arr) {
  10583. return toString.call(arr) == '[object Array]';
  10584. };
  10585. },{}],107:[function(require,module,exports){
  10586. // Copyright Joyent, Inc. and other Node contributors.
  10587. //
  10588. // Permission is hereby granted, free of charge, to any person obtaining a
  10589. // copy of this software and associated documentation files (the
  10590. // "Software"), to deal in the Software without restriction, including
  10591. // without limitation the rights to use, copy, modify, merge, publish,
  10592. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10593. // persons to whom the Software is furnished to do so, subject to the
  10594. // following conditions:
  10595. //
  10596. // The above copyright notice and this permission notice shall be included
  10597. // in all copies or substantial portions of the Software.
  10598. //
  10599. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10600. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10601. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10602. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10603. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10604. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10605. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10606. 'use strict';
  10607. /*<replacement>*/
  10608. var Buffer = require('safe-buffer').Buffer;
  10609. /*</replacement>*/
  10610. var isEncoding = Buffer.isEncoding || function (encoding) {
  10611. encoding = '' + encoding;
  10612. switch (encoding && encoding.toLowerCase()) {
  10613. 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':
  10614. return true;
  10615. default:
  10616. return false;
  10617. }
  10618. };
  10619. function _normalizeEncoding(enc) {
  10620. if (!enc) return 'utf8';
  10621. var retried;
  10622. while (true) {
  10623. switch (enc) {
  10624. case 'utf8':
  10625. case 'utf-8':
  10626. return 'utf8';
  10627. case 'ucs2':
  10628. case 'ucs-2':
  10629. case 'utf16le':
  10630. case 'utf-16le':
  10631. return 'utf16le';
  10632. case 'latin1':
  10633. case 'binary':
  10634. return 'latin1';
  10635. case 'base64':
  10636. case 'ascii':
  10637. case 'hex':
  10638. return enc;
  10639. default:
  10640. if (retried) return; // undefined
  10641. enc = ('' + enc).toLowerCase();
  10642. retried = true;
  10643. }
  10644. }
  10645. };
  10646. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  10647. // modules monkey-patch it to support additional encodings
  10648. function normalizeEncoding(enc) {
  10649. var nenc = _normalizeEncoding(enc);
  10650. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  10651. return nenc || enc;
  10652. }
  10653. // StringDecoder provides an interface for efficiently splitting a series of
  10654. // buffers into a series of JS strings without breaking apart multi-byte
  10655. // characters.
  10656. exports.StringDecoder = StringDecoder;
  10657. function StringDecoder(encoding) {
  10658. this.encoding = normalizeEncoding(encoding);
  10659. var nb;
  10660. switch (this.encoding) {
  10661. case 'utf16le':
  10662. this.text = utf16Text;
  10663. this.end = utf16End;
  10664. nb = 4;
  10665. break;
  10666. case 'utf8':
  10667. this.fillLast = utf8FillLast;
  10668. nb = 4;
  10669. break;
  10670. case 'base64':
  10671. this.text = base64Text;
  10672. this.end = base64End;
  10673. nb = 3;
  10674. break;
  10675. default:
  10676. this.write = simpleWrite;
  10677. this.end = simpleEnd;
  10678. return;
  10679. }
  10680. this.lastNeed = 0;
  10681. this.lastTotal = 0;
  10682. this.lastChar = Buffer.allocUnsafe(nb);
  10683. }
  10684. StringDecoder.prototype.write = function (buf) {
  10685. if (buf.length === 0) return '';
  10686. var r;
  10687. var i;
  10688. if (this.lastNeed) {
  10689. r = this.fillLast(buf);
  10690. if (r === undefined) return '';
  10691. i = this.lastNeed;
  10692. this.lastNeed = 0;
  10693. } else {
  10694. i = 0;
  10695. }
  10696. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  10697. return r || '';
  10698. };
  10699. StringDecoder.prototype.end = utf8End;
  10700. // Returns only complete characters in a Buffer
  10701. StringDecoder.prototype.text = utf8Text;
  10702. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  10703. StringDecoder.prototype.fillLast = function (buf) {
  10704. if (this.lastNeed <= buf.length) {
  10705. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  10706. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10707. }
  10708. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  10709. this.lastNeed -= buf.length;
  10710. };
  10711. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  10712. // continuation byte. If an invalid byte is detected, -2 is returned.
  10713. function utf8CheckByte(byte) {
  10714. 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;
  10715. return byte >> 6 === 0x02 ? -1 : -2;
  10716. }
  10717. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  10718. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  10719. // needed to complete the UTF-8 character (if applicable) are returned.
  10720. function utf8CheckIncomplete(self, buf, i) {
  10721. var j = buf.length - 1;
  10722. if (j < i) return 0;
  10723. var nb = utf8CheckByte(buf[j]);
  10724. if (nb >= 0) {
  10725. if (nb > 0) self.lastNeed = nb - 1;
  10726. return nb;
  10727. }
  10728. if (--j < i || nb === -2) return 0;
  10729. nb = utf8CheckByte(buf[j]);
  10730. if (nb >= 0) {
  10731. if (nb > 0) self.lastNeed = nb - 2;
  10732. return nb;
  10733. }
  10734. if (--j < i || nb === -2) return 0;
  10735. nb = utf8CheckByte(buf[j]);
  10736. if (nb >= 0) {
  10737. if (nb > 0) {
  10738. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  10739. }
  10740. return nb;
  10741. }
  10742. return 0;
  10743. }
  10744. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  10745. // needed or are available. If we see a non-continuation byte where we expect
  10746. // one, we "replace" the validated continuation bytes we've seen so far with
  10747. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  10748. // behavior. The continuation byte check is included three times in the case
  10749. // where all of the continuation bytes for a character exist in the same buffer.
  10750. // It is also done this way as a slight performance increase instead of using a
  10751. // loop.
  10752. function utf8CheckExtraBytes(self, buf, p) {
  10753. if ((buf[0] & 0xC0) !== 0x80) {
  10754. self.lastNeed = 0;
  10755. return '\ufffd';
  10756. }
  10757. if (self.lastNeed > 1 && buf.length > 1) {
  10758. if ((buf[1] & 0xC0) !== 0x80) {
  10759. self.lastNeed = 1;
  10760. return '\ufffd';
  10761. }
  10762. if (self.lastNeed > 2 && buf.length > 2) {
  10763. if ((buf[2] & 0xC0) !== 0x80) {
  10764. self.lastNeed = 2;
  10765. return '\ufffd';
  10766. }
  10767. }
  10768. }
  10769. }
  10770. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  10771. function utf8FillLast(buf) {
  10772. var p = this.lastTotal - this.lastNeed;
  10773. var r = utf8CheckExtraBytes(this, buf, p);
  10774. if (r !== undefined) return r;
  10775. if (this.lastNeed <= buf.length) {
  10776. buf.copy(this.lastChar, p, 0, this.lastNeed);
  10777. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10778. }
  10779. buf.copy(this.lastChar, p, 0, buf.length);
  10780. this.lastNeed -= buf.length;
  10781. }
  10782. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  10783. // partial character, the character's bytes are buffered until the required
  10784. // number of bytes are available.
  10785. function utf8Text(buf, i) {
  10786. var total = utf8CheckIncomplete(this, buf, i);
  10787. if (!this.lastNeed) return buf.toString('utf8', i);
  10788. this.lastTotal = total;
  10789. var end = buf.length - (total - this.lastNeed);
  10790. buf.copy(this.lastChar, 0, end);
  10791. return buf.toString('utf8', i, end);
  10792. }
  10793. // For UTF-8, a replacement character is added when ending on a partial
  10794. // character.
  10795. function utf8End(buf) {
  10796. var r = buf && buf.length ? this.write(buf) : '';
  10797. if (this.lastNeed) return r + '\ufffd';
  10798. return r;
  10799. }
  10800. // UTF-16LE typically needs two bytes per character, but even if we have an even
  10801. // number of bytes available, we need to check if we end on a leading/high
  10802. // surrogate. In that case, we need to wait for the next two bytes in order to
  10803. // decode the last character properly.
  10804. function utf16Text(buf, i) {
  10805. if ((buf.length - i) % 2 === 0) {
  10806. var r = buf.toString('utf16le', i);
  10807. if (r) {
  10808. var c = r.charCodeAt(r.length - 1);
  10809. if (c >= 0xD800 && c <= 0xDBFF) {
  10810. this.lastNeed = 2;
  10811. this.lastTotal = 4;
  10812. this.lastChar[0] = buf[buf.length - 2];
  10813. this.lastChar[1] = buf[buf.length - 1];
  10814. return r.slice(0, -1);
  10815. }
  10816. }
  10817. return r;
  10818. }
  10819. this.lastNeed = 1;
  10820. this.lastTotal = 2;
  10821. this.lastChar[0] = buf[buf.length - 1];
  10822. return buf.toString('utf16le', i, buf.length - 1);
  10823. }
  10824. // For UTF-16LE we do not explicitly append special replacement characters if we
  10825. // end on a partial character, we simply let v8 handle that.
  10826. function utf16End(buf) {
  10827. var r = buf && buf.length ? this.write(buf) : '';
  10828. if (this.lastNeed) {
  10829. var end = this.lastTotal - this.lastNeed;
  10830. return r + this.lastChar.toString('utf16le', 0, end);
  10831. }
  10832. return r;
  10833. }
  10834. function base64Text(buf, i) {
  10835. var n = (buf.length - i) % 3;
  10836. if (n === 0) return buf.toString('base64', i);
  10837. this.lastNeed = 3 - n;
  10838. this.lastTotal = 3;
  10839. if (n === 1) {
  10840. this.lastChar[0] = buf[buf.length - 1];
  10841. } else {
  10842. this.lastChar[0] = buf[buf.length - 2];
  10843. this.lastChar[1] = buf[buf.length - 1];
  10844. }
  10845. return buf.toString('base64', i, buf.length - n);
  10846. }
  10847. function base64End(buf) {
  10848. var r = buf && buf.length ? this.write(buf) : '';
  10849. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  10850. return r;
  10851. }
  10852. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  10853. function simpleWrite(buf) {
  10854. return buf.toString(this.encoding);
  10855. }
  10856. function simpleEnd(buf) {
  10857. return buf && buf.length ? this.write(buf) : '';
  10858. }
  10859. },{"safe-buffer":110}],108:[function(require,module,exports){
  10860. exports = module.exports = require('./lib/_stream_readable.js');
  10861. exports.Stream = exports;
  10862. exports.Readable = exports;
  10863. exports.Writable = require('./lib/_stream_writable.js');
  10864. exports.Duplex = require('./lib/_stream_duplex.js');
  10865. exports.Transform = require('./lib/_stream_transform.js');
  10866. exports.PassThrough = require('./lib/_stream_passthrough.js');
  10867. },{"./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){
  10868. 'use strict'
  10869. function ReInterval (callback, interval, args) {
  10870. var self = this;
  10871. this._callback = callback;
  10872. this._args = args;
  10873. this._interval = setInterval(callback, interval, this._args);
  10874. this.reschedule = function (interval) {
  10875. // if no interval entered, use the interval passed in on creation
  10876. if (!interval)
  10877. interval = self._interval;
  10878. if (self._interval)
  10879. clearInterval(self._interval);
  10880. self._interval = setInterval(self._callback, interval, self._args);
  10881. };
  10882. this.clear = function () {
  10883. if (self._interval) {
  10884. clearInterval(self._interval);
  10885. self._interval = undefined;
  10886. }
  10887. };
  10888. this.destroy = function () {
  10889. if (self._interval) {
  10890. clearInterval(self._interval);
  10891. }
  10892. self._callback = undefined;
  10893. self._interval = undefined;
  10894. self._args = undefined;
  10895. };
  10896. }
  10897. function reInterval () {
  10898. if (typeof arguments[0] !== 'function')
  10899. throw new Error('callback needed');
  10900. if (typeof arguments[1] !== 'number')
  10901. throw new Error('interval needed');
  10902. var args;
  10903. if (arguments.length > 0) {
  10904. args = new Array(arguments.length - 2);
  10905. for (var i = 0; i < args.length; i++) {
  10906. args[i] = arguments[i + 2];
  10907. }
  10908. }
  10909. return new ReInterval(arguments[0], arguments[1], args);
  10910. }
  10911. module.exports = reInterval;
  10912. },{}],110:[function(require,module,exports){
  10913. /* eslint-disable node/no-deprecated-api */
  10914. var buffer = require('buffer')
  10915. var Buffer = buffer.Buffer
  10916. // alternative to using Object.keys for old browsers
  10917. function copyProps (src, dst) {
  10918. for (var key in src) {
  10919. dst[key] = src[key]
  10920. }
  10921. }
  10922. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  10923. module.exports = buffer
  10924. } else {
  10925. // Copy properties from require('buffer')
  10926. copyProps(buffer, exports)
  10927. exports.Buffer = SafeBuffer
  10928. }
  10929. function SafeBuffer (arg, encodingOrOffset, length) {
  10930. return Buffer(arg, encodingOrOffset, length)
  10931. }
  10932. // Copy static methods from Buffer
  10933. copyProps(Buffer, SafeBuffer)
  10934. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  10935. if (typeof arg === 'number') {
  10936. throw new TypeError('Argument must not be a number')
  10937. }
  10938. return Buffer(arg, encodingOrOffset, length)
  10939. }
  10940. SafeBuffer.alloc = function (size, fill, encoding) {
  10941. if (typeof size !== 'number') {
  10942. throw new TypeError('Argument must be a number')
  10943. }
  10944. var buf = Buffer(size)
  10945. if (fill !== undefined) {
  10946. if (typeof encoding === 'string') {
  10947. buf.fill(fill, encoding)
  10948. } else {
  10949. buf.fill(fill)
  10950. }
  10951. } else {
  10952. buf.fill(0)
  10953. }
  10954. return buf
  10955. }
  10956. SafeBuffer.allocUnsafe = function (size) {
  10957. if (typeof size !== 'number') {
  10958. throw new TypeError('Argument must be a number')
  10959. }
  10960. return Buffer(size)
  10961. }
  10962. SafeBuffer.allocUnsafeSlow = function (size) {
  10963. if (typeof size !== 'number') {
  10964. throw new TypeError('Argument must be a number')
  10965. }
  10966. return buffer.SlowBuffer(size)
  10967. }
  10968. },{"buffer":12}],111:[function(require,module,exports){
  10969. module.exports = shift
  10970. function shift (stream) {
  10971. var rs = stream._readableState
  10972. if (!rs) return null
  10973. return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
  10974. }
  10975. function getStateLength (state) {
  10976. if (state.buffer.length) {
  10977. // Since node 6.3.0 state.buffer is a BufferList not an array
  10978. if (state.buffer.head) {
  10979. return state.buffer.head.data.length
  10980. }
  10981. return state.buffer[0].length
  10982. }
  10983. return state.length
  10984. }
  10985. },{}],112:[function(require,module,exports){
  10986. (function (setImmediate,clearImmediate){
  10987. var nextTick = require('process/browser.js').nextTick;
  10988. var apply = Function.prototype.apply;
  10989. var slice = Array.prototype.slice;
  10990. var immediateIds = {};
  10991. var nextImmediateId = 0;
  10992. // DOM APIs, for completeness
  10993. exports.setTimeout = function() {
  10994. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  10995. };
  10996. exports.setInterval = function() {
  10997. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  10998. };
  10999. exports.clearTimeout =
  11000. exports.clearInterval = function(timeout) { timeout.close(); };
  11001. function Timeout(id, clearFn) {
  11002. this._id = id;
  11003. this._clearFn = clearFn;
  11004. }
  11005. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  11006. Timeout.prototype.close = function() {
  11007. this._clearFn.call(window, this._id);
  11008. };
  11009. // Does not start the time, just sets up the members needed.
  11010. exports.enroll = function(item, msecs) {
  11011. clearTimeout(item._idleTimeoutId);
  11012. item._idleTimeout = msecs;
  11013. };
  11014. exports.unenroll = function(item) {
  11015. clearTimeout(item._idleTimeoutId);
  11016. item._idleTimeout = -1;
  11017. };
  11018. exports._unrefActive = exports.active = function(item) {
  11019. clearTimeout(item._idleTimeoutId);
  11020. var msecs = item._idleTimeout;
  11021. if (msecs >= 0) {
  11022. item._idleTimeoutId = setTimeout(function onTimeout() {
  11023. if (item._onTimeout)
  11024. item._onTimeout();
  11025. }, msecs);
  11026. }
  11027. };
  11028. // That's not how node.js implements it but the exposed api is the same.
  11029. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  11030. var id = nextImmediateId++;
  11031. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  11032. immediateIds[id] = true;
  11033. nextTick(function onNextTick() {
  11034. if (immediateIds[id]) {
  11035. // fn.call() is faster so we optimize for the common use-case
  11036. // @see http://jsperf.com/call-apply-segu
  11037. if (args) {
  11038. fn.apply(null, args);
  11039. } else {
  11040. fn.call(null);
  11041. }
  11042. // Prevent ids from leaking
  11043. exports.clearImmediate(id);
  11044. }
  11045. });
  11046. return id;
  11047. };
  11048. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  11049. delete immediateIds[id];
  11050. };
  11051. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  11052. },{"process/browser.js":92,"timers":112}],113:[function(require,module,exports){
  11053. // Copyright Joyent, Inc. and other Node contributors.
  11054. //
  11055. // Permission is hereby granted, free of charge, to any person obtaining a
  11056. // copy of this software and associated documentation files (the
  11057. // "Software"), to deal in the Software without restriction, including
  11058. // without limitation the rights to use, copy, modify, merge, publish,
  11059. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11060. // persons to whom the Software is furnished to do so, subject to the
  11061. // following conditions:
  11062. //
  11063. // The above copyright notice and this permission notice shall be included
  11064. // in all copies or substantial portions of the Software.
  11065. //
  11066. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11067. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11068. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11069. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11070. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11071. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11072. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11073. 'use strict';
  11074. var punycode = require('punycode');
  11075. var util = require('./util');
  11076. exports.parse = urlParse;
  11077. exports.resolve = urlResolve;
  11078. exports.resolveObject = urlResolveObject;
  11079. exports.format = urlFormat;
  11080. exports.Url = Url;
  11081. function Url() {
  11082. this.protocol = null;
  11083. this.slashes = null;
  11084. this.auth = null;
  11085. this.host = null;
  11086. this.port = null;
  11087. this.hostname = null;
  11088. this.hash = null;
  11089. this.search = null;
  11090. this.query = null;
  11091. this.pathname = null;
  11092. this.path = null;
  11093. this.href = null;
  11094. }
  11095. // Reference: RFC 3986, RFC 1808, RFC 2396
  11096. // define these here so at least they only have to be
  11097. // compiled once on the first module load.
  11098. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  11099. portPattern = /:[0-9]*$/,
  11100. // Special case for a simple path URL
  11101. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  11102. // RFC 2396: characters reserved for delimiting URLs.
  11103. // We actually just auto-escape these.
  11104. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  11105. // RFC 2396: characters not allowed for various reasons.
  11106. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  11107. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  11108. autoEscape = ['\''].concat(unwise),
  11109. // Characters that are never ever allowed in a hostname.
  11110. // Note that any invalid chars are also handled, but these
  11111. // are the ones that are *expected* to be seen, so we fast-path
  11112. // them.
  11113. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  11114. hostEndingChars = ['/', '?', '#'],
  11115. hostnameMaxLen = 255,
  11116. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  11117. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  11118. // protocols that can allow "unsafe" and "unwise" chars.
  11119. unsafeProtocol = {
  11120. 'javascript': true,
  11121. 'javascript:': true
  11122. },
  11123. // protocols that never have a hostname.
  11124. hostlessProtocol = {
  11125. 'javascript': true,
  11126. 'javascript:': true
  11127. },
  11128. // protocols that always contain a // bit.
  11129. slashedProtocol = {
  11130. 'http': true,
  11131. 'https': true,
  11132. 'ftp': true,
  11133. 'gopher': true,
  11134. 'file': true,
  11135. 'http:': true,
  11136. 'https:': true,
  11137. 'ftp:': true,
  11138. 'gopher:': true,
  11139. 'file:': true
  11140. },
  11141. querystring = require('querystring');
  11142. function urlParse(url, parseQueryString, slashesDenoteHost) {
  11143. if (url && util.isObject(url) && url instanceof Url) return url;
  11144. var u = new Url;
  11145. u.parse(url, parseQueryString, slashesDenoteHost);
  11146. return u;
  11147. }
  11148. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  11149. if (!util.isString(url)) {
  11150. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  11151. }
  11152. // Copy chrome, IE, opera backslash-handling behavior.
  11153. // Back slashes before the query string get converted to forward slashes
  11154. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  11155. var queryIndex = url.indexOf('?'),
  11156. splitter =
  11157. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  11158. uSplit = url.split(splitter),
  11159. slashRegex = /\\/g;
  11160. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  11161. url = uSplit.join(splitter);
  11162. var rest = url;
  11163. // trim before proceeding.
  11164. // This is to support parse stuff like " http://foo.com \n"
  11165. rest = rest.trim();
  11166. if (!slashesDenoteHost && url.split('#').length === 1) {
  11167. // Try fast path regexp
  11168. var simplePath = simplePathPattern.exec(rest);
  11169. if (simplePath) {
  11170. this.path = rest;
  11171. this.href = rest;
  11172. this.pathname = simplePath[1];
  11173. if (simplePath[2]) {
  11174. this.search = simplePath[2];
  11175. if (parseQueryString) {
  11176. this.query = querystring.parse(this.search.substr(1));
  11177. } else {
  11178. this.query = this.search.substr(1);
  11179. }
  11180. } else if (parseQueryString) {
  11181. this.search = '';
  11182. this.query = {};
  11183. }
  11184. return this;
  11185. }
  11186. }
  11187. var proto = protocolPattern.exec(rest);
  11188. if (proto) {
  11189. proto = proto[0];
  11190. var lowerProto = proto.toLowerCase();
  11191. this.protocol = lowerProto;
  11192. rest = rest.substr(proto.length);
  11193. }
  11194. // figure out if it's got a host
  11195. // user@server is *always* interpreted as a hostname, and url
  11196. // resolution will treat //foo/bar as host=foo,path=bar because that's
  11197. // how the browser resolves relative URLs.
  11198. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  11199. var slashes = rest.substr(0, 2) === '//';
  11200. if (slashes && !(proto && hostlessProtocol[proto])) {
  11201. rest = rest.substr(2);
  11202. this.slashes = true;
  11203. }
  11204. }
  11205. if (!hostlessProtocol[proto] &&
  11206. (slashes || (proto && !slashedProtocol[proto]))) {
  11207. // there's a hostname.
  11208. // the first instance of /, ?, ;, or # ends the host.
  11209. //
  11210. // If there is an @ in the hostname, then non-host chars *are* allowed
  11211. // to the left of the last @ sign, unless some host-ending character
  11212. // comes *before* the @-sign.
  11213. // URLs are obnoxious.
  11214. //
  11215. // ex:
  11216. // http://a@b@c/ => user:a@b host:c
  11217. // http://a@b?@c => user:a host:c path:/?@c
  11218. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  11219. // Review our test case against browsers more comprehensively.
  11220. // find the first instance of any hostEndingChars
  11221. var hostEnd = -1;
  11222. for (var i = 0; i < hostEndingChars.length; i++) {
  11223. var hec = rest.indexOf(hostEndingChars[i]);
  11224. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  11225. hostEnd = hec;
  11226. }
  11227. // at this point, either we have an explicit point where the
  11228. // auth portion cannot go past, or the last @ char is the decider.
  11229. var auth, atSign;
  11230. if (hostEnd === -1) {
  11231. // atSign can be anywhere.
  11232. atSign = rest.lastIndexOf('@');
  11233. } else {
  11234. // atSign must be in auth portion.
  11235. // http://a@b/c@d => host:b auth:a path:/c@d
  11236. atSign = rest.lastIndexOf('@', hostEnd);
  11237. }
  11238. // Now we have a portion which is definitely the auth.
  11239. // Pull that off.
  11240. if (atSign !== -1) {
  11241. auth = rest.slice(0, atSign);
  11242. rest = rest.slice(atSign + 1);
  11243. this.auth = decodeURIComponent(auth);
  11244. }
  11245. // the host is the remaining to the left of the first non-host char
  11246. hostEnd = -1;
  11247. for (var i = 0; i < nonHostChars.length; i++) {
  11248. var hec = rest.indexOf(nonHostChars[i]);
  11249. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  11250. hostEnd = hec;
  11251. }
  11252. // if we still have not hit it, then the entire thing is a host.
  11253. if (hostEnd === -1)
  11254. hostEnd = rest.length;
  11255. this.host = rest.slice(0, hostEnd);
  11256. rest = rest.slice(hostEnd);
  11257. // pull out port.
  11258. this.parseHost();
  11259. // we've indicated that there is a hostname,
  11260. // so even if it's empty, it has to be present.
  11261. this.hostname = this.hostname || '';
  11262. // if hostname begins with [ and ends with ]
  11263. // assume that it's an IPv6 address.
  11264. var ipv6Hostname = this.hostname[0] === '[' &&
  11265. this.hostname[this.hostname.length - 1] === ']';
  11266. // validate a little.
  11267. if (!ipv6Hostname) {
  11268. var hostparts = this.hostname.split(/\./);
  11269. for (var i = 0, l = hostparts.length; i < l; i++) {
  11270. var part = hostparts[i];
  11271. if (!part) continue;
  11272. if (!part.match(hostnamePartPattern)) {
  11273. var newpart = '';
  11274. for (var j = 0, k = part.length; j < k; j++) {
  11275. if (part.charCodeAt(j) > 127) {
  11276. // we replace non-ASCII char with a temporary placeholder
  11277. // we need this to make sure size of hostname is not
  11278. // broken by replacing non-ASCII by nothing
  11279. newpart += 'x';
  11280. } else {
  11281. newpart += part[j];
  11282. }
  11283. }
  11284. // we test again with ASCII char only
  11285. if (!newpart.match(hostnamePartPattern)) {
  11286. var validParts = hostparts.slice(0, i);
  11287. var notHost = hostparts.slice(i + 1);
  11288. var bit = part.match(hostnamePartStart);
  11289. if (bit) {
  11290. validParts.push(bit[1]);
  11291. notHost.unshift(bit[2]);
  11292. }
  11293. if (notHost.length) {
  11294. rest = '/' + notHost.join('.') + rest;
  11295. }
  11296. this.hostname = validParts.join('.');
  11297. break;
  11298. }
  11299. }
  11300. }
  11301. }
  11302. if (this.hostname.length > hostnameMaxLen) {
  11303. this.hostname = '';
  11304. } else {
  11305. // hostnames are always lower case.
  11306. this.hostname = this.hostname.toLowerCase();
  11307. }
  11308. if (!ipv6Hostname) {
  11309. // IDNA Support: Returns a punycoded representation of "domain".
  11310. // It only converts parts of the domain name that
  11311. // have non-ASCII characters, i.e. it doesn't matter if
  11312. // you call it with a domain that already is ASCII-only.
  11313. this.hostname = punycode.toASCII(this.hostname);
  11314. }
  11315. var p = this.port ? ':' + this.port : '';
  11316. var h = this.hostname || '';
  11317. this.host = h + p;
  11318. this.href += this.host;
  11319. // strip [ and ] from the hostname
  11320. // the host field still retains them, though
  11321. if (ipv6Hostname) {
  11322. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  11323. if (rest[0] !== '/') {
  11324. rest = '/' + rest;
  11325. }
  11326. }
  11327. }
  11328. // now rest is set to the post-host stuff.
  11329. // chop off any delim chars.
  11330. if (!unsafeProtocol[lowerProto]) {
  11331. // First, make 100% sure that any "autoEscape" chars get
  11332. // escaped, even if encodeURIComponent doesn't think they
  11333. // need to be.
  11334. for (var i = 0, l = autoEscape.length; i < l; i++) {
  11335. var ae = autoEscape[i];
  11336. if (rest.indexOf(ae) === -1)
  11337. continue;
  11338. var esc = encodeURIComponent(ae);
  11339. if (esc === ae) {
  11340. esc = escape(ae);
  11341. }
  11342. rest = rest.split(ae).join(esc);
  11343. }
  11344. }
  11345. // chop off from the tail first.
  11346. var hash = rest.indexOf('#');
  11347. if (hash !== -1) {
  11348. // got a fragment string.
  11349. this.hash = rest.substr(hash);
  11350. rest = rest.slice(0, hash);
  11351. }
  11352. var qm = rest.indexOf('?');
  11353. if (qm !== -1) {
  11354. this.search = rest.substr(qm);
  11355. this.query = rest.substr(qm + 1);
  11356. if (parseQueryString) {
  11357. this.query = querystring.parse(this.query);
  11358. }
  11359. rest = rest.slice(0, qm);
  11360. } else if (parseQueryString) {
  11361. // no query string, but parseQueryString still requested
  11362. this.search = '';
  11363. this.query = {};
  11364. }
  11365. if (rest) this.pathname = rest;
  11366. if (slashedProtocol[lowerProto] &&
  11367. this.hostname && !this.pathname) {
  11368. this.pathname = '/';
  11369. }
  11370. //to support http.request
  11371. if (this.pathname || this.search) {
  11372. var p = this.pathname || '';
  11373. var s = this.search || '';
  11374. this.path = p + s;
  11375. }
  11376. // finally, reconstruct the href based on what has been validated.
  11377. this.href = this.format();
  11378. return this;
  11379. };
  11380. // format a parsed object into a url string
  11381. function urlFormat(obj) {
  11382. // ensure it's an object, and not a string url.
  11383. // If it's an obj, this is a no-op.
  11384. // this way, you can call url_format() on strings
  11385. // to clean up potentially wonky urls.
  11386. if (util.isString(obj)) obj = urlParse(obj);
  11387. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  11388. return obj.format();
  11389. }
  11390. Url.prototype.format = function() {
  11391. var auth = this.auth || '';
  11392. if (auth) {
  11393. auth = encodeURIComponent(auth);
  11394. auth = auth.replace(/%3A/i, ':');
  11395. auth += '@';
  11396. }
  11397. var protocol = this.protocol || '',
  11398. pathname = this.pathname || '',
  11399. hash = this.hash || '',
  11400. host = false,
  11401. query = '';
  11402. if (this.host) {
  11403. host = auth + this.host;
  11404. } else if (this.hostname) {
  11405. host = auth + (this.hostname.indexOf(':') === -1 ?
  11406. this.hostname :
  11407. '[' + this.hostname + ']');
  11408. if (this.port) {
  11409. host += ':' + this.port;
  11410. }
  11411. }
  11412. if (this.query &&
  11413. util.isObject(this.query) &&
  11414. Object.keys(this.query).length) {
  11415. query = querystring.stringify(this.query);
  11416. }
  11417. var search = this.search || (query && ('?' + query)) || '';
  11418. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  11419. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  11420. // unless they had them to begin with.
  11421. if (this.slashes ||
  11422. (!protocol || slashedProtocol[protocol]) && host !== false) {
  11423. host = '//' + (host || '');
  11424. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  11425. } else if (!host) {
  11426. host = '';
  11427. }
  11428. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  11429. if (search && search.charAt(0) !== '?') search = '?' + search;
  11430. pathname = pathname.replace(/[?#]/g, function(match) {
  11431. return encodeURIComponent(match);
  11432. });
  11433. search = search.replace('#', '%23');
  11434. return protocol + host + pathname + search + hash;
  11435. };
  11436. function urlResolve(source, relative) {
  11437. return urlParse(source, false, true).resolve(relative);
  11438. }
  11439. Url.prototype.resolve = function(relative) {
  11440. return this.resolveObject(urlParse(relative, false, true)).format();
  11441. };
  11442. function urlResolveObject(source, relative) {
  11443. if (!source) return relative;
  11444. return urlParse(source, false, true).resolveObject(relative);
  11445. }
  11446. Url.prototype.resolveObject = function(relative) {
  11447. if (util.isString(relative)) {
  11448. var rel = new Url();
  11449. rel.parse(relative, false, true);
  11450. relative = rel;
  11451. }
  11452. var result = new Url();
  11453. var tkeys = Object.keys(this);
  11454. for (var tk = 0; tk < tkeys.length; tk++) {
  11455. var tkey = tkeys[tk];
  11456. result[tkey] = this[tkey];
  11457. }
  11458. // hash is always overridden, no matter what.
  11459. // even href="" will remove it.
  11460. result.hash = relative.hash;
  11461. // if the relative url is empty, then there's nothing left to do here.
  11462. if (relative.href === '') {
  11463. result.href = result.format();
  11464. return result;
  11465. }
  11466. // hrefs like //foo/bar always cut to the protocol.
  11467. if (relative.slashes && !relative.protocol) {
  11468. // take everything except the protocol from relative
  11469. var rkeys = Object.keys(relative);
  11470. for (var rk = 0; rk < rkeys.length; rk++) {
  11471. var rkey = rkeys[rk];
  11472. if (rkey !== 'protocol')
  11473. result[rkey] = relative[rkey];
  11474. }
  11475. //urlParse appends trailing / to urls like http://www.example.com
  11476. if (slashedProtocol[result.protocol] &&
  11477. result.hostname && !result.pathname) {
  11478. result.path = result.pathname = '/';
  11479. }
  11480. result.href = result.format();
  11481. return result;
  11482. }
  11483. if (relative.protocol && relative.protocol !== result.protocol) {
  11484. // if it's a known url protocol, then changing
  11485. // the protocol does weird things
  11486. // first, if it's not file:, then we MUST have a host,
  11487. // and if there was a path
  11488. // to begin with, then we MUST have a path.
  11489. // if it is file:, then the host is dropped,
  11490. // because that's known to be hostless.
  11491. // anything else is assumed to be absolute.
  11492. if (!slashedProtocol[relative.protocol]) {
  11493. var keys = Object.keys(relative);
  11494. for (var v = 0; v < keys.length; v++) {
  11495. var k = keys[v];
  11496. result[k] = relative[k];
  11497. }
  11498. result.href = result.format();
  11499. return result;
  11500. }
  11501. result.protocol = relative.protocol;
  11502. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  11503. var relPath = (relative.pathname || '').split('/');
  11504. while (relPath.length && !(relative.host = relPath.shift()));
  11505. if (!relative.host) relative.host = '';
  11506. if (!relative.hostname) relative.hostname = '';
  11507. if (relPath[0] !== '') relPath.unshift('');
  11508. if (relPath.length < 2) relPath.unshift('');
  11509. result.pathname = relPath.join('/');
  11510. } else {
  11511. result.pathname = relative.pathname;
  11512. }
  11513. result.search = relative.search;
  11514. result.query = relative.query;
  11515. result.host = relative.host || '';
  11516. result.auth = relative.auth;
  11517. result.hostname = relative.hostname || relative.host;
  11518. result.port = relative.port;
  11519. // to support http.request
  11520. if (result.pathname || result.search) {
  11521. var p = result.pathname || '';
  11522. var s = result.search || '';
  11523. result.path = p + s;
  11524. }
  11525. result.slashes = result.slashes || relative.slashes;
  11526. result.href = result.format();
  11527. return result;
  11528. }
  11529. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  11530. isRelAbs = (
  11531. relative.host ||
  11532. relative.pathname && relative.pathname.charAt(0) === '/'
  11533. ),
  11534. mustEndAbs = (isRelAbs || isSourceAbs ||
  11535. (result.host && relative.pathname)),
  11536. removeAllDots = mustEndAbs,
  11537. srcPath = result.pathname && result.pathname.split('/') || [],
  11538. relPath = relative.pathname && relative.pathname.split('/') || [],
  11539. psychotic = result.protocol && !slashedProtocol[result.protocol];
  11540. // if the url is a non-slashed url, then relative
  11541. // links like ../.. should be able
  11542. // to crawl up to the hostname, as well. This is strange.
  11543. // result.protocol has already been set by now.
  11544. // Later on, put the first path part into the host field.
  11545. if (psychotic) {
  11546. result.hostname = '';
  11547. result.port = null;
  11548. if (result.host) {
  11549. if (srcPath[0] === '') srcPath[0] = result.host;
  11550. else srcPath.unshift(result.host);
  11551. }
  11552. result.host = '';
  11553. if (relative.protocol) {
  11554. relative.hostname = null;
  11555. relative.port = null;
  11556. if (relative.host) {
  11557. if (relPath[0] === '') relPath[0] = relative.host;
  11558. else relPath.unshift(relative.host);
  11559. }
  11560. relative.host = null;
  11561. }
  11562. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  11563. }
  11564. if (isRelAbs) {
  11565. // it's absolute.
  11566. result.host = (relative.host || relative.host === '') ?
  11567. relative.host : result.host;
  11568. result.hostname = (relative.hostname || relative.hostname === '') ?
  11569. relative.hostname : result.hostname;
  11570. result.search = relative.search;
  11571. result.query = relative.query;
  11572. srcPath = relPath;
  11573. // fall through to the dot-handling below.
  11574. } else if (relPath.length) {
  11575. // it's relative
  11576. // throw away the existing file, and take the new path instead.
  11577. if (!srcPath) srcPath = [];
  11578. srcPath.pop();
  11579. srcPath = srcPath.concat(relPath);
  11580. result.search = relative.search;
  11581. result.query = relative.query;
  11582. } else if (!util.isNullOrUndefined(relative.search)) {
  11583. // just pull out the search.
  11584. // like href='?foo'.
  11585. // Put this after the other two cases because it simplifies the booleans
  11586. if (psychotic) {
  11587. result.hostname = result.host = srcPath.shift();
  11588. //occationaly the auth can get stuck only in host
  11589. //this especially happens in cases like
  11590. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  11591. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  11592. result.host.split('@') : false;
  11593. if (authInHost) {
  11594. result.auth = authInHost.shift();
  11595. result.host = result.hostname = authInHost.shift();
  11596. }
  11597. }
  11598. result.search = relative.search;
  11599. result.query = relative.query;
  11600. //to support http.request
  11601. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  11602. result.path = (result.pathname ? result.pathname : '') +
  11603. (result.search ? result.search : '');
  11604. }
  11605. result.href = result.format();
  11606. return result;
  11607. }
  11608. if (!srcPath.length) {
  11609. // no path at all. easy.
  11610. // we've already handled the other stuff above.
  11611. result.pathname = null;
  11612. //to support http.request
  11613. if (result.search) {
  11614. result.path = '/' + result.search;
  11615. } else {
  11616. result.path = null;
  11617. }
  11618. result.href = result.format();
  11619. return result;
  11620. }
  11621. // if a url ENDs in . or .., then it must get a trailing slash.
  11622. // however, if it ends in anything else non-slashy,
  11623. // then it must NOT get a trailing slash.
  11624. var last = srcPath.slice(-1)[0];
  11625. var hasTrailingSlash = (
  11626. (result.host || relative.host || srcPath.length > 1) &&
  11627. (last === '.' || last === '..') || last === '');
  11628. // strip single dots, resolve double dots to parent dir
  11629. // if the path tries to go above the root, `up` ends up > 0
  11630. var up = 0;
  11631. for (var i = srcPath.length; i >= 0; i--) {
  11632. last = srcPath[i];
  11633. if (last === '.') {
  11634. srcPath.splice(i, 1);
  11635. } else if (last === '..') {
  11636. srcPath.splice(i, 1);
  11637. up++;
  11638. } else if (up) {
  11639. srcPath.splice(i, 1);
  11640. up--;
  11641. }
  11642. }
  11643. // if the path is allowed to go above the root, restore leading ..s
  11644. if (!mustEndAbs && !removeAllDots) {
  11645. for (; up--; up) {
  11646. srcPath.unshift('..');
  11647. }
  11648. }
  11649. if (mustEndAbs && srcPath[0] !== '' &&
  11650. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  11651. srcPath.unshift('');
  11652. }
  11653. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  11654. srcPath.push('');
  11655. }
  11656. var isAbsolute = srcPath[0] === '' ||
  11657. (srcPath[0] && srcPath[0].charAt(0) === '/');
  11658. // put the host back
  11659. if (psychotic) {
  11660. result.hostname = result.host = isAbsolute ? '' :
  11661. srcPath.length ? srcPath.shift() : '';
  11662. //occationaly the auth can get stuck only in host
  11663. //this especially happens in cases like
  11664. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  11665. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  11666. result.host.split('@') : false;
  11667. if (authInHost) {
  11668. result.auth = authInHost.shift();
  11669. result.host = result.hostname = authInHost.shift();
  11670. }
  11671. }
  11672. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  11673. if (mustEndAbs && !isAbsolute) {
  11674. srcPath.unshift('');
  11675. }
  11676. if (!srcPath.length) {
  11677. result.pathname = null;
  11678. result.path = null;
  11679. } else {
  11680. result.pathname = srcPath.join('/');
  11681. }
  11682. //to support request.http
  11683. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  11684. result.path = (result.pathname ? result.pathname : '') +
  11685. (result.search ? result.search : '');
  11686. }
  11687. result.auth = relative.auth || result.auth;
  11688. result.slashes = result.slashes || relative.slashes;
  11689. result.href = result.format();
  11690. return result;
  11691. };
  11692. Url.prototype.parseHost = function() {
  11693. var host = this.host;
  11694. var port = portPattern.exec(host);
  11695. if (port) {
  11696. port = port[0];
  11697. if (port !== ':') {
  11698. this.port = port.substr(1);
  11699. }
  11700. host = host.substr(0, host.length - port.length);
  11701. }
  11702. if (host) this.hostname = host;
  11703. };
  11704. },{"./util":114,"punycode":93,"querystring":96}],114:[function(require,module,exports){
  11705. 'use strict';
  11706. module.exports = {
  11707. isString: function(arg) {
  11708. return typeof(arg) === 'string';
  11709. },
  11710. isObject: function(arg) {
  11711. return typeof(arg) === 'object' && arg !== null;
  11712. },
  11713. isNull: function(arg) {
  11714. return arg === null;
  11715. },
  11716. isNullOrUndefined: function(arg) {
  11717. return arg == null;
  11718. }
  11719. };
  11720. },{}],115:[function(require,module,exports){
  11721. (function (global){
  11722. /**
  11723. * Module exports.
  11724. */
  11725. module.exports = deprecate;
  11726. /**
  11727. * Mark that a method should not be used.
  11728. * Returns a modified function which warns once by default.
  11729. *
  11730. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  11731. *
  11732. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  11733. * will throw an Error when invoked.
  11734. *
  11735. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  11736. * will invoke `console.trace()` instead of `console.error()`.
  11737. *
  11738. * @param {Function} fn - the function to deprecate
  11739. * @param {String} msg - the string to print to the console when `fn` is invoked
  11740. * @returns {Function} a new "deprecated" version of `fn`
  11741. * @api public
  11742. */
  11743. function deprecate (fn, msg) {
  11744. if (config('noDeprecation')) {
  11745. return fn;
  11746. }
  11747. var warned = false;
  11748. function deprecated() {
  11749. if (!warned) {
  11750. if (config('throwDeprecation')) {
  11751. throw new Error(msg);
  11752. } else if (config('traceDeprecation')) {
  11753. console.trace(msg);
  11754. } else {
  11755. console.warn(msg);
  11756. }
  11757. warned = true;
  11758. }
  11759. return fn.apply(this, arguments);
  11760. }
  11761. return deprecated;
  11762. }
  11763. /**
  11764. * Checks `localStorage` for boolean values for the given `name`.
  11765. *
  11766. * @param {String} name
  11767. * @returns {Boolean}
  11768. * @api private
  11769. */
  11770. function config (name) {
  11771. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  11772. try {
  11773. if (!global.localStorage) return false;
  11774. } catch (_) {
  11775. return false;
  11776. }
  11777. var val = global.localStorage[name];
  11778. if (null == val) return false;
  11779. return String(val).toLowerCase() === 'true';
  11780. }
  11781. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11782. },{}],116:[function(require,module,exports){
  11783. module.exports = function isBuffer(arg) {
  11784. return arg && typeof arg === 'object'
  11785. && typeof arg.copy === 'function'
  11786. && typeof arg.fill === 'function'
  11787. && typeof arg.readUInt8 === 'function';
  11788. }
  11789. },{}],117:[function(require,module,exports){
  11790. (function (process,global){
  11791. // Copyright Joyent, Inc. and other Node contributors.
  11792. //
  11793. // Permission is hereby granted, free of charge, to any person obtaining a
  11794. // copy of this software and associated documentation files (the
  11795. // "Software"), to deal in the Software without restriction, including
  11796. // without limitation the rights to use, copy, modify, merge, publish,
  11797. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11798. // persons to whom the Software is furnished to do so, subject to the
  11799. // following conditions:
  11800. //
  11801. // The above copyright notice and this permission notice shall be included
  11802. // in all copies or substantial portions of the Software.
  11803. //
  11804. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11805. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11806. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11807. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11808. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11809. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11810. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11811. var formatRegExp = /%[sdj%]/g;
  11812. exports.format = function(f) {
  11813. if (!isString(f)) {
  11814. var objects = [];
  11815. for (var i = 0; i < arguments.length; i++) {
  11816. objects.push(inspect(arguments[i]));
  11817. }
  11818. return objects.join(' ');
  11819. }
  11820. var i = 1;
  11821. var args = arguments;
  11822. var len = args.length;
  11823. var str = String(f).replace(formatRegExp, function(x) {
  11824. if (x === '%%') return '%';
  11825. if (i >= len) return x;
  11826. switch (x) {
  11827. case '%s': return String(args[i++]);
  11828. case '%d': return Number(args[i++]);
  11829. case '%j':
  11830. try {
  11831. return JSON.stringify(args[i++]);
  11832. } catch (_) {
  11833. return '[Circular]';
  11834. }
  11835. default:
  11836. return x;
  11837. }
  11838. });
  11839. for (var x = args[i]; i < len; x = args[++i]) {
  11840. if (isNull(x) || !isObject(x)) {
  11841. str += ' ' + x;
  11842. } else {
  11843. str += ' ' + inspect(x);
  11844. }
  11845. }
  11846. return str;
  11847. };
  11848. // Mark that a method should not be used.
  11849. // Returns a modified function which warns once by default.
  11850. // If --no-deprecation is set, then it is a no-op.
  11851. exports.deprecate = function(fn, msg) {
  11852. // Allow for deprecating things in the process of starting up.
  11853. if (isUndefined(global.process)) {
  11854. return function() {
  11855. return exports.deprecate(fn, msg).apply(this, arguments);
  11856. };
  11857. }
  11858. if (process.noDeprecation === true) {
  11859. return fn;
  11860. }
  11861. var warned = false;
  11862. function deprecated() {
  11863. if (!warned) {
  11864. if (process.throwDeprecation) {
  11865. throw new Error(msg);
  11866. } else if (process.traceDeprecation) {
  11867. console.trace(msg);
  11868. } else {
  11869. console.error(msg);
  11870. }
  11871. warned = true;
  11872. }
  11873. return fn.apply(this, arguments);
  11874. }
  11875. return deprecated;
  11876. };
  11877. var debugs = {};
  11878. var debugEnviron;
  11879. exports.debuglog = function(set) {
  11880. if (isUndefined(debugEnviron))
  11881. debugEnviron = process.env.NODE_DEBUG || '';
  11882. set = set.toUpperCase();
  11883. if (!debugs[set]) {
  11884. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  11885. var pid = process.pid;
  11886. debugs[set] = function() {
  11887. var msg = exports.format.apply(exports, arguments);
  11888. console.error('%s %d: %s', set, pid, msg);
  11889. };
  11890. } else {
  11891. debugs[set] = function() {};
  11892. }
  11893. }
  11894. return debugs[set];
  11895. };
  11896. /**
  11897. * Echos the value of a value. Trys to print the value out
  11898. * in the best way possible given the different types.
  11899. *
  11900. * @param {Object} obj The object to print out.
  11901. * @param {Object} opts Optional options object that alters the output.
  11902. */
  11903. /* legacy: obj, showHidden, depth, colors*/
  11904. function inspect(obj, opts) {
  11905. // default options
  11906. var ctx = {
  11907. seen: [],
  11908. stylize: stylizeNoColor
  11909. };
  11910. // legacy...
  11911. if (arguments.length >= 3) ctx.depth = arguments[2];
  11912. if (arguments.length >= 4) ctx.colors = arguments[3];
  11913. if (isBoolean(opts)) {
  11914. // legacy...
  11915. ctx.showHidden = opts;
  11916. } else if (opts) {
  11917. // got an "options" object
  11918. exports._extend(ctx, opts);
  11919. }
  11920. // set default options
  11921. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  11922. if (isUndefined(ctx.depth)) ctx.depth = 2;
  11923. if (isUndefined(ctx.colors)) ctx.colors = false;
  11924. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  11925. if (ctx.colors) ctx.stylize = stylizeWithColor;
  11926. return formatValue(ctx, obj, ctx.depth);
  11927. }
  11928. exports.inspect = inspect;
  11929. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  11930. inspect.colors = {
  11931. 'bold' : [1, 22],
  11932. 'italic' : [3, 23],
  11933. 'underline' : [4, 24],
  11934. 'inverse' : [7, 27],
  11935. 'white' : [37, 39],
  11936. 'grey' : [90, 39],
  11937. 'black' : [30, 39],
  11938. 'blue' : [34, 39],
  11939. 'cyan' : [36, 39],
  11940. 'green' : [32, 39],
  11941. 'magenta' : [35, 39],
  11942. 'red' : [31, 39],
  11943. 'yellow' : [33, 39]
  11944. };
  11945. // Don't use 'blue' not visible on cmd.exe
  11946. inspect.styles = {
  11947. 'special': 'cyan',
  11948. 'number': 'yellow',
  11949. 'boolean': 'yellow',
  11950. 'undefined': 'grey',
  11951. 'null': 'bold',
  11952. 'string': 'green',
  11953. 'date': 'magenta',
  11954. // "name": intentionally not styling
  11955. 'regexp': 'red'
  11956. };
  11957. function stylizeWithColor(str, styleType) {
  11958. var style = inspect.styles[styleType];
  11959. if (style) {
  11960. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  11961. '\u001b[' + inspect.colors[style][1] + 'm';
  11962. } else {
  11963. return str;
  11964. }
  11965. }
  11966. function stylizeNoColor(str, styleType) {
  11967. return str;
  11968. }
  11969. function arrayToHash(array) {
  11970. var hash = {};
  11971. array.forEach(function(val, idx) {
  11972. hash[val] = true;
  11973. });
  11974. return hash;
  11975. }
  11976. function formatValue(ctx, value, recurseTimes) {
  11977. // Provide a hook for user-specified inspect functions.
  11978. // Check that value is an object with an inspect function on it
  11979. if (ctx.customInspect &&
  11980. value &&
  11981. isFunction(value.inspect) &&
  11982. // Filter out the util module, it's inspect function is special
  11983. value.inspect !== exports.inspect &&
  11984. // Also filter out any prototype objects using the circular check.
  11985. !(value.constructor && value.constructor.prototype === value)) {
  11986. var ret = value.inspect(recurseTimes, ctx);
  11987. if (!isString(ret)) {
  11988. ret = formatValue(ctx, ret, recurseTimes);
  11989. }
  11990. return ret;
  11991. }
  11992. // Primitive types cannot have properties
  11993. var primitive = formatPrimitive(ctx, value);
  11994. if (primitive) {
  11995. return primitive;
  11996. }
  11997. // Look up the keys of the object.
  11998. var keys = Object.keys(value);
  11999. var visibleKeys = arrayToHash(keys);
  12000. if (ctx.showHidden) {
  12001. keys = Object.getOwnPropertyNames(value);
  12002. }
  12003. // IE doesn't make error fields non-enumerable
  12004. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  12005. if (isError(value)
  12006. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  12007. return formatError(value);
  12008. }
  12009. // Some type of object without properties can be shortcutted.
  12010. if (keys.length === 0) {
  12011. if (isFunction(value)) {
  12012. var name = value.name ? ': ' + value.name : '';
  12013. return ctx.stylize('[Function' + name + ']', 'special');
  12014. }
  12015. if (isRegExp(value)) {
  12016. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12017. }
  12018. if (isDate(value)) {
  12019. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  12020. }
  12021. if (isError(value)) {
  12022. return formatError(value);
  12023. }
  12024. }
  12025. var base = '', array = false, braces = ['{', '}'];
  12026. // Make Array say that they are Array
  12027. if (isArray(value)) {
  12028. array = true;
  12029. braces = ['[', ']'];
  12030. }
  12031. // Make functions say that they are functions
  12032. if (isFunction(value)) {
  12033. var n = value.name ? ': ' + value.name : '';
  12034. base = ' [Function' + n + ']';
  12035. }
  12036. // Make RegExps say that they are RegExps
  12037. if (isRegExp(value)) {
  12038. base = ' ' + RegExp.prototype.toString.call(value);
  12039. }
  12040. // Make dates with properties first say the date
  12041. if (isDate(value)) {
  12042. base = ' ' + Date.prototype.toUTCString.call(value);
  12043. }
  12044. // Make error with message first say the error
  12045. if (isError(value)) {
  12046. base = ' ' + formatError(value);
  12047. }
  12048. if (keys.length === 0 && (!array || value.length == 0)) {
  12049. return braces[0] + base + braces[1];
  12050. }
  12051. if (recurseTimes < 0) {
  12052. if (isRegExp(value)) {
  12053. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12054. } else {
  12055. return ctx.stylize('[Object]', 'special');
  12056. }
  12057. }
  12058. ctx.seen.push(value);
  12059. var output;
  12060. if (array) {
  12061. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  12062. } else {
  12063. output = keys.map(function(key) {
  12064. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  12065. });
  12066. }
  12067. ctx.seen.pop();
  12068. return reduceToSingleString(output, base, braces);
  12069. }
  12070. function formatPrimitive(ctx, value) {
  12071. if (isUndefined(value))
  12072. return ctx.stylize('undefined', 'undefined');
  12073. if (isString(value)) {
  12074. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  12075. .replace(/'/g, "\\'")
  12076. .replace(/\\"/g, '"') + '\'';
  12077. return ctx.stylize(simple, 'string');
  12078. }
  12079. if (isNumber(value))
  12080. return ctx.stylize('' + value, 'number');
  12081. if (isBoolean(value))
  12082. return ctx.stylize('' + value, 'boolean');
  12083. // For some reason typeof null is "object", so special case here.
  12084. if (isNull(value))
  12085. return ctx.stylize('null', 'null');
  12086. }
  12087. function formatError(value) {
  12088. return '[' + Error.prototype.toString.call(value) + ']';
  12089. }
  12090. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  12091. var output = [];
  12092. for (var i = 0, l = value.length; i < l; ++i) {
  12093. if (hasOwnProperty(value, String(i))) {
  12094. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12095. String(i), true));
  12096. } else {
  12097. output.push('');
  12098. }
  12099. }
  12100. keys.forEach(function(key) {
  12101. if (!key.match(/^\d+$/)) {
  12102. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12103. key, true));
  12104. }
  12105. });
  12106. return output;
  12107. }
  12108. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  12109. var name, str, desc;
  12110. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  12111. if (desc.get) {
  12112. if (desc.set) {
  12113. str = ctx.stylize('[Getter/Setter]', 'special');
  12114. } else {
  12115. str = ctx.stylize('[Getter]', 'special');
  12116. }
  12117. } else {
  12118. if (desc.set) {
  12119. str = ctx.stylize('[Setter]', 'special');
  12120. }
  12121. }
  12122. if (!hasOwnProperty(visibleKeys, key)) {
  12123. name = '[' + key + ']';
  12124. }
  12125. if (!str) {
  12126. if (ctx.seen.indexOf(desc.value) < 0) {
  12127. if (isNull(recurseTimes)) {
  12128. str = formatValue(ctx, desc.value, null);
  12129. } else {
  12130. str = formatValue(ctx, desc.value, recurseTimes - 1);
  12131. }
  12132. if (str.indexOf('\n') > -1) {
  12133. if (array) {
  12134. str = str.split('\n').map(function(line) {
  12135. return ' ' + line;
  12136. }).join('\n').substr(2);
  12137. } else {
  12138. str = '\n' + str.split('\n').map(function(line) {
  12139. return ' ' + line;
  12140. }).join('\n');
  12141. }
  12142. }
  12143. } else {
  12144. str = ctx.stylize('[Circular]', 'special');
  12145. }
  12146. }
  12147. if (isUndefined(name)) {
  12148. if (array && key.match(/^\d+$/)) {
  12149. return str;
  12150. }
  12151. name = JSON.stringify('' + key);
  12152. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  12153. name = name.substr(1, name.length - 2);
  12154. name = ctx.stylize(name, 'name');
  12155. } else {
  12156. name = name.replace(/'/g, "\\'")
  12157. .replace(/\\"/g, '"')
  12158. .replace(/(^"|"$)/g, "'");
  12159. name = ctx.stylize(name, 'string');
  12160. }
  12161. }
  12162. return name + ': ' + str;
  12163. }
  12164. function reduceToSingleString(output, base, braces) {
  12165. var numLinesEst = 0;
  12166. var length = output.reduce(function(prev, cur) {
  12167. numLinesEst++;
  12168. if (cur.indexOf('\n') >= 0) numLinesEst++;
  12169. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  12170. }, 0);
  12171. if (length > 60) {
  12172. return braces[0] +
  12173. (base === '' ? '' : base + '\n ') +
  12174. ' ' +
  12175. output.join(',\n ') +
  12176. ' ' +
  12177. braces[1];
  12178. }
  12179. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  12180. }
  12181. // NOTE: These type checking functions intentionally don't use `instanceof`
  12182. // because it is fragile and can be easily faked with `Object.create()`.
  12183. function isArray(ar) {
  12184. return Array.isArray(ar);
  12185. }
  12186. exports.isArray = isArray;
  12187. function isBoolean(arg) {
  12188. return typeof arg === 'boolean';
  12189. }
  12190. exports.isBoolean = isBoolean;
  12191. function isNull(arg) {
  12192. return arg === null;
  12193. }
  12194. exports.isNull = isNull;
  12195. function isNullOrUndefined(arg) {
  12196. return arg == null;
  12197. }
  12198. exports.isNullOrUndefined = isNullOrUndefined;
  12199. function isNumber(arg) {
  12200. return typeof arg === 'number';
  12201. }
  12202. exports.isNumber = isNumber;
  12203. function isString(arg) {
  12204. return typeof arg === 'string';
  12205. }
  12206. exports.isString = isString;
  12207. function isSymbol(arg) {
  12208. return typeof arg === 'symbol';
  12209. }
  12210. exports.isSymbol = isSymbol;
  12211. function isUndefined(arg) {
  12212. return arg === void 0;
  12213. }
  12214. exports.isUndefined = isUndefined;
  12215. function isRegExp(re) {
  12216. return isObject(re) && objectToString(re) === '[object RegExp]';
  12217. }
  12218. exports.isRegExp = isRegExp;
  12219. function isObject(arg) {
  12220. return typeof arg === 'object' && arg !== null;
  12221. }
  12222. exports.isObject = isObject;
  12223. function isDate(d) {
  12224. return isObject(d) && objectToString(d) === '[object Date]';
  12225. }
  12226. exports.isDate = isDate;
  12227. function isError(e) {
  12228. return isObject(e) &&
  12229. (objectToString(e) === '[object Error]' || e instanceof Error);
  12230. }
  12231. exports.isError = isError;
  12232. function isFunction(arg) {
  12233. return typeof arg === 'function';
  12234. }
  12235. exports.isFunction = isFunction;
  12236. function isPrimitive(arg) {
  12237. return arg === null ||
  12238. typeof arg === 'boolean' ||
  12239. typeof arg === 'number' ||
  12240. typeof arg === 'string' ||
  12241. typeof arg === 'symbol' || // ES6 symbol
  12242. typeof arg === 'undefined';
  12243. }
  12244. exports.isPrimitive = isPrimitive;
  12245. exports.isBuffer = require('./support/isBuffer');
  12246. function objectToString(o) {
  12247. return Object.prototype.toString.call(o);
  12248. }
  12249. function pad(n) {
  12250. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  12251. }
  12252. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  12253. 'Oct', 'Nov', 'Dec'];
  12254. // 26 Feb 16:19:34
  12255. function timestamp() {
  12256. var d = new Date();
  12257. var time = [pad(d.getHours()),
  12258. pad(d.getMinutes()),
  12259. pad(d.getSeconds())].join(':');
  12260. return [d.getDate(), months[d.getMonth()], time].join(' ');
  12261. }
  12262. // log is just a thin wrapper to console.log that prepends a timestamp
  12263. exports.log = function() {
  12264. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  12265. };
  12266. /**
  12267. * Inherit the prototype methods from one constructor into another.
  12268. *
  12269. * The Function.prototype.inherits from lang.js rewritten as a standalone
  12270. * function (not on Function.prototype). NOTE: If this file is to be loaded
  12271. * during bootstrapping this function needs to be rewritten using some native
  12272. * functions as prototype setup using normal JavaScript does not work as
  12273. * expected during bootstrapping (see mirror.js in r114903).
  12274. *
  12275. * @param {function} ctor Constructor function which needs to inherit the
  12276. * prototype.
  12277. * @param {function} superCtor Constructor function to inherit prototype from.
  12278. */
  12279. exports.inherits = require('inherits');
  12280. exports._extend = function(origin, add) {
  12281. // Don't do anything if add isn't an object
  12282. if (!add || !isObject(add)) return origin;
  12283. var keys = Object.keys(add);
  12284. var i = keys.length;
  12285. while (i--) {
  12286. origin[keys[i]] = add[keys[i]];
  12287. }
  12288. return origin;
  12289. };
  12290. function hasOwnProperty(obj, prop) {
  12291. return Object.prototype.hasOwnProperty.call(obj, prop);
  12292. }
  12293. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12294. },{"./support/isBuffer":116,"_process":92,"inherits":80}],118:[function(require,module,exports){
  12295. (function (process,global){
  12296. 'use strict'
  12297. var Transform = require('readable-stream').Transform
  12298. var duplexify = require('duplexify')
  12299. var WS = require('ws')
  12300. var Buffer = require('safe-buffer').Buffer
  12301. module.exports = WebSocketStream
  12302. function buildProxy (options, socketWrite, socketEnd) {
  12303. var proxy = new Transform({
  12304. objectMode: options.objectMode
  12305. })
  12306. proxy._write = socketWrite
  12307. proxy._flush = socketEnd
  12308. return proxy
  12309. }
  12310. function WebSocketStream(target, protocols, options) {
  12311. var stream, socket
  12312. var isBrowser = process.title === 'browser'
  12313. var isNative = !!global.WebSocket
  12314. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  12315. if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
  12316. // accept the "options" Object as the 2nd argument
  12317. options = protocols
  12318. protocols = null
  12319. if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
  12320. protocols = options.protocol;
  12321. }
  12322. }
  12323. if (!options) options = {}
  12324. if (options.objectMode === undefined) {
  12325. options.objectMode = !(options.binary === true || options.binary === undefined)
  12326. }
  12327. var proxy = buildProxy(options, socketWrite, socketEnd)
  12328. if (!options.objectMode) {
  12329. proxy._writev = writev
  12330. }
  12331. // browser only: sets the maximum socket buffer size before throttling
  12332. var bufferSize = options.browserBufferSize || 1024 * 512
  12333. // browser only: how long to wait when throttling
  12334. var bufferTimeout = options.browserBufferTimeout || 1000
  12335. // use existing WebSocket object that was passed in
  12336. if (typeof target === 'object') {
  12337. socket = target
  12338. // otherwise make a new one
  12339. } else {
  12340. // special constructor treatment for native websockets in browsers, see
  12341. // https://github.com/maxogden/websocket-stream/issues/82
  12342. if (isNative && isBrowser) {
  12343. socket = new WS(target, protocols)
  12344. } else {
  12345. socket = new WS(target, protocols, options)
  12346. }
  12347. socket.binaryType = 'arraybuffer'
  12348. }
  12349. // was already open when passed in
  12350. if (socket.readyState === socket.OPEN) {
  12351. stream = proxy
  12352. } else {
  12353. stream = duplexify.obj()
  12354. socket.onopen = onopen
  12355. }
  12356. stream.socket = socket
  12357. socket.onclose = onclose
  12358. socket.onerror = onerror
  12359. socket.onmessage = onmessage
  12360. proxy.on('close', destroy)
  12361. var coerceToBuffer = !options.objectMode
  12362. function socketWriteNode(chunk, enc, next) {
  12363. // avoid errors, this never happens unless
  12364. // destroy() is called
  12365. if (socket.readyState !== socket.OPEN) {
  12366. next()
  12367. return
  12368. }
  12369. if (coerceToBuffer && typeof chunk === 'string') {
  12370. chunk = Buffer.from(chunk, 'utf8')
  12371. }
  12372. socket.send(chunk, next)
  12373. }
  12374. function socketWriteBrowser(chunk, enc, next) {
  12375. if (socket.bufferedAmount > bufferSize) {
  12376. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  12377. return
  12378. }
  12379. if (coerceToBuffer && typeof chunk === 'string') {
  12380. chunk = Buffer.from(chunk, 'utf8')
  12381. }
  12382. try {
  12383. socket.send(chunk)
  12384. } catch(err) {
  12385. return next(err)
  12386. }
  12387. next()
  12388. }
  12389. function socketEnd(done) {
  12390. socket.close()
  12391. done()
  12392. }
  12393. function onopen() {
  12394. stream.setReadable(proxy)
  12395. stream.setWritable(proxy)
  12396. stream.emit('connect')
  12397. }
  12398. function onclose() {
  12399. stream.end()
  12400. stream.destroy()
  12401. }
  12402. function onerror(err) {
  12403. stream.destroy(err)
  12404. }
  12405. function onmessage(event) {
  12406. var data = event.data
  12407. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  12408. else data = Buffer.from(data, 'utf8')
  12409. proxy.push(data)
  12410. }
  12411. function destroy() {
  12412. socket.close()
  12413. }
  12414. // this is to be enabled only if objectMode is false
  12415. function writev (chunks, cb) {
  12416. var buffers = new Array(chunks.length)
  12417. for (var i = 0; i < chunks.length; i++) {
  12418. if (typeof chunks[i].chunk === 'string') {
  12419. buffers[i] = Buffer.from(chunks[i], 'utf8')
  12420. } else {
  12421. buffers[i] = chunks[i].chunk
  12422. }
  12423. }
  12424. this._write(Buffer.concat(buffers), 'binary', cb)
  12425. }
  12426. return stream
  12427. }
  12428. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12429. },{"_process":92,"duplexify":17,"readable-stream":108,"safe-buffer":110,"ws":119}],119:[function(require,module,exports){
  12430. var ws = null
  12431. if (typeof WebSocket !== 'undefined') {
  12432. ws = WebSocket
  12433. } else if (typeof MozWebSocket !== 'undefined') {
  12434. ws = MozWebSocket
  12435. } else if (typeof window !== 'undefined') {
  12436. ws = window.WebSocket || window.MozWebSocket
  12437. }
  12438. module.exports = ws
  12439. },{}],120:[function(require,module,exports){
  12440. // Returns a wrapper function that returns a wrapped callback
  12441. // The wrapper function should do some stuff, and return a
  12442. // presumably different callback function.
  12443. // This makes sure that own properties are retained, so that
  12444. // decorations and such are not lost along the way.
  12445. module.exports = wrappy
  12446. function wrappy (fn, cb) {
  12447. if (fn && cb) return wrappy(fn)(cb)
  12448. if (typeof fn !== 'function')
  12449. throw new TypeError('need wrapper function')
  12450. Object.keys(fn).forEach(function (k) {
  12451. wrapper[k] = fn[k]
  12452. })
  12453. return wrapper
  12454. function wrapper() {
  12455. var args = new Array(arguments.length)
  12456. for (var i = 0; i < args.length; i++) {
  12457. args[i] = arguments[i]
  12458. }
  12459. var ret = fn.apply(this, args)
  12460. var cb = args[args.length-1]
  12461. if (typeof ret === 'function' && ret !== cb) {
  12462. Object.keys(cb).forEach(function (k) {
  12463. ret[k] = cb[k]
  12464. })
  12465. }
  12466. return ret
  12467. }
  12468. }
  12469. },{}],121:[function(require,module,exports){
  12470. module.exports = extend
  12471. var hasOwnProperty = Object.prototype.hasOwnProperty;
  12472. function extend() {
  12473. var target = {}
  12474. for (var i = 0; i < arguments.length; i++) {
  12475. var source = arguments[i]
  12476. for (var key in source) {
  12477. if (hasOwnProperty.call(source, key)) {
  12478. target[key] = source[key]
  12479. }
  12480. }
  12481. }
  12482. return target
  12483. }
  12484. },{}]},{},[9])(9)
  12485. });