d39c1cae5744d693e31e86b834667257ebe4ae7a1ed86a36fc042bca0f84120d7f4fd4101cea529ae13c136b580c5ca6fdb25e6a3a64eab7c891fe84b0ddc5 551 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mqtt = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (process,global){(function (){
  3. 'use strict'
  4. /**
  5. * Module dependencies
  6. */
  7. const EventEmitter = require('events').EventEmitter
  8. const Store = require('./store')
  9. const TopicAliasRecv = require('./topic-alias-recv')
  10. const TopicAliasSend = require('./topic-alias-send')
  11. const mqttPacket = require('mqtt-packet')
  12. const DefaultMessageIdProvider = require('./default-message-id-provider')
  13. const Writable = require('readable-stream').Writable
  14. const inherits = require('inherits')
  15. const reInterval = require('reinterval')
  16. const clone = require('rfdc/default')
  17. const validations = require('./validations')
  18. const xtend = require('xtend')
  19. const debug = require('debug')('mqttjs:client')
  20. const nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }
  21. const setImmediate = global.setImmediate || function (callback) {
  22. // works in node v0.8
  23. nextTick(callback)
  24. }
  25. const defaultConnectOptions = {
  26. keepalive: 60,
  27. reschedulePings: true,
  28. protocolId: 'MQTT',
  29. protocolVersion: 4,
  30. reconnectPeriod: 1000,
  31. connectTimeout: 30 * 1000,
  32. clean: true,
  33. resubscribe: true
  34. }
  35. const errors = {
  36. 0: '',
  37. 1: 'Unacceptable protocol version',
  38. 2: 'Identifier rejected',
  39. 3: 'Server unavailable',
  40. 4: 'Bad username or password',
  41. 5: 'Not authorized',
  42. 16: 'No matching subscribers',
  43. 17: 'No subscription existed',
  44. 128: 'Unspecified error',
  45. 129: 'Malformed Packet',
  46. 130: 'Protocol Error',
  47. 131: 'Implementation specific error',
  48. 132: 'Unsupported Protocol Version',
  49. 133: 'Client Identifier not valid',
  50. 134: 'Bad User Name or Password',
  51. 135: 'Not authorized',
  52. 136: 'Server unavailable',
  53. 137: 'Server busy',
  54. 138: 'Banned',
  55. 139: 'Server shutting down',
  56. 140: 'Bad authentication method',
  57. 141: 'Keep Alive timeout',
  58. 142: 'Session taken over',
  59. 143: 'Topic Filter invalid',
  60. 144: 'Topic Name invalid',
  61. 145: 'Packet identifier in use',
  62. 146: 'Packet Identifier not found',
  63. 147: 'Receive Maximum exceeded',
  64. 148: 'Topic Alias invalid',
  65. 149: 'Packet too large',
  66. 150: 'Message rate too high',
  67. 151: 'Quota exceeded',
  68. 152: 'Administrative action',
  69. 153: 'Payload format invalid',
  70. 154: 'Retain not supported',
  71. 155: 'QoS not supported',
  72. 156: 'Use another server',
  73. 157: 'Server moved',
  74. 158: 'Shared Subscriptions not supported',
  75. 159: 'Connection rate exceeded',
  76. 160: 'Maximum connect time',
  77. 161: 'Subscription Identifiers not supported',
  78. 162: 'Wildcard Subscriptions not supported'
  79. }
  80. function defaultId () {
  81. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  82. }
  83. function applyTopicAlias (client, packet) {
  84. if (client.options.protocolVersion === 5) {
  85. if (packet.cmd === 'publish') {
  86. let alias
  87. if (packet.properties) {
  88. alias = packet.properties.topicAlias
  89. }
  90. const topic = packet.topic.toString()
  91. if (client.topicAliasSend) {
  92. if (alias) {
  93. if (topic.length !== 0) {
  94. // register topic alias
  95. debug('applyTopicAlias :: register topic: %s - alias: %d', topic, alias)
  96. if (!client.topicAliasSend.put(topic, alias)) {
  97. debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)
  98. return new Error('Sending Topic Alias out of range')
  99. }
  100. }
  101. } else {
  102. if (topic.length !== 0) {
  103. if (client.options.autoAssignTopicAlias) {
  104. alias = client.topicAliasSend.getAliasByTopic(topic)
  105. if (alias) {
  106. packet.topic = ''
  107. packet.properties = { ...(packet.properties), topicAlias: alias }
  108. debug('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias)
  109. } else {
  110. alias = client.topicAliasSend.getLruAlias()
  111. client.topicAliasSend.put(topic, alias)
  112. packet.properties = { ...(packet.properties), topicAlias: alias }
  113. debug('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias)
  114. }
  115. } else if (client.options.autoUseTopicAlias) {
  116. alias = client.topicAliasSend.getAliasByTopic(topic)
  117. if (alias) {
  118. packet.topic = ''
  119. packet.properties = { ...(packet.properties), topicAlias: alias }
  120. debug('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias)
  121. }
  122. }
  123. }
  124. }
  125. } else if (alias) {
  126. debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)
  127. return new Error('Sending Topic Alias out of range')
  128. }
  129. }
  130. }
  131. }
  132. function removeTopicAliasAndRecoverTopicName (client, packet) {
  133. let alias
  134. if (packet.properties) {
  135. alias = packet.properties.topicAlias
  136. }
  137. let topic = packet.topic.toString()
  138. if (topic.length === 0) {
  139. // restore topic from alias
  140. if (typeof alias === 'undefined') {
  141. return new Error('Unregistered Topic Alias')
  142. } else {
  143. topic = client.topicAliasSend.getTopicByAlias(alias)
  144. if (typeof topic === 'undefined') {
  145. return new Error('Unregistered Topic Alias')
  146. } else {
  147. packet.topic = topic
  148. }
  149. }
  150. }
  151. if (alias) {
  152. delete packet.properties.topicAlias
  153. }
  154. }
  155. function sendPacket (client, packet, cb) {
  156. debug('sendPacket :: packet: %O', packet)
  157. debug('sendPacket :: emitting `packetsend`')
  158. client.emit('packetsend', packet)
  159. debug('sendPacket :: writing to stream')
  160. const result = mqttPacket.writeToStream(packet, client.stream, client.options)
  161. debug('sendPacket :: writeToStream result %s', result)
  162. if (!result && cb && cb !== nop) {
  163. debug('sendPacket :: handle events on `drain` once through callback.')
  164. client.stream.once('drain', cb)
  165. } else if (cb) {
  166. debug('sendPacket :: invoking cb')
  167. cb()
  168. }
  169. }
  170. function flush (queue) {
  171. if (queue) {
  172. debug('flush: queue exists? %b', !!(queue))
  173. Object.keys(queue).forEach(function (messageId) {
  174. if (typeof queue[messageId].cb === 'function') {
  175. queue[messageId].cb(new Error('Connection closed'))
  176. // This is suspicious. Why do we only delete this if we have a callbck?
  177. // If this is by-design, then adding no as callback would cause this to get deleted unintentionally.
  178. delete queue[messageId]
  179. }
  180. })
  181. }
  182. }
  183. function flushVolatile (queue) {
  184. if (queue) {
  185. debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')
  186. Object.keys(queue).forEach(function (messageId) {
  187. if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
  188. queue[messageId].cb(new Error('Connection closed'))
  189. delete queue[messageId]
  190. }
  191. })
  192. }
  193. }
  194. function storeAndSend (client, packet, cb, cbStorePut) {
  195. debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)
  196. let storePacket = packet
  197. let err
  198. if (storePacket.cmd === 'publish') {
  199. // The original packet is for sending.
  200. // The cloned storePacket is for storing to resend on reconnect.
  201. // Topic Alias must not be used after disconnected.
  202. storePacket = clone(packet)
  203. err = removeTopicAliasAndRecoverTopicName(client, storePacket)
  204. if (err) {
  205. return cb && cb(err)
  206. }
  207. }
  208. client.outgoingStore.put(storePacket, function storedPacket (err) {
  209. if (err) {
  210. return cb && cb(err)
  211. }
  212. cbStorePut()
  213. sendPacket(client, packet, cb)
  214. })
  215. }
  216. function nop (error) {
  217. debug('nop ::', error)
  218. }
  219. /**
  220. * MqttClient constructor
  221. *
  222. * @param {Stream} stream - stream
  223. * @param {Object} [options] - connection options
  224. * (see Connection#connect)
  225. */
  226. function MqttClient (streamBuilder, options) {
  227. let k
  228. const that = this
  229. if (!(this instanceof MqttClient)) {
  230. return new MqttClient(streamBuilder, options)
  231. }
  232. this.options = options || {}
  233. // Defaults
  234. for (k in defaultConnectOptions) {
  235. if (typeof this.options[k] === 'undefined') {
  236. this.options[k] = defaultConnectOptions[k]
  237. } else {
  238. this.options[k] = options[k]
  239. }
  240. }
  241. debug('MqttClient :: options.protocol', options.protocol)
  242. debug('MqttClient :: options.protocolVersion', options.protocolVersion)
  243. debug('MqttClient :: options.username', options.username)
  244. debug('MqttClient :: options.keepalive', options.keepalive)
  245. debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)
  246. debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)
  247. debug('MqttClient :: options.topicAliasMaximum', options.topicAliasMaximum)
  248. this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
  249. debug('MqttClient :: clientId', this.options.clientId)
  250. this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
  251. this.streamBuilder = streamBuilder
  252. this.messageIdProvider = (typeof this.options.messageIdProvider === 'undefined') ? new DefaultMessageIdProvider() : this.options.messageIdProvider
  253. // Inflight message storages
  254. this.outgoingStore = options.outgoingStore || new Store()
  255. this.incomingStore = options.incomingStore || new Store()
  256. // Should QoS zero messages be queued when the connection is broken?
  257. this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
  258. // map of subscribed topics to support reconnection
  259. this._resubscribeTopics = {}
  260. // map of a subscribe messageId and a topic
  261. this.messageIdToTopic = {}
  262. // Ping timer, setup in _setupPingTimer
  263. this.pingTimer = null
  264. // Is the client connected?
  265. this.connected = false
  266. // Are we disconnecting?
  267. this.disconnecting = false
  268. // Packet queue
  269. this.queue = []
  270. // connack timer
  271. this.connackTimer = null
  272. // Reconnect timer
  273. this.reconnectTimer = null
  274. // Is processing store?
  275. this._storeProcessing = false
  276. // Packet Ids are put into the store during store processing
  277. this._packetIdsDuringStoreProcessing = {}
  278. // Store processing queue
  279. this._storeProcessingQueue = []
  280. // Inflight callbacks
  281. this.outgoing = {}
  282. // True if connection is first time.
  283. this._firstConnection = true
  284. if (options.topicAliasMaximum > 0) {
  285. if (options.topicAliasMaximum > 0xffff) {
  286. debug('MqttClient :: options.topicAliasMaximum is out of range')
  287. } else {
  288. this.topicAliasRecv = new TopicAliasRecv(options.topicAliasMaximum)
  289. }
  290. }
  291. // Send queued packets
  292. this.on('connect', function () {
  293. const queue = this.queue
  294. function deliver () {
  295. const entry = queue.shift()
  296. debug('deliver :: entry %o', entry)
  297. let packet = null
  298. if (!entry) {
  299. that._resubscribe()
  300. return
  301. }
  302. packet = entry.packet
  303. debug('deliver :: call _sendPacket for %o', packet)
  304. let send = true
  305. if (packet.messageId && packet.messageId !== 0) {
  306. if (!that.messageIdProvider.register(packet.messageId)) {
  307. send = false
  308. }
  309. }
  310. if (send) {
  311. that._sendPacket(
  312. packet,
  313. function (err) {
  314. if (entry.cb) {
  315. entry.cb(err)
  316. }
  317. deliver()
  318. }
  319. )
  320. } else {
  321. debug('messageId: %d has already used. The message is skipped and removed.', packet.messageId)
  322. deliver()
  323. }
  324. }
  325. debug('connect :: sending queued packets')
  326. deliver()
  327. })
  328. this.on('close', function () {
  329. debug('close :: connected set to `false`')
  330. this.connected = false
  331. debug('close :: clearing connackTimer')
  332. clearTimeout(this.connackTimer)
  333. debug('close :: clearing ping timer')
  334. if (that.pingTimer !== null) {
  335. that.pingTimer.clear()
  336. that.pingTimer = null
  337. }
  338. if (this.topicAliasRecv) {
  339. this.topicAliasRecv.clear()
  340. }
  341. debug('close :: calling _setupReconnect')
  342. this._setupReconnect()
  343. })
  344. EventEmitter.call(this)
  345. debug('MqttClient :: setting up stream')
  346. this._setupStream()
  347. }
  348. inherits(MqttClient, EventEmitter)
  349. /**
  350. * setup the event handlers in the inner stream.
  351. *
  352. * @api private
  353. */
  354. MqttClient.prototype._setupStream = function () {
  355. const that = this
  356. const writable = new Writable()
  357. const parser = mqttPacket.parser(this.options)
  358. let completeParse = null
  359. const packets = []
  360. debug('_setupStream :: calling method to clear reconnect')
  361. this._clearReconnect()
  362. debug('_setupStream :: using streamBuilder provided to client to create stream')
  363. this.stream = this.streamBuilder(this)
  364. parser.on('packet', function (packet) {
  365. debug('parser :: on packet push to packets array.')
  366. packets.push(packet)
  367. })
  368. function nextTickWork () {
  369. if (packets.length) {
  370. nextTick(work)
  371. } else {
  372. const done = completeParse
  373. completeParse = null
  374. done()
  375. }
  376. }
  377. function work () {
  378. debug('work :: getting next packet in queue')
  379. const packet = packets.shift()
  380. if (packet) {
  381. debug('work :: packet pulled from queue')
  382. that._handlePacket(packet, nextTickWork)
  383. } else {
  384. debug('work :: no packets in queue')
  385. const done = completeParse
  386. completeParse = null
  387. debug('work :: done flag is %s', !!(done))
  388. if (done) done()
  389. }
  390. }
  391. writable._write = function (buf, enc, done) {
  392. completeParse = done
  393. debug('writable stream :: parsing buffer')
  394. parser.parse(buf)
  395. work()
  396. }
  397. function streamErrorHandler (error) {
  398. debug('streamErrorHandler :: error', error.message)
  399. // error.code will only be set on NodeJS env, browse don't allow to detect erros on sockets
  400. // also emitting errors on browser seems to create issues
  401. if (error.code) {
  402. // handle error
  403. debug('streamErrorHandler :: emitting error')
  404. that.emit('error', error)
  405. } else {
  406. nop(error)
  407. }
  408. }
  409. debug('_setupStream :: pipe stream to writable stream')
  410. this.stream.pipe(writable)
  411. // Suppress connection errors
  412. this.stream.on('error', streamErrorHandler)
  413. // Echo stream close
  414. this.stream.on('close', function () {
  415. debug('(%s)stream :: on close', that.options.clientId)
  416. flushVolatile(that.outgoing)
  417. debug('stream: emit close to MqttClient')
  418. that.emit('close')
  419. })
  420. // Send a connect packet
  421. debug('_setupStream: sending packet `connect`')
  422. const connectPacket = Object.create(this.options)
  423. connectPacket.cmd = 'connect'
  424. if (this.topicAliasRecv) {
  425. if (!connectPacket.properties) {
  426. connectPacket.properties = {}
  427. }
  428. if (this.topicAliasRecv) {
  429. connectPacket.properties.topicAliasMaximum = this.topicAliasRecv.max
  430. }
  431. }
  432. // avoid message queue
  433. sendPacket(this, connectPacket)
  434. // Echo connection errors
  435. parser.on('error', this.emit.bind(this, 'error'))
  436. // auth
  437. if (this.options.properties) {
  438. if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
  439. that.end(() =>
  440. this.emit('error', new Error('Packet has no Authentication Method')
  441. ))
  442. return this
  443. }
  444. if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
  445. const authPacket = xtend({ cmd: 'auth', reasonCode: 0 }, this.options.authPacket)
  446. sendPacket(this, authPacket)
  447. }
  448. }
  449. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  450. this.stream.setMaxListeners(1000)
  451. clearTimeout(this.connackTimer)
  452. this.connackTimer = setTimeout(function () {
  453. debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')
  454. that._cleanUp(true)
  455. }, this.options.connectTimeout)
  456. }
  457. MqttClient.prototype._handlePacket = function (packet, done) {
  458. const options = this.options
  459. if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
  460. this.emit('error', new Error('exceeding packets size ' + packet.cmd))
  461. this.end({ reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' } })
  462. return this
  463. }
  464. debug('_handlePacket :: emitting packetreceive')
  465. this.emit('packetreceive', packet)
  466. switch (packet.cmd) {
  467. case 'publish':
  468. this._handlePublish(packet, done)
  469. break
  470. case 'puback':
  471. case 'pubrec':
  472. case 'pubcomp':
  473. case 'suback':
  474. case 'unsuback':
  475. this._handleAck(packet)
  476. done()
  477. break
  478. case 'pubrel':
  479. this._handlePubrel(packet, done)
  480. break
  481. case 'connack':
  482. this._handleConnack(packet)
  483. done()
  484. break
  485. case 'auth':
  486. this._handleAuth(packet)
  487. done()
  488. break
  489. case 'pingresp':
  490. this._handlePingresp(packet)
  491. done()
  492. break
  493. case 'disconnect':
  494. this._handleDisconnect(packet)
  495. done()
  496. break
  497. default:
  498. // do nothing
  499. // maybe we should do an error handling
  500. // or just log it
  501. break
  502. }
  503. }
  504. MqttClient.prototype._checkDisconnecting = function (callback) {
  505. if (this.disconnecting) {
  506. if (callback && callback !== nop) {
  507. callback(new Error('client disconnecting'))
  508. } else {
  509. this.emit('error', new Error('client disconnecting'))
  510. }
  511. }
  512. return this.disconnecting
  513. }
  514. /**
  515. * publish - publish <message> to <topic>
  516. *
  517. * @param {String} topic - topic to publish to
  518. * @param {String, Buffer} message - message to publish
  519. * @param {Object} [opts] - publish options, includes:
  520. * {Number} qos - qos level to publish on
  521. * {Boolean} retain - whether or not to retain the message
  522. * {Boolean} dup - whether or not mark a message as duplicate
  523. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  524. * @param {Function} [callback] - function(err){}
  525. * called when publish succeeds or fails
  526. * @returns {MqttClient} this - for chaining
  527. * @api public
  528. *
  529. * @example client.publish('topic', 'message');
  530. * @example
  531. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  532. * @example client.publish('topic', 'message', console.log);
  533. */
  534. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  535. debug('publish :: message `%s` to topic `%s`', message, topic)
  536. const options = this.options
  537. // .publish(topic, payload, cb);
  538. if (typeof opts === 'function') {
  539. callback = opts
  540. opts = null
  541. }
  542. // default opts
  543. const defaultOpts = { qos: 0, retain: false, dup: false }
  544. opts = xtend(defaultOpts, opts)
  545. if (this._checkDisconnecting(callback)) {
  546. return this
  547. }
  548. const that = this
  549. const publishProc = function () {
  550. let messageId = 0
  551. if (opts.qos === 1 || opts.qos === 2) {
  552. messageId = that._nextId()
  553. if (messageId === null) {
  554. debug('No messageId left')
  555. return false
  556. }
  557. }
  558. const packet = {
  559. cmd: 'publish',
  560. topic: topic,
  561. payload: message,
  562. qos: opts.qos,
  563. retain: opts.retain,
  564. messageId: messageId,
  565. dup: opts.dup
  566. }
  567. if (options.protocolVersion === 5) {
  568. packet.properties = opts.properties
  569. }
  570. debug('publish :: qos', opts.qos)
  571. switch (opts.qos) {
  572. case 1:
  573. case 2:
  574. // Add to callbacks
  575. that.outgoing[packet.messageId] = {
  576. volatile: false,
  577. cb: callback || nop
  578. }
  579. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  580. that._sendPacket(packet, undefined, opts.cbStorePut)
  581. break
  582. default:
  583. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  584. that._sendPacket(packet, callback, opts.cbStorePut)
  585. break
  586. }
  587. return true
  588. }
  589. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !publishProc()) {
  590. this._storeProcessingQueue.push(
  591. {
  592. invoke: publishProc,
  593. cbStorePut: opts.cbStorePut,
  594. callback: callback
  595. }
  596. )
  597. }
  598. return this
  599. }
  600. /**
  601. * subscribe - subscribe to <topic>
  602. *
  603. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  604. * @param {Object} [opts] - optional subscription options, includes:
  605. * {Number} qos - subscribe qos level
  606. * @param {Function} [callback] - function(err, granted){} where:
  607. * {Error} err - subscription error (none at the moment!)
  608. * {Array} granted - array of {topic: 't', qos: 0}
  609. * @returns {MqttClient} this - for chaining
  610. * @api public
  611. * @example client.subscribe('topic');
  612. * @example client.subscribe('topic', {qos: 1});
  613. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  614. * @example client.subscribe('topic', console.log);
  615. */
  616. MqttClient.prototype.subscribe = function () {
  617. const that = this
  618. const args = new Array(arguments.length)
  619. for (let i = 0; i < arguments.length; i++) {
  620. args[i] = arguments[i]
  621. }
  622. const subs = []
  623. let obj = args.shift()
  624. const resubscribe = obj.resubscribe
  625. let callback = args.pop() || nop
  626. let opts = args.pop()
  627. const version = this.options.protocolVersion
  628. delete obj.resubscribe
  629. if (typeof obj === 'string') {
  630. obj = [obj]
  631. }
  632. if (typeof callback !== 'function') {
  633. opts = callback
  634. callback = nop
  635. }
  636. const invalidTopic = validations.validateTopics(obj)
  637. if (invalidTopic !== null) {
  638. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  639. return this
  640. }
  641. if (this._checkDisconnecting(callback)) {
  642. debug('subscribe: discconecting true')
  643. return this
  644. }
  645. const defaultOpts = {
  646. qos: 0
  647. }
  648. if (version === 5) {
  649. defaultOpts.nl = false
  650. defaultOpts.rap = false
  651. defaultOpts.rh = 0
  652. }
  653. opts = xtend(defaultOpts, opts)
  654. if (Array.isArray(obj)) {
  655. obj.forEach(function (topic) {
  656. debug('subscribe: array topic %s', topic)
  657. if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, topic) ||
  658. that._resubscribeTopics[topic].qos < opts.qos ||
  659. resubscribe) {
  660. const currentOpts = {
  661. topic: topic,
  662. qos: opts.qos
  663. }
  664. if (version === 5) {
  665. currentOpts.nl = opts.nl
  666. currentOpts.rap = opts.rap
  667. currentOpts.rh = opts.rh
  668. currentOpts.properties = opts.properties
  669. }
  670. debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
  671. subs.push(currentOpts)
  672. }
  673. })
  674. } else {
  675. Object
  676. .keys(obj)
  677. .forEach(function (k) {
  678. debug('subscribe: object topic %s', k)
  679. if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, k) ||
  680. that._resubscribeTopics[k].qos < obj[k].qos ||
  681. resubscribe) {
  682. const currentOpts = {
  683. topic: k,
  684. qos: obj[k].qos
  685. }
  686. if (version === 5) {
  687. currentOpts.nl = obj[k].nl
  688. currentOpts.rap = obj[k].rap
  689. currentOpts.rh = obj[k].rh
  690. currentOpts.properties = opts.properties
  691. }
  692. debug('subscribe: pushing `%s` to subs list', currentOpts)
  693. subs.push(currentOpts)
  694. }
  695. })
  696. }
  697. if (!subs.length) {
  698. callback(null, [])
  699. return this
  700. }
  701. const subscribeProc = function () {
  702. const messageId = that._nextId()
  703. if (messageId === null) {
  704. debug('No messageId left')
  705. return false
  706. }
  707. const packet = {
  708. cmd: 'subscribe',
  709. subscriptions: subs,
  710. qos: 1,
  711. retain: false,
  712. dup: false,
  713. messageId: messageId
  714. }
  715. if (opts.properties) {
  716. packet.properties = opts.properties
  717. }
  718. // subscriptions to resubscribe to in case of disconnect
  719. if (that.options.resubscribe) {
  720. debug('subscribe :: resubscribe true')
  721. const topics = []
  722. subs.forEach(function (sub) {
  723. if (that.options.reconnectPeriod > 0) {
  724. const topic = { qos: sub.qos }
  725. if (version === 5) {
  726. topic.nl = sub.nl || false
  727. topic.rap = sub.rap || false
  728. topic.rh = sub.rh || 0
  729. topic.properties = sub.properties
  730. }
  731. that._resubscribeTopics[sub.topic] = topic
  732. topics.push(sub.topic)
  733. }
  734. })
  735. that.messageIdToTopic[packet.messageId] = topics
  736. }
  737. that.outgoing[packet.messageId] = {
  738. volatile: true,
  739. cb: function (err, packet) {
  740. if (!err) {
  741. const granted = packet.granted
  742. for (let i = 0; i < granted.length; i += 1) {
  743. subs[i].qos = granted[i]
  744. }
  745. }
  746. callback(err, subs)
  747. }
  748. }
  749. debug('subscribe :: call _sendPacket')
  750. that._sendPacket(packet)
  751. return true
  752. }
  753. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) {
  754. this._storeProcessingQueue.push(
  755. {
  756. invoke: subscribeProc,
  757. callback: callback
  758. }
  759. )
  760. }
  761. return this
  762. }
  763. /**
  764. * unsubscribe - unsubscribe from topic(s)
  765. *
  766. * @param {String, Array} topic - topics to unsubscribe from
  767. * @param {Object} [opts] - optional subscription options, includes:
  768. * {Object} properties - properties of unsubscribe packet
  769. * @param {Function} [callback] - callback fired on unsuback
  770. * @returns {MqttClient} this - for chaining
  771. * @api public
  772. * @example client.unsubscribe('topic');
  773. * @example client.unsubscribe('topic', console.log);
  774. */
  775. MqttClient.prototype.unsubscribe = function () {
  776. const that = this
  777. const args = new Array(arguments.length)
  778. for (let i = 0; i < arguments.length; i++) {
  779. args[i] = arguments[i]
  780. }
  781. let topic = args.shift()
  782. let callback = args.pop() || nop
  783. let opts = args.pop()
  784. if (typeof topic === 'string') {
  785. topic = [topic]
  786. }
  787. if (typeof callback !== 'function') {
  788. opts = callback
  789. callback = nop
  790. }
  791. const invalidTopic = validations.validateTopics(topic)
  792. if (invalidTopic !== null) {
  793. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  794. return this
  795. }
  796. if (that._checkDisconnecting(callback)) {
  797. return this
  798. }
  799. const unsubscribeProc = function () {
  800. const messageId = that._nextId()
  801. if (messageId === null) {
  802. debug('No messageId left')
  803. return false
  804. }
  805. const packet = {
  806. cmd: 'unsubscribe',
  807. qos: 1,
  808. messageId: messageId
  809. }
  810. if (typeof topic === 'string') {
  811. packet.unsubscriptions = [topic]
  812. } else if (Array.isArray(topic)) {
  813. packet.unsubscriptions = topic
  814. }
  815. if (that.options.resubscribe) {
  816. packet.unsubscriptions.forEach(function (topic) {
  817. delete that._resubscribeTopics[topic]
  818. })
  819. }
  820. if (typeof opts === 'object' && opts.properties) {
  821. packet.properties = opts.properties
  822. }
  823. that.outgoing[packet.messageId] = {
  824. volatile: true,
  825. cb: callback
  826. }
  827. debug('unsubscribe: call _sendPacket')
  828. that._sendPacket(packet)
  829. return true
  830. }
  831. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) {
  832. this._storeProcessingQueue.push(
  833. {
  834. invoke: unsubscribeProc,
  835. callback: callback
  836. }
  837. )
  838. }
  839. return this
  840. }
  841. /**
  842. * end - close connection
  843. *
  844. * @returns {MqttClient} this - for chaining
  845. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  846. * @param {Object} opts - added to the disconnect packet
  847. * @param {Function} cb - called when the client has been closed
  848. *
  849. * @api public
  850. */
  851. MqttClient.prototype.end = function (force, opts, cb) {
  852. const that = this
  853. debug('end :: (%s)', this.options.clientId)
  854. if (force == null || typeof force !== 'boolean') {
  855. cb = opts || nop
  856. opts = force
  857. force = false
  858. if (typeof opts !== 'object') {
  859. cb = opts
  860. opts = null
  861. if (typeof cb !== 'function') {
  862. cb = nop
  863. }
  864. }
  865. }
  866. if (typeof opts !== 'object') {
  867. cb = opts
  868. opts = null
  869. }
  870. debug('end :: cb? %s', !!cb)
  871. cb = cb || nop
  872. function closeStores () {
  873. debug('end :: closeStores: closing incoming and outgoing stores')
  874. that.disconnected = true
  875. that.incomingStore.close(function (e1) {
  876. that.outgoingStore.close(function (e2) {
  877. debug('end :: closeStores: emitting end')
  878. that.emit('end')
  879. if (cb) {
  880. const err = e1 || e2
  881. debug('end :: closeStores: invoking callback with args')
  882. cb(err)
  883. }
  884. })
  885. })
  886. if (that._deferredReconnect) {
  887. that._deferredReconnect()
  888. }
  889. }
  890. function finish () {
  891. // defer closesStores of an I/O cycle,
  892. // just to make sure things are
  893. // ok for websockets
  894. debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
  895. that._cleanUp(force, () => {
  896. debug('end :: finish :: calling process.nextTick on closeStores')
  897. // const boundProcess = nextTick.bind(null, closeStores)
  898. nextTick(closeStores.bind(that))
  899. }, opts)
  900. }
  901. if (this.disconnecting) {
  902. cb()
  903. return this
  904. }
  905. this._clearReconnect()
  906. this.disconnecting = true
  907. if (!force && Object.keys(this.outgoing).length > 0) {
  908. // wait 10ms, just to be sure we received all of it
  909. debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
  910. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  911. } else {
  912. debug('end :: (%s) :: immediately calling finish', that.options.clientId)
  913. finish()
  914. }
  915. return this
  916. }
  917. /**
  918. * removeOutgoingMessage - remove a message in outgoing store
  919. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  920. *
  921. * @param {Number} messageId - messageId to remove message
  922. * @returns {MqttClient} this - for chaining
  923. * @api public
  924. *
  925. * @example client.removeOutgoingMessage(client.getLastAllocated());
  926. */
  927. MqttClient.prototype.removeOutgoingMessage = function (messageId) {
  928. const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  929. delete this.outgoing[messageId]
  930. this.outgoingStore.del({ messageId: messageId }, function () {
  931. cb(new Error('Message removed'))
  932. })
  933. return this
  934. }
  935. /**
  936. * reconnect - connect again using the same options as connect()
  937. *
  938. * @param {Object} [opts] - optional reconnect options, includes:
  939. * {Store} incomingStore - a store for the incoming packets
  940. * {Store} outgoingStore - a store for the outgoing packets
  941. * if opts is not given, current stores are used
  942. * @returns {MqttClient} this - for chaining
  943. *
  944. * @api public
  945. */
  946. MqttClient.prototype.reconnect = function (opts) {
  947. debug('client reconnect')
  948. const that = this
  949. const f = function () {
  950. if (opts) {
  951. that.options.incomingStore = opts.incomingStore
  952. that.options.outgoingStore = opts.outgoingStore
  953. } else {
  954. that.options.incomingStore = null
  955. that.options.outgoingStore = null
  956. }
  957. that.incomingStore = that.options.incomingStore || new Store()
  958. that.outgoingStore = that.options.outgoingStore || new Store()
  959. that.disconnecting = false
  960. that.disconnected = false
  961. that._deferredReconnect = null
  962. that._reconnect()
  963. }
  964. if (this.disconnecting && !this.disconnected) {
  965. this._deferredReconnect = f
  966. } else {
  967. f()
  968. }
  969. return this
  970. }
  971. /**
  972. * _reconnect - implement reconnection
  973. * @api privateish
  974. */
  975. MqttClient.prototype._reconnect = function () {
  976. debug('_reconnect: emitting reconnect to client')
  977. this.emit('reconnect')
  978. if (this.connected) {
  979. this.end(() => { this._setupStream() })
  980. debug('client already connected. disconnecting first.')
  981. } else {
  982. debug('_reconnect: calling _setupStream')
  983. this._setupStream()
  984. }
  985. }
  986. /**
  987. * _setupReconnect - setup reconnect timer
  988. */
  989. MqttClient.prototype._setupReconnect = function () {
  990. const that = this
  991. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  992. if (!this.reconnecting) {
  993. debug('_setupReconnect :: emit `offline` state')
  994. this.emit('offline')
  995. debug('_setupReconnect :: set `reconnecting` to `true`')
  996. this.reconnecting = true
  997. }
  998. debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
  999. that.reconnectTimer = setInterval(function () {
  1000. debug('reconnectTimer :: reconnect triggered!')
  1001. that._reconnect()
  1002. }, that.options.reconnectPeriod)
  1003. } else {
  1004. debug('_setupReconnect :: doing nothing...')
  1005. }
  1006. }
  1007. /**
  1008. * _clearReconnect - clear the reconnect timer
  1009. */
  1010. MqttClient.prototype._clearReconnect = function () {
  1011. debug('_clearReconnect : clearing reconnect timer')
  1012. if (this.reconnectTimer) {
  1013. clearInterval(this.reconnectTimer)
  1014. this.reconnectTimer = null
  1015. }
  1016. }
  1017. /**
  1018. * _cleanUp - clean up on connection end
  1019. * @api private
  1020. */
  1021. MqttClient.prototype._cleanUp = function (forced, done) {
  1022. const opts = arguments[2]
  1023. if (done) {
  1024. debug('_cleanUp :: done callback provided for on stream close')
  1025. this.stream.on('close', done)
  1026. }
  1027. debug('_cleanUp :: forced? %s', forced)
  1028. if (forced) {
  1029. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  1030. flush(this.outgoing)
  1031. }
  1032. debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
  1033. this.stream.destroy()
  1034. } else {
  1035. const packet = xtend({ cmd: 'disconnect' }, opts)
  1036. debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
  1037. this._sendPacket(
  1038. packet,
  1039. setImmediate.bind(
  1040. null,
  1041. this.stream.end.bind(this.stream)
  1042. )
  1043. )
  1044. }
  1045. if (!this.disconnecting) {
  1046. debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
  1047. this._clearReconnect()
  1048. this._setupReconnect()
  1049. }
  1050. if (this.pingTimer !== null) {
  1051. debug('_cleanUp :: clearing pingTimer')
  1052. this.pingTimer.clear()
  1053. this.pingTimer = null
  1054. }
  1055. if (done && !this.connected) {
  1056. debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
  1057. this.stream.removeListener('close', done)
  1058. done()
  1059. }
  1060. }
  1061. /**
  1062. * _sendPacket - send or queue a packet
  1063. * @param {Object} packet - packet options
  1064. * @param {Function} cb - callback when the packet is sent
  1065. * @param {Function} cbStorePut - called when message is put into outgoingStore
  1066. * @api private
  1067. */
  1068. MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
  1069. debug('_sendPacket :: (%s) :: start', this.options.clientId)
  1070. cbStorePut = cbStorePut || nop
  1071. cb = cb || nop
  1072. const err = applyTopicAlias(this, packet)
  1073. if (err) {
  1074. cb(err)
  1075. return
  1076. }
  1077. if (!this.connected) {
  1078. // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)
  1079. if (packet.cmd === 'auth') {
  1080. this._shiftPingInterval()
  1081. sendPacket(this, packet, cb)
  1082. return
  1083. }
  1084. debug('_sendPacket :: client not connected. Storing packet offline.')
  1085. this._storePacket(packet, cb, cbStorePut)
  1086. return
  1087. }
  1088. // When sending a packet, reschedule the ping timer
  1089. this._shiftPingInterval()
  1090. switch (packet.cmd) {
  1091. case 'publish':
  1092. break
  1093. case 'pubrel':
  1094. storeAndSend(this, packet, cb, cbStorePut)
  1095. return
  1096. default:
  1097. sendPacket(this, packet, cb)
  1098. return
  1099. }
  1100. switch (packet.qos) {
  1101. case 2:
  1102. case 1:
  1103. storeAndSend(this, packet, cb, cbStorePut)
  1104. break
  1105. /**
  1106. * no need of case here since it will be caught by default
  1107. * and jshint comply that before default it must be a break
  1108. * anyway it will result in -1 evaluation
  1109. */
  1110. case 0:
  1111. /* falls through */
  1112. default:
  1113. sendPacket(this, packet, cb)
  1114. break
  1115. }
  1116. debug('_sendPacket :: (%s) :: end', this.options.clientId)
  1117. }
  1118. /**
  1119. * _storePacket - queue a packet
  1120. * @param {Object} packet - packet options
  1121. * @param {Function} cb - callback when the packet is sent
  1122. * @param {Function} cbStorePut - called when message is put into outgoingStore
  1123. * @api private
  1124. */
  1125. MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
  1126. debug('_storePacket :: packet: %o', packet)
  1127. debug('_storePacket :: cb? %s', !!cb)
  1128. cbStorePut = cbStorePut || nop
  1129. let storePacket = packet
  1130. if (storePacket.cmd === 'publish') {
  1131. // The original packet is for sending.
  1132. // The cloned storePacket is for storing to resend on reconnect.
  1133. // Topic Alias must not be used after disconnected.
  1134. storePacket = clone(packet)
  1135. const err = removeTopicAliasAndRecoverTopicName(this, storePacket)
  1136. if (err) {
  1137. return cb && cb(err)
  1138. }
  1139. }
  1140. // check that the packet is not a qos of 0, or that the command is not a publish
  1141. if (((storePacket.qos || 0) === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
  1142. this.queue.push({ packet: storePacket, cb: cb })
  1143. } else if (storePacket.qos > 0) {
  1144. cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null
  1145. this.outgoingStore.put(storePacket, function (err) {
  1146. if (err) {
  1147. return cb && cb(err)
  1148. }
  1149. cbStorePut()
  1150. })
  1151. } else if (cb) {
  1152. cb(new Error('No connection to broker'))
  1153. }
  1154. }
  1155. /**
  1156. * _setupPingTimer - setup the ping timer
  1157. *
  1158. * @api private
  1159. */
  1160. MqttClient.prototype._setupPingTimer = function () {
  1161. debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
  1162. const that = this
  1163. if (!this.pingTimer && this.options.keepalive) {
  1164. this.pingResp = true
  1165. this.pingTimer = reInterval(function () {
  1166. that._checkPing()
  1167. }, this.options.keepalive * 1000)
  1168. }
  1169. }
  1170. /**
  1171. * _shiftPingInterval - reschedule the ping interval
  1172. *
  1173. * @api private
  1174. */
  1175. MqttClient.prototype._shiftPingInterval = function () {
  1176. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  1177. this.pingTimer.reschedule(this.options.keepalive * 1000)
  1178. }
  1179. }
  1180. /**
  1181. * _checkPing - check if a pingresp has come back, and ping the server again
  1182. *
  1183. * @api private
  1184. */
  1185. MqttClient.prototype._checkPing = function () {
  1186. debug('_checkPing :: checking ping...')
  1187. if (this.pingResp) {
  1188. debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
  1189. this.pingResp = false
  1190. this._sendPacket({ cmd: 'pingreq' })
  1191. } else {
  1192. // do a forced cleanup since socket will be in bad shape
  1193. debug('_checkPing :: calling _cleanUp with force true')
  1194. this._cleanUp(true)
  1195. }
  1196. }
  1197. /**
  1198. * _handlePingresp - handle a pingresp
  1199. *
  1200. * @api private
  1201. */
  1202. MqttClient.prototype._handlePingresp = function () {
  1203. this.pingResp = true
  1204. }
  1205. /**
  1206. * _handleConnack
  1207. *
  1208. * @param {Object} packet
  1209. * @api private
  1210. */
  1211. MqttClient.prototype._handleConnack = function (packet) {
  1212. debug('_handleConnack')
  1213. const options = this.options
  1214. const version = options.protocolVersion
  1215. const rc = version === 5 ? packet.reasonCode : packet.returnCode
  1216. clearTimeout(this.connackTimer)
  1217. delete this.topicAliasSend
  1218. if (packet.properties) {
  1219. if (packet.properties.topicAliasMaximum) {
  1220. if (packet.properties.topicAliasMaximum > 0xffff) {
  1221. this.emit('error', new Error('topicAliasMaximum from broker is out of range'))
  1222. return
  1223. }
  1224. if (packet.properties.topicAliasMaximum > 0) {
  1225. this.topicAliasSend = new TopicAliasSend(packet.properties.topicAliasMaximum)
  1226. }
  1227. }
  1228. if (packet.properties.serverKeepAlive && options.keepalive) {
  1229. options.keepalive = packet.properties.serverKeepAlive
  1230. this._shiftPingInterval()
  1231. }
  1232. if (packet.properties.maximumPacketSize) {
  1233. if (!options.properties) { options.properties = {} }
  1234. options.properties.maximumPacketSize = packet.properties.maximumPacketSize
  1235. }
  1236. }
  1237. if (rc === 0) {
  1238. this.reconnecting = false
  1239. this._onConnect(packet)
  1240. } else if (rc > 0) {
  1241. const err = new Error('Connection refused: ' + errors[rc])
  1242. err.code = rc
  1243. this.emit('error', err)
  1244. }
  1245. }
  1246. MqttClient.prototype._handleAuth = function (packet) {
  1247. const options = this.options
  1248. const version = options.protocolVersion
  1249. const rc = version === 5 ? packet.reasonCode : packet.returnCode
  1250. if (version !== 5) {
  1251. const err = new Error('Protocol error: Auth packets are only supported in MQTT 5. Your version:' + version)
  1252. err.code = rc
  1253. this.emit('error', err)
  1254. return
  1255. }
  1256. const that = this
  1257. this.handleAuth(packet, function (err, packet) {
  1258. if (err) {
  1259. that.emit('error', err)
  1260. return
  1261. }
  1262. if (rc === 24) {
  1263. that.reconnecting = false
  1264. that._sendPacket(packet)
  1265. } else {
  1266. const error = new Error('Connection refused: ' + errors[rc])
  1267. err.code = rc
  1268. that.emit('error', error)
  1269. }
  1270. })
  1271. }
  1272. /**
  1273. * @param packet the packet received by the broker
  1274. * @return the auth packet to be returned to the broker
  1275. * @api public
  1276. */
  1277. MqttClient.prototype.handleAuth = function (packet, callback) {
  1278. callback()
  1279. }
  1280. /**
  1281. * _handlePublish
  1282. *
  1283. * @param {Object} packet
  1284. * @api private
  1285. */
  1286. /*
  1287. those late 2 case should be rewrite to comply with coding style:
  1288. case 1:
  1289. case 0:
  1290. // do not wait sending a puback
  1291. // no callback passed
  1292. if (1 === qos) {
  1293. this._sendPacket({
  1294. cmd: 'puback',
  1295. messageId: messageId
  1296. });
  1297. }
  1298. // emit the message event for both qos 1 and 0
  1299. this.emit('message', topic, message, packet);
  1300. this.handleMessage(packet, done);
  1301. break;
  1302. default:
  1303. // do nothing but every switch mus have a default
  1304. // log or throw an error about unknown qos
  1305. break;
  1306. for now i just suppressed the warnings
  1307. */
  1308. MqttClient.prototype._handlePublish = function (packet, done) {
  1309. debug('_handlePublish: packet %o', packet)
  1310. done = typeof done !== 'undefined' ? done : nop
  1311. let topic = packet.topic.toString()
  1312. const message = packet.payload
  1313. const qos = packet.qos
  1314. const messageId = packet.messageId
  1315. const that = this
  1316. const options = this.options
  1317. const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  1318. if (this.options.protocolVersion === 5) {
  1319. let alias
  1320. if (packet.properties) {
  1321. alias = packet.properties.topicAlias
  1322. }
  1323. if (typeof alias !== 'undefined') {
  1324. if (topic.length === 0) {
  1325. if (alias > 0 && alias <= 0xffff) {
  1326. const gotTopic = this.topicAliasRecv.getTopicByAlias(alias)
  1327. if (gotTopic) {
  1328. topic = gotTopic
  1329. debug('_handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias)
  1330. } else {
  1331. debug('_handlePublish :: unregistered topic alias. alias: %d', alias)
  1332. this.emit('error', new Error('Received unregistered Topic Alias'))
  1333. return
  1334. }
  1335. } else {
  1336. debug('_handlePublish :: topic alias out of range. alias: %d', alias)
  1337. this.emit('error', new Error('Received Topic Alias is out of range'))
  1338. return
  1339. }
  1340. } else {
  1341. if (this.topicAliasRecv.put(topic, alias)) {
  1342. debug('_handlePublish :: registered topic: %s - alias: %d', topic, alias)
  1343. } else {
  1344. debug('_handlePublish :: topic alias out of range. alias: %d', alias)
  1345. this.emit('error', new Error('Received Topic Alias is out of range'))
  1346. return
  1347. }
  1348. }
  1349. }
  1350. }
  1351. debug('_handlePublish: qos %d', qos)
  1352. switch (qos) {
  1353. case 2: {
  1354. options.customHandleAcks(topic, message, packet, function (error, code) {
  1355. if (!(error instanceof Error)) {
  1356. code = error
  1357. error = null
  1358. }
  1359. if (error) { return that.emit('error', error) }
  1360. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
  1361. if (code) {
  1362. that._sendPacket({ cmd: 'pubrec', messageId: messageId, reasonCode: code }, done)
  1363. } else {
  1364. that.incomingStore.put(packet, function () {
  1365. that._sendPacket({ cmd: 'pubrec', messageId: messageId }, done)
  1366. })
  1367. }
  1368. })
  1369. break
  1370. }
  1371. case 1: {
  1372. // emit the message event
  1373. options.customHandleAcks(topic, message, packet, function (error, code) {
  1374. if (!(error instanceof Error)) {
  1375. code = error
  1376. error = null
  1377. }
  1378. if (error) { return that.emit('error', error) }
  1379. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
  1380. if (!code) { that.emit('message', topic, message, packet) }
  1381. that.handleMessage(packet, function (err) {
  1382. if (err) {
  1383. return done && done(err)
  1384. }
  1385. that._sendPacket({ cmd: 'puback', messageId: messageId, reasonCode: code }, done)
  1386. })
  1387. })
  1388. break
  1389. }
  1390. case 0:
  1391. // emit the message event
  1392. this.emit('message', topic, message, packet)
  1393. this.handleMessage(packet, done)
  1394. break
  1395. default:
  1396. // do nothing
  1397. debug('_handlePublish: unknown QoS. Doing nothing.')
  1398. // log or throw an error about unknown qos
  1399. break
  1400. }
  1401. }
  1402. /**
  1403. * Handle messages with backpressure support, one at a time.
  1404. * Override at will.
  1405. *
  1406. * @param Packet packet the packet
  1407. * @param Function callback call when finished
  1408. * @api public
  1409. */
  1410. MqttClient.prototype.handleMessage = function (packet, callback) {
  1411. callback()
  1412. }
  1413. /**
  1414. * _handleAck
  1415. *
  1416. * @param {Object} packet
  1417. * @api private
  1418. */
  1419. MqttClient.prototype._handleAck = function (packet) {
  1420. /* eslint no-fallthrough: "off" */
  1421. const messageId = packet.messageId
  1422. const type = packet.cmd
  1423. let response = null
  1424. const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  1425. const that = this
  1426. let err
  1427. // Checking `!cb` happens to work, but it's not technically "correct".
  1428. //
  1429. // Why? This code assumes that "no callback" is the same as that "we're not
  1430. // waiting for responses" (puback, pubrec, pubcomp, suback, or unsuback).
  1431. //
  1432. // It would be better to check `if (!this.outgoing[messageId])` here, but
  1433. // there's no reason to change it and risk (another) regression.
  1434. //
  1435. // The only reason this code works is becaues code in MqttClient.publish,
  1436. // MqttClinet.subscribe, and MqttClient.unsubscribe ensures that we will
  1437. // have a callback even if the user doesn't pass one in.)
  1438. if (!cb) {
  1439. debug('_handleAck :: Server sent an ack in error. Ignoring.')
  1440. // Server sent an ack in error, ignore it.
  1441. return
  1442. }
  1443. // Process
  1444. debug('_handleAck :: packet type', type)
  1445. switch (type) {
  1446. case 'pubcomp':
  1447. // same thing as puback for QoS 2
  1448. case 'puback': {
  1449. const pubackRC = packet.reasonCode
  1450. // Callback - we're done
  1451. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1452. err = new Error('Publish error: ' + errors[pubackRC])
  1453. err.code = pubackRC
  1454. cb(err, packet)
  1455. }
  1456. delete this.outgoing[messageId]
  1457. this.outgoingStore.del(packet, cb)
  1458. this.messageIdProvider.deallocate(messageId)
  1459. this._invokeStoreProcessingQueue()
  1460. break
  1461. }
  1462. case 'pubrec': {
  1463. response = {
  1464. cmd: 'pubrel',
  1465. qos: 2,
  1466. messageId: messageId
  1467. }
  1468. const pubrecRC = packet.reasonCode
  1469. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1470. err = new Error('Publish error: ' + errors[pubrecRC])
  1471. err.code = pubrecRC
  1472. cb(err, packet)
  1473. } else {
  1474. this._sendPacket(response)
  1475. }
  1476. break
  1477. }
  1478. case 'suback': {
  1479. delete this.outgoing[messageId]
  1480. this.messageIdProvider.deallocate(messageId)
  1481. for (let grantedI = 0; grantedI < packet.granted.length; grantedI++) {
  1482. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1483. // suback with Failure status
  1484. const topics = this.messageIdToTopic[messageId]
  1485. if (topics) {
  1486. topics.forEach(function (topic) {
  1487. delete that._resubscribeTopics[topic]
  1488. })
  1489. }
  1490. }
  1491. }
  1492. this._invokeStoreProcessingQueue()
  1493. cb(null, packet)
  1494. break
  1495. }
  1496. case 'unsuback': {
  1497. delete this.outgoing[messageId]
  1498. this.messageIdProvider.deallocate(messageId)
  1499. this._invokeStoreProcessingQueue()
  1500. cb(null)
  1501. break
  1502. }
  1503. default:
  1504. that.emit('error', new Error('unrecognized packet type'))
  1505. }
  1506. if (this.disconnecting &&
  1507. Object.keys(this.outgoing).length === 0) {
  1508. this.emit('outgoingEmpty')
  1509. }
  1510. }
  1511. /**
  1512. * _handlePubrel
  1513. *
  1514. * @param {Object} packet
  1515. * @api private
  1516. */
  1517. MqttClient.prototype._handlePubrel = function (packet, callback) {
  1518. debug('handling pubrel packet')
  1519. callback = typeof callback !== 'undefined' ? callback : nop
  1520. const messageId = packet.messageId
  1521. const that = this
  1522. const comp = { cmd: 'pubcomp', messageId: messageId }
  1523. that.incomingStore.get(packet, function (err, pub) {
  1524. if (!err) {
  1525. that.emit('message', pub.topic, pub.payload, pub)
  1526. that.handleMessage(pub, function (err) {
  1527. if (err) {
  1528. return callback(err)
  1529. }
  1530. that.incomingStore.del(pub, nop)
  1531. that._sendPacket(comp, callback)
  1532. })
  1533. } else {
  1534. that._sendPacket(comp, callback)
  1535. }
  1536. })
  1537. }
  1538. /**
  1539. * _handleDisconnect
  1540. *
  1541. * @param {Object} packet
  1542. * @api private
  1543. */
  1544. MqttClient.prototype._handleDisconnect = function (packet) {
  1545. this.emit('disconnect', packet)
  1546. }
  1547. /**
  1548. * _nextId
  1549. * @return unsigned int
  1550. */
  1551. MqttClient.prototype._nextId = function () {
  1552. return this.messageIdProvider.allocate()
  1553. }
  1554. /**
  1555. * getLastMessageId
  1556. * @return unsigned int
  1557. */
  1558. MqttClient.prototype.getLastMessageId = function () {
  1559. return this.messageIdProvider.getLastAllocated()
  1560. }
  1561. /**
  1562. * _resubscribe
  1563. * @api private
  1564. */
  1565. MqttClient.prototype._resubscribe = function () {
  1566. debug('_resubscribe')
  1567. const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
  1568. if (!this._firstConnection &&
  1569. (this.options.clean || (this.options.protocolVersion === 5 && !this.connackPacket.sessionPresent)) &&
  1570. _resubscribeTopicsKeys.length > 0) {
  1571. if (this.options.resubscribe) {
  1572. if (this.options.protocolVersion === 5) {
  1573. debug('_resubscribe: protocolVersion 5')
  1574. for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
  1575. const resubscribeTopic = {}
  1576. resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
  1577. resubscribeTopic.resubscribe = true
  1578. this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties })
  1579. }
  1580. } else {
  1581. this._resubscribeTopics.resubscribe = true
  1582. this.subscribe(this._resubscribeTopics)
  1583. }
  1584. } else {
  1585. this._resubscribeTopics = {}
  1586. }
  1587. }
  1588. this._firstConnection = false
  1589. }
  1590. /**
  1591. * _onConnect
  1592. *
  1593. * @api private
  1594. */
  1595. MqttClient.prototype._onConnect = function (packet) {
  1596. if (this.disconnected) {
  1597. this.emit('connect', packet)
  1598. return
  1599. }
  1600. const that = this
  1601. this.connackPacket = packet
  1602. this.messageIdProvider.clear()
  1603. this._setupPingTimer()
  1604. this.connected = true
  1605. function startStreamProcess () {
  1606. let outStore = that.outgoingStore.createStream()
  1607. function clearStoreProcessing () {
  1608. that._storeProcessing = false
  1609. that._packetIdsDuringStoreProcessing = {}
  1610. }
  1611. that.once('close', remove)
  1612. outStore.on('error', function (err) {
  1613. clearStoreProcessing()
  1614. that._flushStoreProcessingQueue()
  1615. that.removeListener('close', remove)
  1616. that.emit('error', err)
  1617. })
  1618. function remove () {
  1619. outStore.destroy()
  1620. outStore = null
  1621. that._flushStoreProcessingQueue()
  1622. clearStoreProcessing()
  1623. }
  1624. function storeDeliver () {
  1625. // edge case, we wrapped this twice
  1626. if (!outStore) {
  1627. return
  1628. }
  1629. that._storeProcessing = true
  1630. const packet = outStore.read(1)
  1631. let cb
  1632. if (!packet) {
  1633. // read when data is available in the future
  1634. outStore.once('readable', storeDeliver)
  1635. return
  1636. }
  1637. // Skip already processed store packets
  1638. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1639. storeDeliver()
  1640. return
  1641. }
  1642. // Avoid unnecessary stream read operations when disconnected
  1643. if (!that.disconnecting && !that.reconnectTimer) {
  1644. cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
  1645. that.outgoing[packet.messageId] = {
  1646. volatile: false,
  1647. cb: function (err, status) {
  1648. // Ensure that the original callback passed in to publish gets invoked
  1649. if (cb) {
  1650. cb(err, status)
  1651. }
  1652. storeDeliver()
  1653. }
  1654. }
  1655. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1656. if (that.messageIdProvider.register(packet.messageId)) {
  1657. that._sendPacket(packet)
  1658. } else {
  1659. debug('messageId: %d has already used.', packet.messageId)
  1660. }
  1661. } else if (outStore.destroy) {
  1662. outStore.destroy()
  1663. }
  1664. }
  1665. outStore.on('end', function () {
  1666. let allProcessed = true
  1667. for (const id in that._packetIdsDuringStoreProcessing) {
  1668. if (!that._packetIdsDuringStoreProcessing[id]) {
  1669. allProcessed = false
  1670. break
  1671. }
  1672. }
  1673. if (allProcessed) {
  1674. clearStoreProcessing()
  1675. that.removeListener('close', remove)
  1676. that._invokeAllStoreProcessingQueue()
  1677. that.emit('connect', packet)
  1678. } else {
  1679. startStreamProcess()
  1680. }
  1681. })
  1682. storeDeliver()
  1683. }
  1684. // start flowing
  1685. startStreamProcess()
  1686. }
  1687. MqttClient.prototype._invokeStoreProcessingQueue = function () {
  1688. if (this._storeProcessingQueue.length > 0) {
  1689. const f = this._storeProcessingQueue[0]
  1690. if (f && f.invoke()) {
  1691. this._storeProcessingQueue.shift()
  1692. return true
  1693. }
  1694. }
  1695. return false
  1696. }
  1697. MqttClient.prototype._invokeAllStoreProcessingQueue = function () {
  1698. while (this._invokeStoreProcessingQueue()) { /* empty */ }
  1699. }
  1700. MqttClient.prototype._flushStoreProcessingQueue = function () {
  1701. for (const f of this._storeProcessingQueue) {
  1702. if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))
  1703. if (f.callback) f.callback(new Error('Connection closed'))
  1704. }
  1705. this._storeProcessingQueue.splice(0)
  1706. }
  1707. module.exports = MqttClient
  1708. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1709. },{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,"_process":50,"debug":18,"events":22,"inherits":24,"mqtt-packet":40,"readable-stream":69,"reinterval":70,"rfdc/default":71,"xtend":81}],2:[function(require,module,exports){
  1710. 'use strict'
  1711. const { Buffer } = require('buffer')
  1712. const Transform = require('readable-stream').Transform
  1713. const duplexify = require('duplexify')
  1714. /* global FileReader */
  1715. let my
  1716. let proxy
  1717. let stream
  1718. let isInitialized = false
  1719. function buildProxy () {
  1720. const proxy = new Transform()
  1721. proxy._write = function (chunk, encoding, next) {
  1722. my.sendSocketMessage({
  1723. data: chunk.buffer,
  1724. success: function () {
  1725. next()
  1726. },
  1727. fail: function () {
  1728. next(new Error())
  1729. }
  1730. })
  1731. }
  1732. proxy._flush = function socketEnd (done) {
  1733. my.closeSocket({
  1734. success: function () {
  1735. done()
  1736. }
  1737. })
  1738. }
  1739. return proxy
  1740. }
  1741. function setDefaultOpts (opts) {
  1742. if (!opts.hostname) {
  1743. opts.hostname = 'localhost'
  1744. }
  1745. if (!opts.path) {
  1746. opts.path = '/'
  1747. }
  1748. if (!opts.wsOptions) {
  1749. opts.wsOptions = {}
  1750. }
  1751. }
  1752. function buildUrl (opts, client) {
  1753. const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1754. let url = protocol + '://' + opts.hostname + opts.path
  1755. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1756. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1757. }
  1758. if (typeof (opts.transformWsUrl) === 'function') {
  1759. url = opts.transformWsUrl(url, opts, client)
  1760. }
  1761. return url
  1762. }
  1763. function bindEventHandler () {
  1764. if (isInitialized) return
  1765. isInitialized = true
  1766. my.onSocketOpen(function () {
  1767. stream.setReadable(proxy)
  1768. stream.setWritable(proxy)
  1769. stream.emit('connect')
  1770. })
  1771. my.onSocketMessage(function (res) {
  1772. if (typeof res.data === 'string') {
  1773. const buffer = Buffer.from(res.data, 'base64')
  1774. proxy.push(buffer)
  1775. } else {
  1776. const reader = new FileReader()
  1777. reader.addEventListener('load', function () {
  1778. let data = reader.result
  1779. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1780. else data = Buffer.from(data, 'utf8')
  1781. proxy.push(data)
  1782. })
  1783. reader.readAsArrayBuffer(res.data)
  1784. }
  1785. })
  1786. my.onSocketClose(function () {
  1787. stream.end()
  1788. stream.destroy()
  1789. })
  1790. my.onSocketError(function (res) {
  1791. stream.destroy(res)
  1792. })
  1793. }
  1794. function buildStream (client, opts) {
  1795. opts.hostname = opts.hostname || opts.host
  1796. if (!opts.hostname) {
  1797. throw new Error('Could not determine host. Specify host manually.')
  1798. }
  1799. const websocketSubProtocol =
  1800. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1801. ? 'mqttv3.1'
  1802. : 'mqtt'
  1803. setDefaultOpts(opts)
  1804. const url = buildUrl(opts, client)
  1805. my = opts.my
  1806. my.connectSocket({
  1807. url: url,
  1808. protocols: websocketSubProtocol
  1809. })
  1810. proxy = buildProxy()
  1811. stream = duplexify.obj()
  1812. bindEventHandler()
  1813. return stream
  1814. }
  1815. module.exports = buildStream
  1816. },{"buffer":17,"duplexify":20,"readable-stream":69}],3:[function(require,module,exports){
  1817. 'use strict'
  1818. const net = require('net')
  1819. const debug = require('debug')('mqttjs:tcp')
  1820. /*
  1821. variables port and host can be removed since
  1822. you have all required information in opts object
  1823. */
  1824. function streamBuilder (client, opts) {
  1825. opts.port = opts.port || 1883
  1826. opts.hostname = opts.hostname || opts.host || 'localhost'
  1827. const port = opts.port
  1828. const host = opts.hostname
  1829. debug('port %d and host %s', port, host)
  1830. return net.createConnection(port, host)
  1831. }
  1832. module.exports = streamBuilder
  1833. },{"debug":18,"net":16}],4:[function(require,module,exports){
  1834. 'use strict'
  1835. const tls = require('tls')
  1836. const net = require('net')
  1837. const debug = require('debug')('mqttjs:tls')
  1838. function buildBuilder (mqttClient, opts) {
  1839. opts.port = opts.port || 8883
  1840. opts.host = opts.hostname || opts.host || 'localhost'
  1841. if (net.isIP(opts.host) === 0) {
  1842. opts.servername = opts.host
  1843. }
  1844. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1845. delete opts.path
  1846. debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)
  1847. const connection = tls.connect(opts)
  1848. /* eslint no-use-before-define: [2, "nofunc"] */
  1849. connection.on('secureConnect', function () {
  1850. if (opts.rejectUnauthorized && !connection.authorized) {
  1851. connection.emit('error', new Error('TLS not authorized'))
  1852. } else {
  1853. connection.removeListener('error', handleTLSerrors)
  1854. }
  1855. })
  1856. function handleTLSerrors (err) {
  1857. // How can I get verify this error is a tls error?
  1858. if (opts.rejectUnauthorized) {
  1859. mqttClient.emit('error', err)
  1860. }
  1861. // close this connection to match the behaviour of net
  1862. // otherwise all we get is an error from the connection
  1863. // and close event doesn't fire. This is a work around
  1864. // to enable the reconnect code to work the same as with
  1865. // net.createConnection
  1866. connection.end()
  1867. }
  1868. connection.on('error', handleTLSerrors)
  1869. return connection
  1870. }
  1871. module.exports = buildBuilder
  1872. },{"debug":18,"net":16,"tls":16}],5:[function(require,module,exports){
  1873. (function (process){(function (){
  1874. 'use strict'
  1875. const { Buffer } = require('buffer')
  1876. const WS = require('ws')
  1877. const debug = require('debug')('mqttjs:ws')
  1878. const duplexify = require('duplexify')
  1879. const Transform = require('readable-stream').Transform
  1880. const WSS_OPTIONS = [
  1881. 'rejectUnauthorized',
  1882. 'ca',
  1883. 'cert',
  1884. 'key',
  1885. 'pfx',
  1886. 'passphrase'
  1887. ]
  1888. // eslint-disable-next-line camelcase
  1889. const IS_BROWSER = (typeof process !== 'undefined' && process.title === 'browser') || typeof __webpack_require__ === 'function'
  1890. function buildUrl (opts, client) {
  1891. let url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1892. if (typeof (opts.transformWsUrl) === 'function') {
  1893. url = opts.transformWsUrl(url, opts, client)
  1894. }
  1895. return url
  1896. }
  1897. function setDefaultOpts (opts) {
  1898. const options = opts
  1899. if (!opts.hostname) {
  1900. options.hostname = 'localhost'
  1901. }
  1902. if (!opts.port) {
  1903. if (opts.protocol === 'wss') {
  1904. options.port = 443
  1905. } else {
  1906. options.port = 80
  1907. }
  1908. }
  1909. if (!opts.path) {
  1910. options.path = '/'
  1911. }
  1912. if (!opts.wsOptions) {
  1913. options.wsOptions = {}
  1914. }
  1915. if (!IS_BROWSER && opts.protocol === 'wss') {
  1916. // Add cert/key/ca etc options
  1917. WSS_OPTIONS.forEach(function (prop) {
  1918. if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {
  1919. options.wsOptions[prop] = opts[prop]
  1920. }
  1921. })
  1922. }
  1923. return options
  1924. }
  1925. function setDefaultBrowserOpts (opts) {
  1926. const options = setDefaultOpts(opts)
  1927. if (!options.hostname) {
  1928. options.hostname = options.host
  1929. }
  1930. if (!options.hostname) {
  1931. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1932. // can not determine the `hostname` automatically. If connecting to
  1933. // localhost, please supply the `hostname` as an argument.
  1934. if (typeof (document) === 'undefined') {
  1935. throw new Error('Could not determine host. Specify host manually.')
  1936. }
  1937. const parsed = new URL(document.URL)
  1938. options.hostname = parsed.hostname
  1939. if (!options.port) {
  1940. options.port = parsed.port
  1941. }
  1942. }
  1943. // objectMode should be defined for logic
  1944. if (options.objectMode === undefined) {
  1945. options.objectMode = !(options.binary === true || options.binary === undefined)
  1946. }
  1947. return options
  1948. }
  1949. function createWebSocket (client, url, opts) {
  1950. debug('createWebSocket')
  1951. debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)
  1952. const websocketSubProtocol =
  1953. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1954. ? 'mqttv3.1'
  1955. : 'mqtt'
  1956. debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)
  1957. const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)
  1958. return socket
  1959. }
  1960. function createBrowserWebSocket (client, opts) {
  1961. const websocketSubProtocol =
  1962. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1963. ? 'mqttv3.1'
  1964. : 'mqtt'
  1965. const url = buildUrl(opts, client)
  1966. /* global WebSocket */
  1967. const socket = new WebSocket(url, [websocketSubProtocol])
  1968. socket.binaryType = 'arraybuffer'
  1969. return socket
  1970. }
  1971. function streamBuilder (client, opts) {
  1972. debug('streamBuilder')
  1973. const options = setDefaultOpts(opts)
  1974. const url = buildUrl(options, client)
  1975. const socket = createWebSocket(client, url, options)
  1976. const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)
  1977. webSocketStream.url = url
  1978. socket.on('close', () => { webSocketStream.destroy() })
  1979. return webSocketStream
  1980. }
  1981. function browserStreamBuilder (client, opts) {
  1982. debug('browserStreamBuilder')
  1983. let stream
  1984. const options = setDefaultBrowserOpts(opts)
  1985. // sets the maximum socket buffer size before throttling
  1986. const bufferSize = options.browserBufferSize || 1024 * 512
  1987. const bufferTimeout = opts.browserBufferTimeout || 1000
  1988. const coerceToBuffer = !opts.objectMode
  1989. const socket = createBrowserWebSocket(client, opts)
  1990. const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)
  1991. if (!opts.objectMode) {
  1992. proxy._writev = writev
  1993. }
  1994. proxy.on('close', () => { socket.close() })
  1995. const eventListenerSupport = (typeof socket.addEventListener !== 'undefined')
  1996. // was already open when passed in
  1997. if (socket.readyState === socket.OPEN) {
  1998. stream = proxy
  1999. } else {
  2000. stream = stream = duplexify(undefined, undefined, opts)
  2001. if (!opts.objectMode) {
  2002. stream._writev = writev
  2003. }
  2004. if (eventListenerSupport) {
  2005. socket.addEventListener('open', onopen)
  2006. } else {
  2007. socket.onopen = onopen
  2008. }
  2009. }
  2010. stream.socket = socket
  2011. if (eventListenerSupport) {
  2012. socket.addEventListener('close', onclose)
  2013. socket.addEventListener('error', onerror)
  2014. socket.addEventListener('message', onmessage)
  2015. } else {
  2016. socket.onclose = onclose
  2017. socket.onerror = onerror
  2018. socket.onmessage = onmessage
  2019. }
  2020. // methods for browserStreamBuilder
  2021. function buildProxy (options, socketWrite, socketEnd) {
  2022. const proxy = new Transform({
  2023. objectModeMode: options.objectMode
  2024. })
  2025. proxy._write = socketWrite
  2026. proxy._flush = socketEnd
  2027. return proxy
  2028. }
  2029. function onopen () {
  2030. stream.setReadable(proxy)
  2031. stream.setWritable(proxy)
  2032. stream.emit('connect')
  2033. }
  2034. function onclose () {
  2035. stream.end()
  2036. stream.destroy()
  2037. }
  2038. function onerror (err) {
  2039. stream.destroy(err)
  2040. }
  2041. function onmessage (event) {
  2042. let data = event.data
  2043. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2044. else data = Buffer.from(data, 'utf8')
  2045. proxy.push(data)
  2046. }
  2047. // this is to be enabled only if objectMode is false
  2048. function writev (chunks, cb) {
  2049. const buffers = new Array(chunks.length)
  2050. for (let i = 0; i < chunks.length; i++) {
  2051. if (typeof chunks[i].chunk === 'string') {
  2052. buffers[i] = Buffer.from(chunks[i], 'utf8')
  2053. } else {
  2054. buffers[i] = chunks[i].chunk
  2055. }
  2056. }
  2057. this._write(Buffer.concat(buffers), 'binary', cb)
  2058. }
  2059. function socketWriteBrowser (chunk, enc, next) {
  2060. if (socket.bufferedAmount > bufferSize) {
  2061. // throttle data until buffered amount is reduced.
  2062. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  2063. }
  2064. if (coerceToBuffer && typeof chunk === 'string') {
  2065. chunk = Buffer.from(chunk, 'utf8')
  2066. }
  2067. try {
  2068. socket.send(chunk)
  2069. } catch (err) {
  2070. return next(err)
  2071. }
  2072. next()
  2073. }
  2074. function socketEndBrowser (done) {
  2075. socket.close()
  2076. done()
  2077. }
  2078. // end methods for browserStreamBuilder
  2079. return stream
  2080. }
  2081. if (IS_BROWSER) {
  2082. module.exports = browserStreamBuilder
  2083. } else {
  2084. module.exports = streamBuilder
  2085. }
  2086. }).call(this)}).call(this,require('_process'))
  2087. },{"_process":50,"buffer":17,"debug":18,"duplexify":20,"readable-stream":69,"ws":80}],6:[function(require,module,exports){
  2088. 'use strict'
  2089. const { Buffer } = require('buffer')
  2090. const Transform = require('readable-stream').Transform
  2091. const duplexify = require('duplexify')
  2092. /* global wx */
  2093. let socketTask, proxy, stream
  2094. function buildProxy () {
  2095. const proxy = new Transform()
  2096. proxy._write = function (chunk, encoding, next) {
  2097. socketTask.send({
  2098. data: chunk.buffer,
  2099. success: function () {
  2100. next()
  2101. },
  2102. fail: function (errMsg) {
  2103. next(new Error(errMsg))
  2104. }
  2105. })
  2106. }
  2107. proxy._flush = function socketEnd (done) {
  2108. socketTask.close({
  2109. success: function () {
  2110. done()
  2111. }
  2112. })
  2113. }
  2114. return proxy
  2115. }
  2116. function setDefaultOpts (opts) {
  2117. if (!opts.hostname) {
  2118. opts.hostname = 'localhost'
  2119. }
  2120. if (!opts.path) {
  2121. opts.path = '/'
  2122. }
  2123. if (!opts.wsOptions) {
  2124. opts.wsOptions = {}
  2125. }
  2126. }
  2127. function buildUrl (opts, client) {
  2128. const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  2129. let url = protocol + '://' + opts.hostname + opts.path
  2130. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  2131. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  2132. }
  2133. if (typeof (opts.transformWsUrl) === 'function') {
  2134. url = opts.transformWsUrl(url, opts, client)
  2135. }
  2136. return url
  2137. }
  2138. function bindEventHandler () {
  2139. socketTask.onOpen(function () {
  2140. stream.setReadable(proxy)
  2141. stream.setWritable(proxy)
  2142. stream.emit('connect')
  2143. })
  2144. socketTask.onMessage(function (res) {
  2145. let data = res.data
  2146. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2147. else data = Buffer.from(data, 'utf8')
  2148. proxy.push(data)
  2149. })
  2150. socketTask.onClose(function () {
  2151. stream.end()
  2152. stream.destroy()
  2153. })
  2154. socketTask.onError(function (res) {
  2155. stream.destroy(new Error(res.errMsg))
  2156. })
  2157. }
  2158. function buildStream (client, opts) {
  2159. opts.hostname = opts.hostname || opts.host
  2160. if (!opts.hostname) {
  2161. throw new Error('Could not determine host. Specify host manually.')
  2162. }
  2163. const websocketSubProtocol =
  2164. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  2165. ? 'mqttv3.1'
  2166. : 'mqtt'
  2167. setDefaultOpts(opts)
  2168. const url = buildUrl(opts, client)
  2169. socketTask = wx.connectSocket({
  2170. url: url,
  2171. protocols: [websocketSubProtocol]
  2172. })
  2173. proxy = buildProxy()
  2174. stream = duplexify.obj()
  2175. stream._destroy = function (err, cb) {
  2176. socketTask.close({
  2177. success: function () {
  2178. cb && cb(err)
  2179. }
  2180. })
  2181. }
  2182. const destroyRef = stream.destroy
  2183. stream.destroy = function () {
  2184. stream.destroy = destroyRef
  2185. const self = this
  2186. setTimeout(function () {
  2187. socketTask.close({
  2188. fail: function () {
  2189. self._destroy(new Error())
  2190. }
  2191. })
  2192. }, 0)
  2193. }.bind(stream)
  2194. bindEventHandler()
  2195. return stream
  2196. }
  2197. module.exports = buildStream
  2198. },{"buffer":17,"duplexify":20,"readable-stream":69}],7:[function(require,module,exports){
  2199. 'use strict'
  2200. /**
  2201. * DefaultMessageAllocator constructor
  2202. * @constructor
  2203. */
  2204. function DefaultMessageIdProvider () {
  2205. if (!(this instanceof DefaultMessageIdProvider)) {
  2206. return new DefaultMessageIdProvider()
  2207. }
  2208. /**
  2209. * MessageIDs starting with 1
  2210. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  2211. */
  2212. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  2213. }
  2214. /**
  2215. * allocate
  2216. *
  2217. * Get the next messageId.
  2218. * @return unsigned int
  2219. */
  2220. DefaultMessageIdProvider.prototype.allocate = function () {
  2221. // id becomes current state of this.nextId and increments afterwards
  2222. const id = this.nextId++
  2223. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  2224. if (this.nextId === 65536) {
  2225. this.nextId = 1
  2226. }
  2227. return id
  2228. }
  2229. /**
  2230. * getLastAllocated
  2231. * Get the last allocated messageId.
  2232. * @return unsigned int
  2233. */
  2234. DefaultMessageIdProvider.prototype.getLastAllocated = function () {
  2235. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  2236. }
  2237. /**
  2238. * register
  2239. * Register messageId. If success return true, otherwise return false.
  2240. * @param { unsigned int } - messageId to register,
  2241. * @return boolean
  2242. */
  2243. DefaultMessageIdProvider.prototype.register = function (messageId) {
  2244. return true
  2245. }
  2246. /**
  2247. * deallocate
  2248. * Deallocate messageId.
  2249. * @param { unsigned int } - messageId to deallocate,
  2250. */
  2251. DefaultMessageIdProvider.prototype.deallocate = function (messageId) {
  2252. }
  2253. /**
  2254. * clear
  2255. * Deallocate all messageIds.
  2256. */
  2257. DefaultMessageIdProvider.prototype.clear = function () {
  2258. }
  2259. module.exports = DefaultMessageIdProvider
  2260. },{}],8:[function(require,module,exports){
  2261. 'use strict'
  2262. /**
  2263. * Module dependencies
  2264. */
  2265. const xtend = require('xtend')
  2266. const Readable = require('readable-stream').Readable
  2267. const streamsOpts = { objectMode: true }
  2268. const defaultStoreOptions = {
  2269. clean: true
  2270. }
  2271. /**
  2272. * In-memory implementation of the message store
  2273. * This can actually be saved into files.
  2274. *
  2275. * @param {Object} [options] - store options
  2276. */
  2277. function Store (options) {
  2278. if (!(this instanceof Store)) {
  2279. return new Store(options)
  2280. }
  2281. this.options = options || {}
  2282. // Defaults
  2283. this.options = xtend(defaultStoreOptions, options)
  2284. this._inflights = new Map()
  2285. }
  2286. /**
  2287. * Adds a packet to the store, a packet is
  2288. * anything that has a messageId property.
  2289. *
  2290. */
  2291. Store.prototype.put = function (packet, cb) {
  2292. this._inflights.set(packet.messageId, packet)
  2293. if (cb) {
  2294. cb()
  2295. }
  2296. return this
  2297. }
  2298. /**
  2299. * Creates a stream with all the packets in the store
  2300. *
  2301. */
  2302. Store.prototype.createStream = function () {
  2303. const stream = new Readable(streamsOpts)
  2304. const values = []
  2305. let destroyed = false
  2306. let i = 0
  2307. this._inflights.forEach(function (value, key) {
  2308. values.push(value)
  2309. })
  2310. stream._read = function () {
  2311. if (!destroyed && i < values.length) {
  2312. this.push(values[i++])
  2313. } else {
  2314. this.push(null)
  2315. }
  2316. }
  2317. stream.destroy = function () {
  2318. if (destroyed) {
  2319. return
  2320. }
  2321. const self = this
  2322. destroyed = true
  2323. setTimeout(function () {
  2324. self.emit('close')
  2325. }, 0)
  2326. }
  2327. return stream
  2328. }
  2329. /**
  2330. * deletes a packet from the store.
  2331. */
  2332. Store.prototype.del = function (packet, cb) {
  2333. packet = this._inflights.get(packet.messageId)
  2334. if (packet) {
  2335. this._inflights.delete(packet.messageId)
  2336. cb(null, packet)
  2337. } else if (cb) {
  2338. cb(new Error('missing packet'))
  2339. }
  2340. return this
  2341. }
  2342. /**
  2343. * get a packet from the store.
  2344. */
  2345. Store.prototype.get = function (packet, cb) {
  2346. packet = this._inflights.get(packet.messageId)
  2347. if (packet) {
  2348. cb(null, packet)
  2349. } else if (cb) {
  2350. cb(new Error('missing packet'))
  2351. }
  2352. return this
  2353. }
  2354. /**
  2355. * Close the store
  2356. */
  2357. Store.prototype.close = function (cb) {
  2358. if (this.options.clean) {
  2359. this._inflights = null
  2360. }
  2361. if (cb) {
  2362. cb()
  2363. }
  2364. }
  2365. module.exports = Store
  2366. },{"readable-stream":69,"xtend":81}],9:[function(require,module,exports){
  2367. 'use strict'
  2368. /**
  2369. * Topic Alias receiving manager
  2370. * This holds alias to topic map
  2371. * @param {Number} [max] - topic alias maximum entries
  2372. */
  2373. function TopicAliasRecv (max) {
  2374. if (!(this instanceof TopicAliasRecv)) {
  2375. return new TopicAliasRecv(max)
  2376. }
  2377. this.aliasToTopic = {}
  2378. this.max = max
  2379. }
  2380. /**
  2381. * Insert or update topic - alias entry.
  2382. * @param {String} [topic] - topic
  2383. * @param {Number} [alias] - topic alias
  2384. * @returns {Boolean} - if success return true otherwise false
  2385. */
  2386. TopicAliasRecv.prototype.put = function (topic, alias) {
  2387. if (alias === 0 || alias > this.max) {
  2388. return false
  2389. }
  2390. this.aliasToTopic[alias] = topic
  2391. this.length = Object.keys(this.aliasToTopic).length
  2392. return true
  2393. }
  2394. /**
  2395. * Get topic by alias
  2396. * @param {String} [topic] - topic
  2397. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  2398. */
  2399. TopicAliasRecv.prototype.getTopicByAlias = function (alias) {
  2400. return this.aliasToTopic[alias]
  2401. }
  2402. /**
  2403. * Clear all entries
  2404. */
  2405. TopicAliasRecv.prototype.clear = function () {
  2406. this.aliasToTopic = {}
  2407. }
  2408. module.exports = TopicAliasRecv
  2409. },{}],10:[function(require,module,exports){
  2410. 'use strict'
  2411. /**
  2412. * Module dependencies
  2413. */
  2414. const LruMap = require('lru-cache')
  2415. const NumberAllocator = require('number-allocator').NumberAllocator
  2416. /**
  2417. * Topic Alias sending manager
  2418. * This holds both topic to alias and alias to topic map
  2419. * @param {Number} [max] - topic alias maximum entries
  2420. */
  2421. function TopicAliasSend (max) {
  2422. if (!(this instanceof TopicAliasSend)) {
  2423. return new TopicAliasSend(max)
  2424. }
  2425. if (max > 0) {
  2426. this.aliasToTopic = new LruMap({ max: max })
  2427. this.topicToAlias = {}
  2428. this.numberAllocator = new NumberAllocator(1, max)
  2429. this.max = max
  2430. this.length = 0
  2431. }
  2432. }
  2433. /**
  2434. * Insert or update topic - alias entry.
  2435. * @param {String} [topic] - topic
  2436. * @param {Number} [alias] - topic alias
  2437. * @returns {Boolean} - if success return true otherwise false
  2438. */
  2439. TopicAliasSend.prototype.put = function (topic, alias) {
  2440. if (alias === 0 || alias > this.max) {
  2441. return false
  2442. }
  2443. const entry = this.aliasToTopic.get(alias)
  2444. if (entry) {
  2445. delete this.topicToAlias[entry]
  2446. }
  2447. this.aliasToTopic.set(alias, topic)
  2448. this.topicToAlias[topic] = alias
  2449. this.numberAllocator.use(alias)
  2450. this.length = this.aliasToTopic.length
  2451. return true
  2452. }
  2453. /**
  2454. * Get topic by alias
  2455. * @param {Number} [alias] - topic alias
  2456. * @returns {String} - if mapped topic exists return topic, otherwise return undefined
  2457. */
  2458. TopicAliasSend.prototype.getTopicByAlias = function (alias) {
  2459. return this.aliasToTopic.get(alias)
  2460. }
  2461. /**
  2462. * Get topic by alias
  2463. * @param {String} [topic] - topic
  2464. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  2465. */
  2466. TopicAliasSend.prototype.getAliasByTopic = function (topic) {
  2467. const alias = this.topicToAlias[topic]
  2468. if (typeof alias !== 'undefined') {
  2469. this.aliasToTopic.get(alias) // LRU update
  2470. }
  2471. return alias
  2472. }
  2473. /**
  2474. * Clear all entries
  2475. */
  2476. TopicAliasSend.prototype.clear = function () {
  2477. this.aliasToTopic.reset()
  2478. this.topicToAlias = {}
  2479. this.numberAllocator.clear()
  2480. this.length = 0
  2481. }
  2482. /**
  2483. * Get Least Recently Used (LRU) topic alias
  2484. * @returns {Number} - if vacant alias exists then return it, otherwise then return LRU alias
  2485. */
  2486. TopicAliasSend.prototype.getLruAlias = function () {
  2487. const alias = this.numberAllocator.firstVacant()
  2488. if (alias) return alias
  2489. return this.aliasToTopic.keys()[this.aliasToTopic.length - 1]
  2490. }
  2491. module.exports = TopicAliasSend
  2492. },{"lru-cache":37,"number-allocator":46}],11:[function(require,module,exports){
  2493. 'use strict'
  2494. /**
  2495. * Validate a topic to see if it's valid or not.
  2496. * A topic is valid if it follow below rules:
  2497. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  2498. * - Rule #2: Part `#` must be located at the end of the mailbox
  2499. *
  2500. * @param {String} topic - A topic
  2501. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  2502. */
  2503. function validateTopic (topic) {
  2504. const parts = topic.split('/')
  2505. for (let i = 0; i < parts.length; i++) {
  2506. if (parts[i] === '+') {
  2507. continue
  2508. }
  2509. if (parts[i] === '#') {
  2510. // for Rule #2
  2511. return i === parts.length - 1
  2512. }
  2513. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  2514. return false
  2515. }
  2516. }
  2517. return true
  2518. }
  2519. /**
  2520. * Validate an array of topics to see if any of them is valid or not
  2521. * @param {Array} topics - Array of topics
  2522. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  2523. */
  2524. function validateTopics (topics) {
  2525. if (topics.length === 0) {
  2526. return 'empty_topic_list'
  2527. }
  2528. for (let i = 0; i < topics.length; i++) {
  2529. if (!validateTopic(topics[i])) {
  2530. return topics[i]
  2531. }
  2532. }
  2533. return null
  2534. }
  2535. module.exports = {
  2536. validateTopics: validateTopics
  2537. }
  2538. },{}],12:[function(require,module,exports){
  2539. (function (process){(function (){
  2540. 'use strict'
  2541. const MqttClient = require('../client')
  2542. const Store = require('../store')
  2543. const url = require('url')
  2544. const xtend = require('xtend')
  2545. const debug = require('debug')('mqttjs')
  2546. const protocols = {}
  2547. // eslint-disable-next-line camelcase
  2548. if ((typeof process !== 'undefined' && process.title !== 'browser') || typeof __webpack_require__ !== 'function') {
  2549. protocols.mqtt = require('./tcp')
  2550. protocols.tcp = require('./tcp')
  2551. protocols.ssl = require('./tls')
  2552. protocols.tls = require('./tls')
  2553. protocols.mqtts = require('./tls')
  2554. } else {
  2555. protocols.wx = require('./wx')
  2556. protocols.wxs = require('./wx')
  2557. protocols.ali = require('./ali')
  2558. protocols.alis = require('./ali')
  2559. }
  2560. protocols.ws = require('./ws')
  2561. protocols.wss = require('./ws')
  2562. /**
  2563. * Parse the auth attribute and merge username and password in the options object.
  2564. *
  2565. * @param {Object} [opts] option object
  2566. */
  2567. function parseAuthOptions (opts) {
  2568. let matches
  2569. if (opts.auth) {
  2570. matches = opts.auth.match(/^(.+):(.+)$/)
  2571. if (matches) {
  2572. opts.username = matches[1]
  2573. opts.password = matches[2]
  2574. } else {
  2575. opts.username = opts.auth
  2576. }
  2577. }
  2578. }
  2579. /**
  2580. * connect - connect to an MQTT broker.
  2581. *
  2582. * @param {String} [brokerUrl] - url of the broker, optional
  2583. * @param {Object} opts - see MqttClient#constructor
  2584. */
  2585. function connect (brokerUrl, opts) {
  2586. debug('connecting to an MQTT broker...')
  2587. if ((typeof brokerUrl === 'object') && !opts) {
  2588. opts = brokerUrl
  2589. brokerUrl = null
  2590. }
  2591. opts = opts || {}
  2592. if (brokerUrl) {
  2593. // eslint-disable-next-line
  2594. const parsed = url.parse(brokerUrl, true)
  2595. if (parsed.port != null) {
  2596. parsed.port = Number(parsed.port)
  2597. }
  2598. opts = xtend(parsed, opts)
  2599. if (opts.protocol === null) {
  2600. throw new Error('Missing protocol')
  2601. }
  2602. opts.protocol = opts.protocol.replace(/:$/, '')
  2603. }
  2604. // merge in the auth options if supplied
  2605. parseAuthOptions(opts)
  2606. // support clientId passed in the query string of the url
  2607. if (opts.query && typeof opts.query.clientId === 'string') {
  2608. opts.clientId = opts.query.clientId
  2609. }
  2610. if (opts.cert && opts.key) {
  2611. if (opts.protocol) {
  2612. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  2613. switch (opts.protocol) {
  2614. case 'mqtt':
  2615. opts.protocol = 'mqtts'
  2616. break
  2617. case 'ws':
  2618. opts.protocol = 'wss'
  2619. break
  2620. case 'wx':
  2621. opts.protocol = 'wxs'
  2622. break
  2623. case 'ali':
  2624. opts.protocol = 'alis'
  2625. break
  2626. default:
  2627. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  2628. }
  2629. }
  2630. } else {
  2631. // A cert and key was provided, however no protocol was specified, so we will throw an error.
  2632. throw new Error('Missing secure protocol key')
  2633. }
  2634. }
  2635. if (!protocols[opts.protocol]) {
  2636. const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  2637. opts.protocol = [
  2638. 'mqtt',
  2639. 'mqtts',
  2640. 'ws',
  2641. 'wss',
  2642. 'wx',
  2643. 'wxs',
  2644. 'ali',
  2645. 'alis'
  2646. ].filter(function (key, index) {
  2647. if (isSecure && index % 2 === 0) {
  2648. // Skip insecure protocols when requesting a secure one.
  2649. return false
  2650. }
  2651. return (typeof protocols[key] === 'function')
  2652. })[0]
  2653. }
  2654. if (opts.clean === false && !opts.clientId) {
  2655. throw new Error('Missing clientId for unclean clients')
  2656. }
  2657. if (opts.protocol) {
  2658. opts.defaultProtocol = opts.protocol
  2659. }
  2660. function wrapper (client) {
  2661. if (opts.servers) {
  2662. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  2663. client._reconnectCount = 0
  2664. }
  2665. opts.host = opts.servers[client._reconnectCount].host
  2666. opts.port = opts.servers[client._reconnectCount].port
  2667. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  2668. opts.hostname = opts.host
  2669. client._reconnectCount++
  2670. }
  2671. debug('calling streambuilder for', opts.protocol)
  2672. return protocols[opts.protocol](client, opts)
  2673. }
  2674. const client = new MqttClient(wrapper, opts)
  2675. client.on('error', function () { /* Automatically set up client error handling */ })
  2676. return client
  2677. }
  2678. module.exports = connect
  2679. module.exports.connect = connect
  2680. module.exports.MqttClient = MqttClient
  2681. module.exports.Store = Store
  2682. }).call(this)}).call(this,require('_process'))
  2683. },{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,"_process":50,"debug":18,"url":76,"xtend":81}],13:[function(require,module,exports){
  2684. 'use strict'
  2685. exports.byteLength = byteLength
  2686. exports.toByteArray = toByteArray
  2687. exports.fromByteArray = fromByteArray
  2688. var lookup = []
  2689. var revLookup = []
  2690. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2691. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2692. for (var i = 0, len = code.length; i < len; ++i) {
  2693. lookup[i] = code[i]
  2694. revLookup[code.charCodeAt(i)] = i
  2695. }
  2696. // Support decoding URL-safe base64 strings, as Node.js does.
  2697. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2698. revLookup['-'.charCodeAt(0)] = 62
  2699. revLookup['_'.charCodeAt(0)] = 63
  2700. function getLens (b64) {
  2701. var len = b64.length
  2702. if (len % 4 > 0) {
  2703. throw new Error('Invalid string. Length must be a multiple of 4')
  2704. }
  2705. // Trim off extra bytes after placeholder bytes are found
  2706. // See: https://github.com/beatgammit/base64-js/issues/42
  2707. var validLen = b64.indexOf('=')
  2708. if (validLen === -1) validLen = len
  2709. var placeHoldersLen = validLen === len
  2710. ? 0
  2711. : 4 - (validLen % 4)
  2712. return [validLen, placeHoldersLen]
  2713. }
  2714. // base64 is 4/3 + up to two characters of the original data
  2715. function byteLength (b64) {
  2716. var lens = getLens(b64)
  2717. var validLen = lens[0]
  2718. var placeHoldersLen = lens[1]
  2719. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2720. }
  2721. function _byteLength (b64, validLen, placeHoldersLen) {
  2722. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2723. }
  2724. function toByteArray (b64) {
  2725. var tmp
  2726. var lens = getLens(b64)
  2727. var validLen = lens[0]
  2728. var placeHoldersLen = lens[1]
  2729. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2730. var curByte = 0
  2731. // if there are placeholders, only get up to the last complete 4 chars
  2732. var len = placeHoldersLen > 0
  2733. ? validLen - 4
  2734. : validLen
  2735. var i
  2736. for (i = 0; i < len; i += 4) {
  2737. tmp =
  2738. (revLookup[b64.charCodeAt(i)] << 18) |
  2739. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2740. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2741. revLookup[b64.charCodeAt(i + 3)]
  2742. arr[curByte++] = (tmp >> 16) & 0xFF
  2743. arr[curByte++] = (tmp >> 8) & 0xFF
  2744. arr[curByte++] = tmp & 0xFF
  2745. }
  2746. if (placeHoldersLen === 2) {
  2747. tmp =
  2748. (revLookup[b64.charCodeAt(i)] << 2) |
  2749. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2750. arr[curByte++] = tmp & 0xFF
  2751. }
  2752. if (placeHoldersLen === 1) {
  2753. tmp =
  2754. (revLookup[b64.charCodeAt(i)] << 10) |
  2755. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2756. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2757. arr[curByte++] = (tmp >> 8) & 0xFF
  2758. arr[curByte++] = tmp & 0xFF
  2759. }
  2760. return arr
  2761. }
  2762. function tripletToBase64 (num) {
  2763. return lookup[num >> 18 & 0x3F] +
  2764. lookup[num >> 12 & 0x3F] +
  2765. lookup[num >> 6 & 0x3F] +
  2766. lookup[num & 0x3F]
  2767. }
  2768. function encodeChunk (uint8, start, end) {
  2769. var tmp
  2770. var output = []
  2771. for (var i = start; i < end; i += 3) {
  2772. tmp =
  2773. ((uint8[i] << 16) & 0xFF0000) +
  2774. ((uint8[i + 1] << 8) & 0xFF00) +
  2775. (uint8[i + 2] & 0xFF)
  2776. output.push(tripletToBase64(tmp))
  2777. }
  2778. return output.join('')
  2779. }
  2780. function fromByteArray (uint8) {
  2781. var tmp
  2782. var len = uint8.length
  2783. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2784. var parts = []
  2785. var maxChunkLength = 16383 // must be multiple of 3
  2786. // go through the array every three bytes, we'll deal with trailing stuff later
  2787. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2788. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  2789. }
  2790. // pad the end with zeros, but make sure to not forget the extra bytes
  2791. if (extraBytes === 1) {
  2792. tmp = uint8[len - 1]
  2793. parts.push(
  2794. lookup[tmp >> 2] +
  2795. lookup[(tmp << 4) & 0x3F] +
  2796. '=='
  2797. )
  2798. } else if (extraBytes === 2) {
  2799. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2800. parts.push(
  2801. lookup[tmp >> 10] +
  2802. lookup[(tmp >> 4) & 0x3F] +
  2803. lookup[(tmp << 2) & 0x3F] +
  2804. '='
  2805. )
  2806. }
  2807. return parts.join('')
  2808. }
  2809. },{}],14:[function(require,module,exports){
  2810. 'use strict'
  2811. const { Buffer } = require('buffer')
  2812. const symbol = Symbol.for('BufferList')
  2813. function BufferList (buf) {
  2814. if (!(this instanceof BufferList)) {
  2815. return new BufferList(buf)
  2816. }
  2817. BufferList._init.call(this, buf)
  2818. }
  2819. BufferList._init = function _init (buf) {
  2820. Object.defineProperty(this, symbol, { value: true })
  2821. this._bufs = []
  2822. this.length = 0
  2823. if (buf) {
  2824. this.append(buf)
  2825. }
  2826. }
  2827. BufferList.prototype._new = function _new (buf) {
  2828. return new BufferList(buf)
  2829. }
  2830. BufferList.prototype._offset = function _offset (offset) {
  2831. if (offset === 0) {
  2832. return [0, 0]
  2833. }
  2834. let tot = 0
  2835. for (let i = 0; i < this._bufs.length; i++) {
  2836. const _t = tot + this._bufs[i].length
  2837. if (offset < _t || i === this._bufs.length - 1) {
  2838. return [i, offset - tot]
  2839. }
  2840. tot = _t
  2841. }
  2842. }
  2843. BufferList.prototype._reverseOffset = function (blOffset) {
  2844. const bufferId = blOffset[0]
  2845. let offset = blOffset[1]
  2846. for (let i = 0; i < bufferId; i++) {
  2847. offset += this._bufs[i].length
  2848. }
  2849. return offset
  2850. }
  2851. BufferList.prototype.get = function get (index) {
  2852. if (index > this.length || index < 0) {
  2853. return undefined
  2854. }
  2855. const offset = this._offset(index)
  2856. return this._bufs[offset[0]][offset[1]]
  2857. }
  2858. BufferList.prototype.slice = function slice (start, end) {
  2859. if (typeof start === 'number' && start < 0) {
  2860. start += this.length
  2861. }
  2862. if (typeof end === 'number' && end < 0) {
  2863. end += this.length
  2864. }
  2865. return this.copy(null, 0, start, end)
  2866. }
  2867. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  2868. if (typeof srcStart !== 'number' || srcStart < 0) {
  2869. srcStart = 0
  2870. }
  2871. if (typeof srcEnd !== 'number' || srcEnd > this.length) {
  2872. srcEnd = this.length
  2873. }
  2874. if (srcStart >= this.length) {
  2875. return dst || Buffer.alloc(0)
  2876. }
  2877. if (srcEnd <= 0) {
  2878. return dst || Buffer.alloc(0)
  2879. }
  2880. const copy = !!dst
  2881. const off = this._offset(srcStart)
  2882. const len = srcEnd - srcStart
  2883. let bytes = len
  2884. let bufoff = (copy && dstStart) || 0
  2885. let start = off[1]
  2886. // copy/slice everything
  2887. if (srcStart === 0 && srcEnd === this.length) {
  2888. if (!copy) {
  2889. // slice, but full concat if multiple buffers
  2890. return this._bufs.length === 1
  2891. ? this._bufs[0]
  2892. : Buffer.concat(this._bufs, this.length)
  2893. }
  2894. // copy, need to copy individual buffers
  2895. for (let i = 0; i < this._bufs.length; i++) {
  2896. this._bufs[i].copy(dst, bufoff)
  2897. bufoff += this._bufs[i].length
  2898. }
  2899. return dst
  2900. }
  2901. // easy, cheap case where it's a subset of one of the buffers
  2902. if (bytes <= this._bufs[off[0]].length - start) {
  2903. return copy
  2904. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  2905. : this._bufs[off[0]].slice(start, start + bytes)
  2906. }
  2907. if (!copy) {
  2908. // a slice, we need something to copy in to
  2909. dst = Buffer.allocUnsafe(len)
  2910. }
  2911. for (let i = off[0]; i < this._bufs.length; i++) {
  2912. const l = this._bufs[i].length - start
  2913. if (bytes > l) {
  2914. this._bufs[i].copy(dst, bufoff, start)
  2915. bufoff += l
  2916. } else {
  2917. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  2918. bufoff += l
  2919. break
  2920. }
  2921. bytes -= l
  2922. if (start) {
  2923. start = 0
  2924. }
  2925. }
  2926. // safeguard so that we don't return uninitialized memory
  2927. if (dst.length > bufoff) return dst.slice(0, bufoff)
  2928. return dst
  2929. }
  2930. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  2931. start = start || 0
  2932. end = typeof end !== 'number' ? this.length : end
  2933. if (start < 0) {
  2934. start += this.length
  2935. }
  2936. if (end < 0) {
  2937. end += this.length
  2938. }
  2939. if (start === end) {
  2940. return this._new()
  2941. }
  2942. const startOffset = this._offset(start)
  2943. const endOffset = this._offset(end)
  2944. const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  2945. if (endOffset[1] === 0) {
  2946. buffers.pop()
  2947. } else {
  2948. buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])
  2949. }
  2950. if (startOffset[1] !== 0) {
  2951. buffers[0] = buffers[0].slice(startOffset[1])
  2952. }
  2953. return this._new(buffers)
  2954. }
  2955. BufferList.prototype.toString = function toString (encoding, start, end) {
  2956. return this.slice(start, end).toString(encoding)
  2957. }
  2958. BufferList.prototype.consume = function consume (bytes) {
  2959. // first, normalize the argument, in accordance with how Buffer does it
  2960. bytes = Math.trunc(bytes)
  2961. // do nothing if not a positive number
  2962. if (Number.isNaN(bytes) || bytes <= 0) return this
  2963. while (this._bufs.length) {
  2964. if (bytes >= this._bufs[0].length) {
  2965. bytes -= this._bufs[0].length
  2966. this.length -= this._bufs[0].length
  2967. this._bufs.shift()
  2968. } else {
  2969. this._bufs[0] = this._bufs[0].slice(bytes)
  2970. this.length -= bytes
  2971. break
  2972. }
  2973. }
  2974. return this
  2975. }
  2976. BufferList.prototype.duplicate = function duplicate () {
  2977. const copy = this._new()
  2978. for (let i = 0; i < this._bufs.length; i++) {
  2979. copy.append(this._bufs[i])
  2980. }
  2981. return copy
  2982. }
  2983. BufferList.prototype.append = function append (buf) {
  2984. if (buf == null) {
  2985. return this
  2986. }
  2987. if (buf.buffer) {
  2988. // append a view of the underlying ArrayBuffer
  2989. this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))
  2990. } else if (Array.isArray(buf)) {
  2991. for (let i = 0; i < buf.length; i++) {
  2992. this.append(buf[i])
  2993. }
  2994. } else if (this._isBufferList(buf)) {
  2995. // unwrap argument into individual BufferLists
  2996. for (let i = 0; i < buf._bufs.length; i++) {
  2997. this.append(buf._bufs[i])
  2998. }
  2999. } else {
  3000. // coerce number arguments to strings, since Buffer(number) does
  3001. // uninitialized memory allocation
  3002. if (typeof buf === 'number') {
  3003. buf = buf.toString()
  3004. }
  3005. this._appendBuffer(Buffer.from(buf))
  3006. }
  3007. return this
  3008. }
  3009. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  3010. this._bufs.push(buf)
  3011. this.length += buf.length
  3012. }
  3013. BufferList.prototype.indexOf = function (search, offset, encoding) {
  3014. if (encoding === undefined && typeof offset === 'string') {
  3015. encoding = offset
  3016. offset = undefined
  3017. }
  3018. if (typeof search === 'function' || Array.isArray(search)) {
  3019. throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.')
  3020. } else if (typeof search === 'number') {
  3021. search = Buffer.from([search])
  3022. } else if (typeof search === 'string') {
  3023. search = Buffer.from(search, encoding)
  3024. } else if (this._isBufferList(search)) {
  3025. search = search.slice()
  3026. } else if (Array.isArray(search.buffer)) {
  3027. search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)
  3028. } else if (!Buffer.isBuffer(search)) {
  3029. search = Buffer.from(search)
  3030. }
  3031. offset = Number(offset || 0)
  3032. if (isNaN(offset)) {
  3033. offset = 0
  3034. }
  3035. if (offset < 0) {
  3036. offset = this.length + offset
  3037. }
  3038. if (offset < 0) {
  3039. offset = 0
  3040. }
  3041. if (search.length === 0) {
  3042. return offset > this.length ? this.length : offset
  3043. }
  3044. const blOffset = this._offset(offset)
  3045. let blIndex = blOffset[0] // index of which internal buffer we're working on
  3046. let buffOffset = blOffset[1] // offset of the internal buffer we're working on
  3047. // scan over each buffer
  3048. for (; blIndex < this._bufs.length; blIndex++) {
  3049. const buff = this._bufs[blIndex]
  3050. while (buffOffset < buff.length) {
  3051. const availableWindow = buff.length - buffOffset
  3052. if (availableWindow >= search.length) {
  3053. const nativeSearchResult = buff.indexOf(search, buffOffset)
  3054. if (nativeSearchResult !== -1) {
  3055. return this._reverseOffset([blIndex, nativeSearchResult])
  3056. }
  3057. buffOffset = buff.length - search.length + 1 // end of native search window
  3058. } else {
  3059. const revOffset = this._reverseOffset([blIndex, buffOffset])
  3060. if (this._match(revOffset, search)) {
  3061. return revOffset
  3062. }
  3063. buffOffset++
  3064. }
  3065. }
  3066. buffOffset = 0
  3067. }
  3068. return -1
  3069. }
  3070. BufferList.prototype._match = function (offset, search) {
  3071. if (this.length - offset < search.length) {
  3072. return false
  3073. }
  3074. for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {
  3075. if (this.get(offset + searchOffset) !== search[searchOffset]) {
  3076. return false
  3077. }
  3078. }
  3079. return true
  3080. }
  3081. ;(function () {
  3082. const methods = {
  3083. readDoubleBE: 8,
  3084. readDoubleLE: 8,
  3085. readFloatBE: 4,
  3086. readFloatLE: 4,
  3087. readInt32BE: 4,
  3088. readInt32LE: 4,
  3089. readUInt32BE: 4,
  3090. readUInt32LE: 4,
  3091. readInt16BE: 2,
  3092. readInt16LE: 2,
  3093. readUInt16BE: 2,
  3094. readUInt16LE: 2,
  3095. readInt8: 1,
  3096. readUInt8: 1,
  3097. readIntBE: null,
  3098. readIntLE: null,
  3099. readUIntBE: null,
  3100. readUIntLE: null
  3101. }
  3102. for (const m in methods) {
  3103. (function (m) {
  3104. if (methods[m] === null) {
  3105. BufferList.prototype[m] = function (offset, byteLength) {
  3106. return this.slice(offset, offset + byteLength)[m](0, byteLength)
  3107. }
  3108. } else {
  3109. BufferList.prototype[m] = function (offset = 0) {
  3110. return this.slice(offset, offset + methods[m])[m](0)
  3111. }
  3112. }
  3113. }(m))
  3114. }
  3115. }())
  3116. // Used internally by the class and also as an indicator of this object being
  3117. // a `BufferList`. It's not possible to use `instanceof BufferList` in a browser
  3118. // environment because there could be multiple different copies of the
  3119. // BufferList class and some `BufferList`s might be `BufferList`s.
  3120. BufferList.prototype._isBufferList = function _isBufferList (b) {
  3121. return b instanceof BufferList || BufferList.isBufferList(b)
  3122. }
  3123. BufferList.isBufferList = function isBufferList (b) {
  3124. return b != null && b[symbol]
  3125. }
  3126. module.exports = BufferList
  3127. },{"buffer":17}],15:[function(require,module,exports){
  3128. 'use strict'
  3129. const DuplexStream = require('readable-stream').Duplex
  3130. const inherits = require('inherits')
  3131. const BufferList = require('./BufferList')
  3132. function BufferListStream (callback) {
  3133. if (!(this instanceof BufferListStream)) {
  3134. return new BufferListStream(callback)
  3135. }
  3136. if (typeof callback === 'function') {
  3137. this._callback = callback
  3138. const piper = function piper (err) {
  3139. if (this._callback) {
  3140. this._callback(err)
  3141. this._callback = null
  3142. }
  3143. }.bind(this)
  3144. this.on('pipe', function onPipe (src) {
  3145. src.on('error', piper)
  3146. })
  3147. this.on('unpipe', function onUnpipe (src) {
  3148. src.removeListener('error', piper)
  3149. })
  3150. callback = null
  3151. }
  3152. BufferList._init.call(this, callback)
  3153. DuplexStream.call(this)
  3154. }
  3155. inherits(BufferListStream, DuplexStream)
  3156. Object.assign(BufferListStream.prototype, BufferList.prototype)
  3157. BufferListStream.prototype._new = function _new (callback) {
  3158. return new BufferListStream(callback)
  3159. }
  3160. BufferListStream.prototype._write = function _write (buf, encoding, callback) {
  3161. this._appendBuffer(buf)
  3162. if (typeof callback === 'function') {
  3163. callback()
  3164. }
  3165. }
  3166. BufferListStream.prototype._read = function _read (size) {
  3167. if (!this.length) {
  3168. return this.push(null)
  3169. }
  3170. size = Math.min(size, this.length)
  3171. this.push(this.slice(0, size))
  3172. this.consume(size)
  3173. }
  3174. BufferListStream.prototype.end = function end (chunk) {
  3175. DuplexStream.prototype.end.call(this, chunk)
  3176. if (this._callback) {
  3177. this._callback(null, this.slice())
  3178. this._callback = null
  3179. }
  3180. }
  3181. BufferListStream.prototype._destroy = function _destroy (err, cb) {
  3182. this._bufs.length = 0
  3183. this.length = 0
  3184. cb(err)
  3185. }
  3186. BufferListStream.prototype._isBufferList = function _isBufferList (b) {
  3187. return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)
  3188. }
  3189. BufferListStream.isBufferList = BufferList.isBufferList
  3190. module.exports = BufferListStream
  3191. module.exports.BufferListStream = BufferListStream
  3192. module.exports.BufferList = BufferList
  3193. },{"./BufferList":14,"inherits":24,"readable-stream":69}],16:[function(require,module,exports){
  3194. },{}],17:[function(require,module,exports){
  3195. (function (Buffer){(function (){
  3196. /*!
  3197. * The buffer module from node.js, for the browser.
  3198. *
  3199. * @author Feross Aboukhadijeh <https://feross.org>
  3200. * @license MIT
  3201. */
  3202. /* eslint-disable no-proto */
  3203. 'use strict'
  3204. var base64 = require('base64-js')
  3205. var ieee754 = require('ieee754')
  3206. exports.Buffer = Buffer
  3207. exports.SlowBuffer = SlowBuffer
  3208. exports.INSPECT_MAX_BYTES = 50
  3209. var K_MAX_LENGTH = 0x7fffffff
  3210. exports.kMaxLength = K_MAX_LENGTH
  3211. /**
  3212. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  3213. * === true Use Uint8Array implementation (fastest)
  3214. * === false Print warning and recommend using `buffer` v4.x which has an Object
  3215. * implementation (most compatible, even IE6)
  3216. *
  3217. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  3218. * Opera 11.6+, iOS 4.2+.
  3219. *
  3220. * We report that the browser does not support typed arrays if the are not subclassable
  3221. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  3222. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  3223. * for __proto__ and has a buggy typed array implementation.
  3224. */
  3225. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  3226. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  3227. typeof console.error === 'function') {
  3228. console.error(
  3229. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  3230. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  3231. )
  3232. }
  3233. function typedArraySupport () {
  3234. // Can typed array instances can be augmented?
  3235. try {
  3236. var arr = new Uint8Array(1)
  3237. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  3238. return arr.foo() === 42
  3239. } catch (e) {
  3240. return false
  3241. }
  3242. }
  3243. Object.defineProperty(Buffer.prototype, 'parent', {
  3244. enumerable: true,
  3245. get: function () {
  3246. if (!Buffer.isBuffer(this)) return undefined
  3247. return this.buffer
  3248. }
  3249. })
  3250. Object.defineProperty(Buffer.prototype, 'offset', {
  3251. enumerable: true,
  3252. get: function () {
  3253. if (!Buffer.isBuffer(this)) return undefined
  3254. return this.byteOffset
  3255. }
  3256. })
  3257. function createBuffer (length) {
  3258. if (length > K_MAX_LENGTH) {
  3259. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  3260. }
  3261. // Return an augmented `Uint8Array` instance
  3262. var buf = new Uint8Array(length)
  3263. buf.__proto__ = Buffer.prototype
  3264. return buf
  3265. }
  3266. /**
  3267. * The Buffer constructor returns instances of `Uint8Array` that have their
  3268. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  3269. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  3270. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  3271. * returns a single octet.
  3272. *
  3273. * The `Uint8Array` prototype remains unmodified.
  3274. */
  3275. function Buffer (arg, encodingOrOffset, length) {
  3276. // Common case.
  3277. if (typeof arg === 'number') {
  3278. if (typeof encodingOrOffset === 'string') {
  3279. throw new TypeError(
  3280. 'The "string" argument must be of type string. Received type number'
  3281. )
  3282. }
  3283. return allocUnsafe(arg)
  3284. }
  3285. return from(arg, encodingOrOffset, length)
  3286. }
  3287. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  3288. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  3289. Buffer[Symbol.species] === Buffer) {
  3290. Object.defineProperty(Buffer, Symbol.species, {
  3291. value: null,
  3292. configurable: true,
  3293. enumerable: false,
  3294. writable: false
  3295. })
  3296. }
  3297. Buffer.poolSize = 8192 // not used by this implementation
  3298. function from (value, encodingOrOffset, length) {
  3299. if (typeof value === 'string') {
  3300. return fromString(value, encodingOrOffset)
  3301. }
  3302. if (ArrayBuffer.isView(value)) {
  3303. return fromArrayLike(value)
  3304. }
  3305. if (value == null) {
  3306. throw TypeError(
  3307. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  3308. 'or Array-like Object. Received type ' + (typeof value)
  3309. )
  3310. }
  3311. if (isInstance(value, ArrayBuffer) ||
  3312. (value && isInstance(value.buffer, ArrayBuffer))) {
  3313. return fromArrayBuffer(value, encodingOrOffset, length)
  3314. }
  3315. if (typeof value === 'number') {
  3316. throw new TypeError(
  3317. 'The "value" argument must not be of type number. Received type number'
  3318. )
  3319. }
  3320. var valueOf = value.valueOf && value.valueOf()
  3321. if (valueOf != null && valueOf !== value) {
  3322. return Buffer.from(valueOf, encodingOrOffset, length)
  3323. }
  3324. var b = fromObject(value)
  3325. if (b) return b
  3326. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  3327. typeof value[Symbol.toPrimitive] === 'function') {
  3328. return Buffer.from(
  3329. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  3330. )
  3331. }
  3332. throw new TypeError(
  3333. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  3334. 'or Array-like Object. Received type ' + (typeof value)
  3335. )
  3336. }
  3337. /**
  3338. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  3339. * if value is a number.
  3340. * Buffer.from(str[, encoding])
  3341. * Buffer.from(array)
  3342. * Buffer.from(buffer)
  3343. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  3344. **/
  3345. Buffer.from = function (value, encodingOrOffset, length) {
  3346. return from(value, encodingOrOffset, length)
  3347. }
  3348. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  3349. // https://github.com/feross/buffer/pull/148
  3350. Buffer.prototype.__proto__ = Uint8Array.prototype
  3351. Buffer.__proto__ = Uint8Array
  3352. function assertSize (size) {
  3353. if (typeof size !== 'number') {
  3354. throw new TypeError('"size" argument must be of type number')
  3355. } else if (size < 0) {
  3356. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  3357. }
  3358. }
  3359. function alloc (size, fill, encoding) {
  3360. assertSize(size)
  3361. if (size <= 0) {
  3362. return createBuffer(size)
  3363. }
  3364. if (fill !== undefined) {
  3365. // Only pay attention to encoding if it's a string. This
  3366. // prevents accidentally sending in a number that would
  3367. // be interpretted as a start offset.
  3368. return typeof encoding === 'string'
  3369. ? createBuffer(size).fill(fill, encoding)
  3370. : createBuffer(size).fill(fill)
  3371. }
  3372. return createBuffer(size)
  3373. }
  3374. /**
  3375. * Creates a new filled Buffer instance.
  3376. * alloc(size[, fill[, encoding]])
  3377. **/
  3378. Buffer.alloc = function (size, fill, encoding) {
  3379. return alloc(size, fill, encoding)
  3380. }
  3381. function allocUnsafe (size) {
  3382. assertSize(size)
  3383. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  3384. }
  3385. /**
  3386. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  3387. * */
  3388. Buffer.allocUnsafe = function (size) {
  3389. return allocUnsafe(size)
  3390. }
  3391. /**
  3392. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  3393. */
  3394. Buffer.allocUnsafeSlow = function (size) {
  3395. return allocUnsafe(size)
  3396. }
  3397. function fromString (string, encoding) {
  3398. if (typeof encoding !== 'string' || encoding === '') {
  3399. encoding = 'utf8'
  3400. }
  3401. if (!Buffer.isEncoding(encoding)) {
  3402. throw new TypeError('Unknown encoding: ' + encoding)
  3403. }
  3404. var length = byteLength(string, encoding) | 0
  3405. var buf = createBuffer(length)
  3406. var actual = buf.write(string, encoding)
  3407. if (actual !== length) {
  3408. // Writing a hex string, for example, that contains invalid characters will
  3409. // cause everything after the first invalid character to be ignored. (e.g.
  3410. // 'abxxcd' will be treated as 'ab')
  3411. buf = buf.slice(0, actual)
  3412. }
  3413. return buf
  3414. }
  3415. function fromArrayLike (array) {
  3416. var length = array.length < 0 ? 0 : checked(array.length) | 0
  3417. var buf = createBuffer(length)
  3418. for (var i = 0; i < length; i += 1) {
  3419. buf[i] = array[i] & 255
  3420. }
  3421. return buf
  3422. }
  3423. function fromArrayBuffer (array, byteOffset, length) {
  3424. if (byteOffset < 0 || array.byteLength < byteOffset) {
  3425. throw new RangeError('"offset" is outside of buffer bounds')
  3426. }
  3427. if (array.byteLength < byteOffset + (length || 0)) {
  3428. throw new RangeError('"length" is outside of buffer bounds')
  3429. }
  3430. var buf
  3431. if (byteOffset === undefined && length === undefined) {
  3432. buf = new Uint8Array(array)
  3433. } else if (length === undefined) {
  3434. buf = new Uint8Array(array, byteOffset)
  3435. } else {
  3436. buf = new Uint8Array(array, byteOffset, length)
  3437. }
  3438. // Return an augmented `Uint8Array` instance
  3439. buf.__proto__ = Buffer.prototype
  3440. return buf
  3441. }
  3442. function fromObject (obj) {
  3443. if (Buffer.isBuffer(obj)) {
  3444. var len = checked(obj.length) | 0
  3445. var buf = createBuffer(len)
  3446. if (buf.length === 0) {
  3447. return buf
  3448. }
  3449. obj.copy(buf, 0, 0, len)
  3450. return buf
  3451. }
  3452. if (obj.length !== undefined) {
  3453. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  3454. return createBuffer(0)
  3455. }
  3456. return fromArrayLike(obj)
  3457. }
  3458. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  3459. return fromArrayLike(obj.data)
  3460. }
  3461. }
  3462. function checked (length) {
  3463. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  3464. // length is NaN (which is otherwise coerced to zero.)
  3465. if (length >= K_MAX_LENGTH) {
  3466. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  3467. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  3468. }
  3469. return length | 0
  3470. }
  3471. function SlowBuffer (length) {
  3472. if (+length != length) { // eslint-disable-line eqeqeq
  3473. length = 0
  3474. }
  3475. return Buffer.alloc(+length)
  3476. }
  3477. Buffer.isBuffer = function isBuffer (b) {
  3478. return b != null && b._isBuffer === true &&
  3479. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  3480. }
  3481. Buffer.compare = function compare (a, b) {
  3482. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  3483. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  3484. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  3485. throw new TypeError(
  3486. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  3487. )
  3488. }
  3489. if (a === b) return 0
  3490. var x = a.length
  3491. var y = b.length
  3492. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  3493. if (a[i] !== b[i]) {
  3494. x = a[i]
  3495. y = b[i]
  3496. break
  3497. }
  3498. }
  3499. if (x < y) return -1
  3500. if (y < x) return 1
  3501. return 0
  3502. }
  3503. Buffer.isEncoding = function isEncoding (encoding) {
  3504. switch (String(encoding).toLowerCase()) {
  3505. case 'hex':
  3506. case 'utf8':
  3507. case 'utf-8':
  3508. case 'ascii':
  3509. case 'latin1':
  3510. case 'binary':
  3511. case 'base64':
  3512. case 'ucs2':
  3513. case 'ucs-2':
  3514. case 'utf16le':
  3515. case 'utf-16le':
  3516. return true
  3517. default:
  3518. return false
  3519. }
  3520. }
  3521. Buffer.concat = function concat (list, length) {
  3522. if (!Array.isArray(list)) {
  3523. throw new TypeError('"list" argument must be an Array of Buffers')
  3524. }
  3525. if (list.length === 0) {
  3526. return Buffer.alloc(0)
  3527. }
  3528. var i
  3529. if (length === undefined) {
  3530. length = 0
  3531. for (i = 0; i < list.length; ++i) {
  3532. length += list[i].length
  3533. }
  3534. }
  3535. var buffer = Buffer.allocUnsafe(length)
  3536. var pos = 0
  3537. for (i = 0; i < list.length; ++i) {
  3538. var buf = list[i]
  3539. if (isInstance(buf, Uint8Array)) {
  3540. buf = Buffer.from(buf)
  3541. }
  3542. if (!Buffer.isBuffer(buf)) {
  3543. throw new TypeError('"list" argument must be an Array of Buffers')
  3544. }
  3545. buf.copy(buffer, pos)
  3546. pos += buf.length
  3547. }
  3548. return buffer
  3549. }
  3550. function byteLength (string, encoding) {
  3551. if (Buffer.isBuffer(string)) {
  3552. return string.length
  3553. }
  3554. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  3555. return string.byteLength
  3556. }
  3557. if (typeof string !== 'string') {
  3558. throw new TypeError(
  3559. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  3560. 'Received type ' + typeof string
  3561. )
  3562. }
  3563. var len = string.length
  3564. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  3565. if (!mustMatch && len === 0) return 0
  3566. // Use a for loop to avoid recursion
  3567. var loweredCase = false
  3568. for (;;) {
  3569. switch (encoding) {
  3570. case 'ascii':
  3571. case 'latin1':
  3572. case 'binary':
  3573. return len
  3574. case 'utf8':
  3575. case 'utf-8':
  3576. return utf8ToBytes(string).length
  3577. case 'ucs2':
  3578. case 'ucs-2':
  3579. case 'utf16le':
  3580. case 'utf-16le':
  3581. return len * 2
  3582. case 'hex':
  3583. return len >>> 1
  3584. case 'base64':
  3585. return base64ToBytes(string).length
  3586. default:
  3587. if (loweredCase) {
  3588. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  3589. }
  3590. encoding = ('' + encoding).toLowerCase()
  3591. loweredCase = true
  3592. }
  3593. }
  3594. }
  3595. Buffer.byteLength = byteLength
  3596. function slowToString (encoding, start, end) {
  3597. var loweredCase = false
  3598. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  3599. // property of a typed array.
  3600. // This behaves neither like String nor Uint8Array in that we set start/end
  3601. // to their upper/lower bounds if the value passed is out of range.
  3602. // undefined is handled specially as per ECMA-262 6th Edition,
  3603. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  3604. if (start === undefined || start < 0) {
  3605. start = 0
  3606. }
  3607. // Return early if start > this.length. Done here to prevent potential uint32
  3608. // coercion fail below.
  3609. if (start > this.length) {
  3610. return ''
  3611. }
  3612. if (end === undefined || end > this.length) {
  3613. end = this.length
  3614. }
  3615. if (end <= 0) {
  3616. return ''
  3617. }
  3618. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  3619. end >>>= 0
  3620. start >>>= 0
  3621. if (end <= start) {
  3622. return ''
  3623. }
  3624. if (!encoding) encoding = 'utf8'
  3625. while (true) {
  3626. switch (encoding) {
  3627. case 'hex':
  3628. return hexSlice(this, start, end)
  3629. case 'utf8':
  3630. case 'utf-8':
  3631. return utf8Slice(this, start, end)
  3632. case 'ascii':
  3633. return asciiSlice(this, start, end)
  3634. case 'latin1':
  3635. case 'binary':
  3636. return latin1Slice(this, start, end)
  3637. case 'base64':
  3638. return base64Slice(this, start, end)
  3639. case 'ucs2':
  3640. case 'ucs-2':
  3641. case 'utf16le':
  3642. case 'utf-16le':
  3643. return utf16leSlice(this, start, end)
  3644. default:
  3645. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3646. encoding = (encoding + '').toLowerCase()
  3647. loweredCase = true
  3648. }
  3649. }
  3650. }
  3651. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  3652. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  3653. // reliably in a browserify context because there could be multiple different
  3654. // copies of the 'buffer' package in use. This method works even for Buffer
  3655. // instances that were created from another copy of the `buffer` package.
  3656. // See: https://github.com/feross/buffer/issues/154
  3657. Buffer.prototype._isBuffer = true
  3658. function swap (b, n, m) {
  3659. var i = b[n]
  3660. b[n] = b[m]
  3661. b[m] = i
  3662. }
  3663. Buffer.prototype.swap16 = function swap16 () {
  3664. var len = this.length
  3665. if (len % 2 !== 0) {
  3666. throw new RangeError('Buffer size must be a multiple of 16-bits')
  3667. }
  3668. for (var i = 0; i < len; i += 2) {
  3669. swap(this, i, i + 1)
  3670. }
  3671. return this
  3672. }
  3673. Buffer.prototype.swap32 = function swap32 () {
  3674. var len = this.length
  3675. if (len % 4 !== 0) {
  3676. throw new RangeError('Buffer size must be a multiple of 32-bits')
  3677. }
  3678. for (var i = 0; i < len; i += 4) {
  3679. swap(this, i, i + 3)
  3680. swap(this, i + 1, i + 2)
  3681. }
  3682. return this
  3683. }
  3684. Buffer.prototype.swap64 = function swap64 () {
  3685. var len = this.length
  3686. if (len % 8 !== 0) {
  3687. throw new RangeError('Buffer size must be a multiple of 64-bits')
  3688. }
  3689. for (var i = 0; i < len; i += 8) {
  3690. swap(this, i, i + 7)
  3691. swap(this, i + 1, i + 6)
  3692. swap(this, i + 2, i + 5)
  3693. swap(this, i + 3, i + 4)
  3694. }
  3695. return this
  3696. }
  3697. Buffer.prototype.toString = function toString () {
  3698. var length = this.length
  3699. if (length === 0) return ''
  3700. if (arguments.length === 0) return utf8Slice(this, 0, length)
  3701. return slowToString.apply(this, arguments)
  3702. }
  3703. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  3704. Buffer.prototype.equals = function equals (b) {
  3705. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  3706. if (this === b) return true
  3707. return Buffer.compare(this, b) === 0
  3708. }
  3709. Buffer.prototype.inspect = function inspect () {
  3710. var str = ''
  3711. var max = exports.INSPECT_MAX_BYTES
  3712. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  3713. if (this.length > max) str += ' ... '
  3714. return '<Buffer ' + str + '>'
  3715. }
  3716. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  3717. if (isInstance(target, Uint8Array)) {
  3718. target = Buffer.from(target, target.offset, target.byteLength)
  3719. }
  3720. if (!Buffer.isBuffer(target)) {
  3721. throw new TypeError(
  3722. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  3723. 'Received type ' + (typeof target)
  3724. )
  3725. }
  3726. if (start === undefined) {
  3727. start = 0
  3728. }
  3729. if (end === undefined) {
  3730. end = target ? target.length : 0
  3731. }
  3732. if (thisStart === undefined) {
  3733. thisStart = 0
  3734. }
  3735. if (thisEnd === undefined) {
  3736. thisEnd = this.length
  3737. }
  3738. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  3739. throw new RangeError('out of range index')
  3740. }
  3741. if (thisStart >= thisEnd && start >= end) {
  3742. return 0
  3743. }
  3744. if (thisStart >= thisEnd) {
  3745. return -1
  3746. }
  3747. if (start >= end) {
  3748. return 1
  3749. }
  3750. start >>>= 0
  3751. end >>>= 0
  3752. thisStart >>>= 0
  3753. thisEnd >>>= 0
  3754. if (this === target) return 0
  3755. var x = thisEnd - thisStart
  3756. var y = end - start
  3757. var len = Math.min(x, y)
  3758. var thisCopy = this.slice(thisStart, thisEnd)
  3759. var targetCopy = target.slice(start, end)
  3760. for (var i = 0; i < len; ++i) {
  3761. if (thisCopy[i] !== targetCopy[i]) {
  3762. x = thisCopy[i]
  3763. y = targetCopy[i]
  3764. break
  3765. }
  3766. }
  3767. if (x < y) return -1
  3768. if (y < x) return 1
  3769. return 0
  3770. }
  3771. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  3772. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  3773. //
  3774. // Arguments:
  3775. // - buffer - a Buffer to search
  3776. // - val - a string, Buffer, or number
  3777. // - byteOffset - an index into `buffer`; will be clamped to an int32
  3778. // - encoding - an optional encoding, relevant is val is a string
  3779. // - dir - true for indexOf, false for lastIndexOf
  3780. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  3781. // Empty buffer means no match
  3782. if (buffer.length === 0) return -1
  3783. // Normalize byteOffset
  3784. if (typeof byteOffset === 'string') {
  3785. encoding = byteOffset
  3786. byteOffset = 0
  3787. } else if (byteOffset > 0x7fffffff) {
  3788. byteOffset = 0x7fffffff
  3789. } else if (byteOffset < -0x80000000) {
  3790. byteOffset = -0x80000000
  3791. }
  3792. byteOffset = +byteOffset // Coerce to Number.
  3793. if (numberIsNaN(byteOffset)) {
  3794. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  3795. byteOffset = dir ? 0 : (buffer.length - 1)
  3796. }
  3797. // Normalize byteOffset: negative offsets start from the end of the buffer
  3798. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  3799. if (byteOffset >= buffer.length) {
  3800. if (dir) return -1
  3801. else byteOffset = buffer.length - 1
  3802. } else if (byteOffset < 0) {
  3803. if (dir) byteOffset = 0
  3804. else return -1
  3805. }
  3806. // Normalize val
  3807. if (typeof val === 'string') {
  3808. val = Buffer.from(val, encoding)
  3809. }
  3810. // Finally, search either indexOf (if dir is true) or lastIndexOf
  3811. if (Buffer.isBuffer(val)) {
  3812. // Special case: looking for empty string/buffer always fails
  3813. if (val.length === 0) {
  3814. return -1
  3815. }
  3816. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  3817. } else if (typeof val === 'number') {
  3818. val = val & 0xFF // Search for a byte value [0-255]
  3819. if (typeof Uint8Array.prototype.indexOf === 'function') {
  3820. if (dir) {
  3821. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  3822. } else {
  3823. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  3824. }
  3825. }
  3826. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  3827. }
  3828. throw new TypeError('val must be string, number or Buffer')
  3829. }
  3830. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  3831. var indexSize = 1
  3832. var arrLength = arr.length
  3833. var valLength = val.length
  3834. if (encoding !== undefined) {
  3835. encoding = String(encoding).toLowerCase()
  3836. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  3837. encoding === 'utf16le' || encoding === 'utf-16le') {
  3838. if (arr.length < 2 || val.length < 2) {
  3839. return -1
  3840. }
  3841. indexSize = 2
  3842. arrLength /= 2
  3843. valLength /= 2
  3844. byteOffset /= 2
  3845. }
  3846. }
  3847. function read (buf, i) {
  3848. if (indexSize === 1) {
  3849. return buf[i]
  3850. } else {
  3851. return buf.readUInt16BE(i * indexSize)
  3852. }
  3853. }
  3854. var i
  3855. if (dir) {
  3856. var foundIndex = -1
  3857. for (i = byteOffset; i < arrLength; i++) {
  3858. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  3859. if (foundIndex === -1) foundIndex = i
  3860. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  3861. } else {
  3862. if (foundIndex !== -1) i -= i - foundIndex
  3863. foundIndex = -1
  3864. }
  3865. }
  3866. } else {
  3867. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  3868. for (i = byteOffset; i >= 0; i--) {
  3869. var found = true
  3870. for (var j = 0; j < valLength; j++) {
  3871. if (read(arr, i + j) !== read(val, j)) {
  3872. found = false
  3873. break
  3874. }
  3875. }
  3876. if (found) return i
  3877. }
  3878. }
  3879. return -1
  3880. }
  3881. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  3882. return this.indexOf(val, byteOffset, encoding) !== -1
  3883. }
  3884. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  3885. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  3886. }
  3887. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  3888. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  3889. }
  3890. function hexWrite (buf, string, offset, length) {
  3891. offset = Number(offset) || 0
  3892. var remaining = buf.length - offset
  3893. if (!length) {
  3894. length = remaining
  3895. } else {
  3896. length = Number(length)
  3897. if (length > remaining) {
  3898. length = remaining
  3899. }
  3900. }
  3901. var strLen = string.length
  3902. if (length > strLen / 2) {
  3903. length = strLen / 2
  3904. }
  3905. for (var i = 0; i < length; ++i) {
  3906. var parsed = parseInt(string.substr(i * 2, 2), 16)
  3907. if (numberIsNaN(parsed)) return i
  3908. buf[offset + i] = parsed
  3909. }
  3910. return i
  3911. }
  3912. function utf8Write (buf, string, offset, length) {
  3913. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3914. }
  3915. function asciiWrite (buf, string, offset, length) {
  3916. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3917. }
  3918. function latin1Write (buf, string, offset, length) {
  3919. return asciiWrite(buf, string, offset, length)
  3920. }
  3921. function base64Write (buf, string, offset, length) {
  3922. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3923. }
  3924. function ucs2Write (buf, string, offset, length) {
  3925. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3926. }
  3927. Buffer.prototype.write = function write (string, offset, length, encoding) {
  3928. // Buffer#write(string)
  3929. if (offset === undefined) {
  3930. encoding = 'utf8'
  3931. length = this.length
  3932. offset = 0
  3933. // Buffer#write(string, encoding)
  3934. } else if (length === undefined && typeof offset === 'string') {
  3935. encoding = offset
  3936. length = this.length
  3937. offset = 0
  3938. // Buffer#write(string, offset[, length][, encoding])
  3939. } else if (isFinite(offset)) {
  3940. offset = offset >>> 0
  3941. if (isFinite(length)) {
  3942. length = length >>> 0
  3943. if (encoding === undefined) encoding = 'utf8'
  3944. } else {
  3945. encoding = length
  3946. length = undefined
  3947. }
  3948. } else {
  3949. throw new Error(
  3950. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3951. )
  3952. }
  3953. var remaining = this.length - offset
  3954. if (length === undefined || length > remaining) length = remaining
  3955. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3956. throw new RangeError('Attempt to write outside buffer bounds')
  3957. }
  3958. if (!encoding) encoding = 'utf8'
  3959. var loweredCase = false
  3960. for (;;) {
  3961. switch (encoding) {
  3962. case 'hex':
  3963. return hexWrite(this, string, offset, length)
  3964. case 'utf8':
  3965. case 'utf-8':
  3966. return utf8Write(this, string, offset, length)
  3967. case 'ascii':
  3968. return asciiWrite(this, string, offset, length)
  3969. case 'latin1':
  3970. case 'binary':
  3971. return latin1Write(this, string, offset, length)
  3972. case 'base64':
  3973. // Warning: maxLength not taken into account in base64Write
  3974. return base64Write(this, string, offset, length)
  3975. case 'ucs2':
  3976. case 'ucs-2':
  3977. case 'utf16le':
  3978. case 'utf-16le':
  3979. return ucs2Write(this, string, offset, length)
  3980. default:
  3981. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3982. encoding = ('' + encoding).toLowerCase()
  3983. loweredCase = true
  3984. }
  3985. }
  3986. }
  3987. Buffer.prototype.toJSON = function toJSON () {
  3988. return {
  3989. type: 'Buffer',
  3990. data: Array.prototype.slice.call(this._arr || this, 0)
  3991. }
  3992. }
  3993. function base64Slice (buf, start, end) {
  3994. if (start === 0 && end === buf.length) {
  3995. return base64.fromByteArray(buf)
  3996. } else {
  3997. return base64.fromByteArray(buf.slice(start, end))
  3998. }
  3999. }
  4000. function utf8Slice (buf, start, end) {
  4001. end = Math.min(buf.length, end)
  4002. var res = []
  4003. var i = start
  4004. while (i < end) {
  4005. var firstByte = buf[i]
  4006. var codePoint = null
  4007. var bytesPerSequence = (firstByte > 0xEF) ? 4
  4008. : (firstByte > 0xDF) ? 3
  4009. : (firstByte > 0xBF) ? 2
  4010. : 1
  4011. if (i + bytesPerSequence <= end) {
  4012. var secondByte, thirdByte, fourthByte, tempCodePoint
  4013. switch (bytesPerSequence) {
  4014. case 1:
  4015. if (firstByte < 0x80) {
  4016. codePoint = firstByte
  4017. }
  4018. break
  4019. case 2:
  4020. secondByte = buf[i + 1]
  4021. if ((secondByte & 0xC0) === 0x80) {
  4022. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  4023. if (tempCodePoint > 0x7F) {
  4024. codePoint = tempCodePoint
  4025. }
  4026. }
  4027. break
  4028. case 3:
  4029. secondByte = buf[i + 1]
  4030. thirdByte = buf[i + 2]
  4031. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  4032. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  4033. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  4034. codePoint = tempCodePoint
  4035. }
  4036. }
  4037. break
  4038. case 4:
  4039. secondByte = buf[i + 1]
  4040. thirdByte = buf[i + 2]
  4041. fourthByte = buf[i + 3]
  4042. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  4043. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  4044. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  4045. codePoint = tempCodePoint
  4046. }
  4047. }
  4048. }
  4049. }
  4050. if (codePoint === null) {
  4051. // we did not generate a valid codePoint so insert a
  4052. // replacement char (U+FFFD) and advance only 1 byte
  4053. codePoint = 0xFFFD
  4054. bytesPerSequence = 1
  4055. } else if (codePoint > 0xFFFF) {
  4056. // encode to utf16 (surrogate pair dance)
  4057. codePoint -= 0x10000
  4058. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  4059. codePoint = 0xDC00 | codePoint & 0x3FF
  4060. }
  4061. res.push(codePoint)
  4062. i += bytesPerSequence
  4063. }
  4064. return decodeCodePointsArray(res)
  4065. }
  4066. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  4067. // the lowest limit is Chrome, with 0x10000 args.
  4068. // We go 1 magnitude less, for safety
  4069. var MAX_ARGUMENTS_LENGTH = 0x1000
  4070. function decodeCodePointsArray (codePoints) {
  4071. var len = codePoints.length
  4072. if (len <= MAX_ARGUMENTS_LENGTH) {
  4073. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  4074. }
  4075. // Decode in chunks to avoid "call stack size exceeded".
  4076. var res = ''
  4077. var i = 0
  4078. while (i < len) {
  4079. res += String.fromCharCode.apply(
  4080. String,
  4081. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  4082. )
  4083. }
  4084. return res
  4085. }
  4086. function asciiSlice (buf, start, end) {
  4087. var ret = ''
  4088. end = Math.min(buf.length, end)
  4089. for (var i = start; i < end; ++i) {
  4090. ret += String.fromCharCode(buf[i] & 0x7F)
  4091. }
  4092. return ret
  4093. }
  4094. function latin1Slice (buf, start, end) {
  4095. var ret = ''
  4096. end = Math.min(buf.length, end)
  4097. for (var i = start; i < end; ++i) {
  4098. ret += String.fromCharCode(buf[i])
  4099. }
  4100. return ret
  4101. }
  4102. function hexSlice (buf, start, end) {
  4103. var len = buf.length
  4104. if (!start || start < 0) start = 0
  4105. if (!end || end < 0 || end > len) end = len
  4106. var out = ''
  4107. for (var i = start; i < end; ++i) {
  4108. out += toHex(buf[i])
  4109. }
  4110. return out
  4111. }
  4112. function utf16leSlice (buf, start, end) {
  4113. var bytes = buf.slice(start, end)
  4114. var res = ''
  4115. for (var i = 0; i < bytes.length; i += 2) {
  4116. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  4117. }
  4118. return res
  4119. }
  4120. Buffer.prototype.slice = function slice (start, end) {
  4121. var len = this.length
  4122. start = ~~start
  4123. end = end === undefined ? len : ~~end
  4124. if (start < 0) {
  4125. start += len
  4126. if (start < 0) start = 0
  4127. } else if (start > len) {
  4128. start = len
  4129. }
  4130. if (end < 0) {
  4131. end += len
  4132. if (end < 0) end = 0
  4133. } else if (end > len) {
  4134. end = len
  4135. }
  4136. if (end < start) end = start
  4137. var newBuf = this.subarray(start, end)
  4138. // Return an augmented `Uint8Array` instance
  4139. newBuf.__proto__ = Buffer.prototype
  4140. return newBuf
  4141. }
  4142. /*
  4143. * Need to make sure that buffer isn't trying to write out of bounds.
  4144. */
  4145. function checkOffset (offset, ext, length) {
  4146. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  4147. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  4148. }
  4149. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  4150. offset = offset >>> 0
  4151. byteLength = byteLength >>> 0
  4152. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4153. var val = this[offset]
  4154. var mul = 1
  4155. var i = 0
  4156. while (++i < byteLength && (mul *= 0x100)) {
  4157. val += this[offset + i] * mul
  4158. }
  4159. return val
  4160. }
  4161. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  4162. offset = offset >>> 0
  4163. byteLength = byteLength >>> 0
  4164. if (!noAssert) {
  4165. checkOffset(offset, byteLength, this.length)
  4166. }
  4167. var val = this[offset + --byteLength]
  4168. var mul = 1
  4169. while (byteLength > 0 && (mul *= 0x100)) {
  4170. val += this[offset + --byteLength] * mul
  4171. }
  4172. return val
  4173. }
  4174. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  4175. offset = offset >>> 0
  4176. if (!noAssert) checkOffset(offset, 1, this.length)
  4177. return this[offset]
  4178. }
  4179. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  4180. offset = offset >>> 0
  4181. if (!noAssert) checkOffset(offset, 2, this.length)
  4182. return this[offset] | (this[offset + 1] << 8)
  4183. }
  4184. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  4185. offset = offset >>> 0
  4186. if (!noAssert) checkOffset(offset, 2, this.length)
  4187. return (this[offset] << 8) | this[offset + 1]
  4188. }
  4189. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  4190. offset = offset >>> 0
  4191. if (!noAssert) checkOffset(offset, 4, this.length)
  4192. return ((this[offset]) |
  4193. (this[offset + 1] << 8) |
  4194. (this[offset + 2] << 16)) +
  4195. (this[offset + 3] * 0x1000000)
  4196. }
  4197. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  4198. offset = offset >>> 0
  4199. if (!noAssert) checkOffset(offset, 4, this.length)
  4200. return (this[offset] * 0x1000000) +
  4201. ((this[offset + 1] << 16) |
  4202. (this[offset + 2] << 8) |
  4203. this[offset + 3])
  4204. }
  4205. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  4206. offset = offset >>> 0
  4207. byteLength = byteLength >>> 0
  4208. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4209. var val = this[offset]
  4210. var mul = 1
  4211. var i = 0
  4212. while (++i < byteLength && (mul *= 0x100)) {
  4213. val += this[offset + i] * mul
  4214. }
  4215. mul *= 0x80
  4216. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  4217. return val
  4218. }
  4219. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  4220. offset = offset >>> 0
  4221. byteLength = byteLength >>> 0
  4222. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4223. var i = byteLength
  4224. var mul = 1
  4225. var val = this[offset + --i]
  4226. while (i > 0 && (mul *= 0x100)) {
  4227. val += this[offset + --i] * mul
  4228. }
  4229. mul *= 0x80
  4230. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  4231. return val
  4232. }
  4233. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  4234. offset = offset >>> 0
  4235. if (!noAssert) checkOffset(offset, 1, this.length)
  4236. if (!(this[offset] & 0x80)) return (this[offset])
  4237. return ((0xff - this[offset] + 1) * -1)
  4238. }
  4239. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  4240. offset = offset >>> 0
  4241. if (!noAssert) checkOffset(offset, 2, this.length)
  4242. var val = this[offset] | (this[offset + 1] << 8)
  4243. return (val & 0x8000) ? val | 0xFFFF0000 : val
  4244. }
  4245. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  4246. offset = offset >>> 0
  4247. if (!noAssert) checkOffset(offset, 2, this.length)
  4248. var val = this[offset + 1] | (this[offset] << 8)
  4249. return (val & 0x8000) ? val | 0xFFFF0000 : val
  4250. }
  4251. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  4252. offset = offset >>> 0
  4253. if (!noAssert) checkOffset(offset, 4, this.length)
  4254. return (this[offset]) |
  4255. (this[offset + 1] << 8) |
  4256. (this[offset + 2] << 16) |
  4257. (this[offset + 3] << 24)
  4258. }
  4259. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  4260. offset = offset >>> 0
  4261. if (!noAssert) checkOffset(offset, 4, this.length)
  4262. return (this[offset] << 24) |
  4263. (this[offset + 1] << 16) |
  4264. (this[offset + 2] << 8) |
  4265. (this[offset + 3])
  4266. }
  4267. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  4268. offset = offset >>> 0
  4269. if (!noAssert) checkOffset(offset, 4, this.length)
  4270. return ieee754.read(this, offset, true, 23, 4)
  4271. }
  4272. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  4273. offset = offset >>> 0
  4274. if (!noAssert) checkOffset(offset, 4, this.length)
  4275. return ieee754.read(this, offset, false, 23, 4)
  4276. }
  4277. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  4278. offset = offset >>> 0
  4279. if (!noAssert) checkOffset(offset, 8, this.length)
  4280. return ieee754.read(this, offset, true, 52, 8)
  4281. }
  4282. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  4283. offset = offset >>> 0
  4284. if (!noAssert) checkOffset(offset, 8, this.length)
  4285. return ieee754.read(this, offset, false, 52, 8)
  4286. }
  4287. function checkInt (buf, value, offset, ext, max, min) {
  4288. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  4289. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  4290. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4291. }
  4292. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  4293. value = +value
  4294. offset = offset >>> 0
  4295. byteLength = byteLength >>> 0
  4296. if (!noAssert) {
  4297. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  4298. checkInt(this, value, offset, byteLength, maxBytes, 0)
  4299. }
  4300. var mul = 1
  4301. var i = 0
  4302. this[offset] = value & 0xFF
  4303. while (++i < byteLength && (mul *= 0x100)) {
  4304. this[offset + i] = (value / mul) & 0xFF
  4305. }
  4306. return offset + byteLength
  4307. }
  4308. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  4309. value = +value
  4310. offset = offset >>> 0
  4311. byteLength = byteLength >>> 0
  4312. if (!noAssert) {
  4313. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  4314. checkInt(this, value, offset, byteLength, maxBytes, 0)
  4315. }
  4316. var i = byteLength - 1
  4317. var mul = 1
  4318. this[offset + i] = value & 0xFF
  4319. while (--i >= 0 && (mul *= 0x100)) {
  4320. this[offset + i] = (value / mul) & 0xFF
  4321. }
  4322. return offset + byteLength
  4323. }
  4324. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  4325. value = +value
  4326. offset = offset >>> 0
  4327. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  4328. this[offset] = (value & 0xff)
  4329. return offset + 1
  4330. }
  4331. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  4332. value = +value
  4333. offset = offset >>> 0
  4334. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  4335. this[offset] = (value & 0xff)
  4336. this[offset + 1] = (value >>> 8)
  4337. return offset + 2
  4338. }
  4339. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  4340. value = +value
  4341. offset = offset >>> 0
  4342. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  4343. this[offset] = (value >>> 8)
  4344. this[offset + 1] = (value & 0xff)
  4345. return offset + 2
  4346. }
  4347. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  4348. value = +value
  4349. offset = offset >>> 0
  4350. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  4351. this[offset + 3] = (value >>> 24)
  4352. this[offset + 2] = (value >>> 16)
  4353. this[offset + 1] = (value >>> 8)
  4354. this[offset] = (value & 0xff)
  4355. return offset + 4
  4356. }
  4357. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  4358. value = +value
  4359. offset = offset >>> 0
  4360. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  4361. this[offset] = (value >>> 24)
  4362. this[offset + 1] = (value >>> 16)
  4363. this[offset + 2] = (value >>> 8)
  4364. this[offset + 3] = (value & 0xff)
  4365. return offset + 4
  4366. }
  4367. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  4368. value = +value
  4369. offset = offset >>> 0
  4370. if (!noAssert) {
  4371. var limit = Math.pow(2, (8 * byteLength) - 1)
  4372. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  4373. }
  4374. var i = 0
  4375. var mul = 1
  4376. var sub = 0
  4377. this[offset] = value & 0xFF
  4378. while (++i < byteLength && (mul *= 0x100)) {
  4379. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  4380. sub = 1
  4381. }
  4382. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  4383. }
  4384. return offset + byteLength
  4385. }
  4386. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  4387. value = +value
  4388. offset = offset >>> 0
  4389. if (!noAssert) {
  4390. var limit = Math.pow(2, (8 * byteLength) - 1)
  4391. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  4392. }
  4393. var i = byteLength - 1
  4394. var mul = 1
  4395. var sub = 0
  4396. this[offset + i] = value & 0xFF
  4397. while (--i >= 0 && (mul *= 0x100)) {
  4398. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  4399. sub = 1
  4400. }
  4401. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  4402. }
  4403. return offset + byteLength
  4404. }
  4405. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  4406. value = +value
  4407. offset = offset >>> 0
  4408. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  4409. if (value < 0) value = 0xff + value + 1
  4410. this[offset] = (value & 0xff)
  4411. return offset + 1
  4412. }
  4413. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  4414. value = +value
  4415. offset = offset >>> 0
  4416. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  4417. this[offset] = (value & 0xff)
  4418. this[offset + 1] = (value >>> 8)
  4419. return offset + 2
  4420. }
  4421. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  4422. value = +value
  4423. offset = offset >>> 0
  4424. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  4425. this[offset] = (value >>> 8)
  4426. this[offset + 1] = (value & 0xff)
  4427. return offset + 2
  4428. }
  4429. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  4430. value = +value
  4431. offset = offset >>> 0
  4432. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  4433. this[offset] = (value & 0xff)
  4434. this[offset + 1] = (value >>> 8)
  4435. this[offset + 2] = (value >>> 16)
  4436. this[offset + 3] = (value >>> 24)
  4437. return offset + 4
  4438. }
  4439. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  4440. value = +value
  4441. offset = offset >>> 0
  4442. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  4443. if (value < 0) value = 0xffffffff + value + 1
  4444. this[offset] = (value >>> 24)
  4445. this[offset + 1] = (value >>> 16)
  4446. this[offset + 2] = (value >>> 8)
  4447. this[offset + 3] = (value & 0xff)
  4448. return offset + 4
  4449. }
  4450. function checkIEEE754 (buf, value, offset, ext, max, min) {
  4451. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4452. if (offset < 0) throw new RangeError('Index out of range')
  4453. }
  4454. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  4455. value = +value
  4456. offset = offset >>> 0
  4457. if (!noAssert) {
  4458. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  4459. }
  4460. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  4461. return offset + 4
  4462. }
  4463. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  4464. return writeFloat(this, value, offset, true, noAssert)
  4465. }
  4466. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  4467. return writeFloat(this, value, offset, false, noAssert)
  4468. }
  4469. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  4470. value = +value
  4471. offset = offset >>> 0
  4472. if (!noAssert) {
  4473. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  4474. }
  4475. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  4476. return offset + 8
  4477. }
  4478. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  4479. return writeDouble(this, value, offset, true, noAssert)
  4480. }
  4481. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  4482. return writeDouble(this, value, offset, false, noAssert)
  4483. }
  4484. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  4485. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  4486. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  4487. if (!start) start = 0
  4488. if (!end && end !== 0) end = this.length
  4489. if (targetStart >= target.length) targetStart = target.length
  4490. if (!targetStart) targetStart = 0
  4491. if (end > 0 && end < start) end = start
  4492. // Copy 0 bytes; we're done
  4493. if (end === start) return 0
  4494. if (target.length === 0 || this.length === 0) return 0
  4495. // Fatal error conditions
  4496. if (targetStart < 0) {
  4497. throw new RangeError('targetStart out of bounds')
  4498. }
  4499. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  4500. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  4501. // Are we oob?
  4502. if (end > this.length) end = this.length
  4503. if (target.length - targetStart < end - start) {
  4504. end = target.length - targetStart + start
  4505. }
  4506. var len = end - start
  4507. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  4508. // Use built-in when available, missing from IE11
  4509. this.copyWithin(targetStart, start, end)
  4510. } else if (this === target && start < targetStart && targetStart < end) {
  4511. // descending copy from end
  4512. for (var i = len - 1; i >= 0; --i) {
  4513. target[i + targetStart] = this[i + start]
  4514. }
  4515. } else {
  4516. Uint8Array.prototype.set.call(
  4517. target,
  4518. this.subarray(start, end),
  4519. targetStart
  4520. )
  4521. }
  4522. return len
  4523. }
  4524. // Usage:
  4525. // buffer.fill(number[, offset[, end]])
  4526. // buffer.fill(buffer[, offset[, end]])
  4527. // buffer.fill(string[, offset[, end]][, encoding])
  4528. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  4529. // Handle string cases:
  4530. if (typeof val === 'string') {
  4531. if (typeof start === 'string') {
  4532. encoding = start
  4533. start = 0
  4534. end = this.length
  4535. } else if (typeof end === 'string') {
  4536. encoding = end
  4537. end = this.length
  4538. }
  4539. if (encoding !== undefined && typeof encoding !== 'string') {
  4540. throw new TypeError('encoding must be a string')
  4541. }
  4542. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  4543. throw new TypeError('Unknown encoding: ' + encoding)
  4544. }
  4545. if (val.length === 1) {
  4546. var code = val.charCodeAt(0)
  4547. if ((encoding === 'utf8' && code < 128) ||
  4548. encoding === 'latin1') {
  4549. // Fast path: If `val` fits into a single byte, use that numeric value.
  4550. val = code
  4551. }
  4552. }
  4553. } else if (typeof val === 'number') {
  4554. val = val & 255
  4555. }
  4556. // Invalid ranges are not set to a default, so can range check early.
  4557. if (start < 0 || this.length < start || this.length < end) {
  4558. throw new RangeError('Out of range index')
  4559. }
  4560. if (end <= start) {
  4561. return this
  4562. }
  4563. start = start >>> 0
  4564. end = end === undefined ? this.length : end >>> 0
  4565. if (!val) val = 0
  4566. var i
  4567. if (typeof val === 'number') {
  4568. for (i = start; i < end; ++i) {
  4569. this[i] = val
  4570. }
  4571. } else {
  4572. var bytes = Buffer.isBuffer(val)
  4573. ? val
  4574. : Buffer.from(val, encoding)
  4575. var len = bytes.length
  4576. if (len === 0) {
  4577. throw new TypeError('The value "' + val +
  4578. '" is invalid for argument "value"')
  4579. }
  4580. for (i = 0; i < end - start; ++i) {
  4581. this[i + start] = bytes[i % len]
  4582. }
  4583. }
  4584. return this
  4585. }
  4586. // HELPER FUNCTIONS
  4587. // ================
  4588. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  4589. function base64clean (str) {
  4590. // Node takes equal signs as end of the Base64 encoding
  4591. str = str.split('=')[0]
  4592. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  4593. str = str.trim().replace(INVALID_BASE64_RE, '')
  4594. // Node converts strings with length < 2 to ''
  4595. if (str.length < 2) return ''
  4596. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  4597. while (str.length % 4 !== 0) {
  4598. str = str + '='
  4599. }
  4600. return str
  4601. }
  4602. function toHex (n) {
  4603. if (n < 16) return '0' + n.toString(16)
  4604. return n.toString(16)
  4605. }
  4606. function utf8ToBytes (string, units) {
  4607. units = units || Infinity
  4608. var codePoint
  4609. var length = string.length
  4610. var leadSurrogate = null
  4611. var bytes = []
  4612. for (var i = 0; i < length; ++i) {
  4613. codePoint = string.charCodeAt(i)
  4614. // is surrogate component
  4615. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  4616. // last char was a lead
  4617. if (!leadSurrogate) {
  4618. // no lead yet
  4619. if (codePoint > 0xDBFF) {
  4620. // unexpected trail
  4621. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4622. continue
  4623. } else if (i + 1 === length) {
  4624. // unpaired lead
  4625. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4626. continue
  4627. }
  4628. // valid lead
  4629. leadSurrogate = codePoint
  4630. continue
  4631. }
  4632. // 2 leads in a row
  4633. if (codePoint < 0xDC00) {
  4634. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4635. leadSurrogate = codePoint
  4636. continue
  4637. }
  4638. // valid surrogate pair
  4639. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  4640. } else if (leadSurrogate) {
  4641. // valid bmp char, but last char was a lead
  4642. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4643. }
  4644. leadSurrogate = null
  4645. // encode utf8
  4646. if (codePoint < 0x80) {
  4647. if ((units -= 1) < 0) break
  4648. bytes.push(codePoint)
  4649. } else if (codePoint < 0x800) {
  4650. if ((units -= 2) < 0) break
  4651. bytes.push(
  4652. codePoint >> 0x6 | 0xC0,
  4653. codePoint & 0x3F | 0x80
  4654. )
  4655. } else if (codePoint < 0x10000) {
  4656. if ((units -= 3) < 0) break
  4657. bytes.push(
  4658. codePoint >> 0xC | 0xE0,
  4659. codePoint >> 0x6 & 0x3F | 0x80,
  4660. codePoint & 0x3F | 0x80
  4661. )
  4662. } else if (codePoint < 0x110000) {
  4663. if ((units -= 4) < 0) break
  4664. bytes.push(
  4665. codePoint >> 0x12 | 0xF0,
  4666. codePoint >> 0xC & 0x3F | 0x80,
  4667. codePoint >> 0x6 & 0x3F | 0x80,
  4668. codePoint & 0x3F | 0x80
  4669. )
  4670. } else {
  4671. throw new Error('Invalid code point')
  4672. }
  4673. }
  4674. return bytes
  4675. }
  4676. function asciiToBytes (str) {
  4677. var byteArray = []
  4678. for (var i = 0; i < str.length; ++i) {
  4679. // Node's code seems to be doing this and not & 0x7F..
  4680. byteArray.push(str.charCodeAt(i) & 0xFF)
  4681. }
  4682. return byteArray
  4683. }
  4684. function utf16leToBytes (str, units) {
  4685. var c, hi, lo
  4686. var byteArray = []
  4687. for (var i = 0; i < str.length; ++i) {
  4688. if ((units -= 2) < 0) break
  4689. c = str.charCodeAt(i)
  4690. hi = c >> 8
  4691. lo = c % 256
  4692. byteArray.push(lo)
  4693. byteArray.push(hi)
  4694. }
  4695. return byteArray
  4696. }
  4697. function base64ToBytes (str) {
  4698. return base64.toByteArray(base64clean(str))
  4699. }
  4700. function blitBuffer (src, dst, offset, length) {
  4701. for (var i = 0; i < length; ++i) {
  4702. if ((i + offset >= dst.length) || (i >= src.length)) break
  4703. dst[i + offset] = src[i]
  4704. }
  4705. return i
  4706. }
  4707. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  4708. // the `instanceof` check but they should be treated as of that type.
  4709. // See: https://github.com/feross/buffer/issues/166
  4710. function isInstance (obj, type) {
  4711. return obj instanceof type ||
  4712. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  4713. obj.constructor.name === type.name)
  4714. }
  4715. function numberIsNaN (obj) {
  4716. // For IE11 support
  4717. return obj !== obj // eslint-disable-line no-self-compare
  4718. }
  4719. }).call(this)}).call(this,require("buffer").Buffer)
  4720. },{"base64-js":13,"buffer":17,"ieee754":23}],18:[function(require,module,exports){
  4721. (function (process){(function (){
  4722. /* eslint-env browser */
  4723. /**
  4724. * This is the web browser implementation of `debug()`.
  4725. */
  4726. exports.formatArgs = formatArgs;
  4727. exports.save = save;
  4728. exports.load = load;
  4729. exports.useColors = useColors;
  4730. exports.storage = localstorage();
  4731. exports.destroy = (() => {
  4732. let warned = false;
  4733. return () => {
  4734. if (!warned) {
  4735. warned = true;
  4736. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  4737. }
  4738. };
  4739. })();
  4740. /**
  4741. * Colors.
  4742. */
  4743. exports.colors = [
  4744. '#0000CC',
  4745. '#0000FF',
  4746. '#0033CC',
  4747. '#0033FF',
  4748. '#0066CC',
  4749. '#0066FF',
  4750. '#0099CC',
  4751. '#0099FF',
  4752. '#00CC00',
  4753. '#00CC33',
  4754. '#00CC66',
  4755. '#00CC99',
  4756. '#00CCCC',
  4757. '#00CCFF',
  4758. '#3300CC',
  4759. '#3300FF',
  4760. '#3333CC',
  4761. '#3333FF',
  4762. '#3366CC',
  4763. '#3366FF',
  4764. '#3399CC',
  4765. '#3399FF',
  4766. '#33CC00',
  4767. '#33CC33',
  4768. '#33CC66',
  4769. '#33CC99',
  4770. '#33CCCC',
  4771. '#33CCFF',
  4772. '#6600CC',
  4773. '#6600FF',
  4774. '#6633CC',
  4775. '#6633FF',
  4776. '#66CC00',
  4777. '#66CC33',
  4778. '#9900CC',
  4779. '#9900FF',
  4780. '#9933CC',
  4781. '#9933FF',
  4782. '#99CC00',
  4783. '#99CC33',
  4784. '#CC0000',
  4785. '#CC0033',
  4786. '#CC0066',
  4787. '#CC0099',
  4788. '#CC00CC',
  4789. '#CC00FF',
  4790. '#CC3300',
  4791. '#CC3333',
  4792. '#CC3366',
  4793. '#CC3399',
  4794. '#CC33CC',
  4795. '#CC33FF',
  4796. '#CC6600',
  4797. '#CC6633',
  4798. '#CC9900',
  4799. '#CC9933',
  4800. '#CCCC00',
  4801. '#CCCC33',
  4802. '#FF0000',
  4803. '#FF0033',
  4804. '#FF0066',
  4805. '#FF0099',
  4806. '#FF00CC',
  4807. '#FF00FF',
  4808. '#FF3300',
  4809. '#FF3333',
  4810. '#FF3366',
  4811. '#FF3399',
  4812. '#FF33CC',
  4813. '#FF33FF',
  4814. '#FF6600',
  4815. '#FF6633',
  4816. '#FF9900',
  4817. '#FF9933',
  4818. '#FFCC00',
  4819. '#FFCC33'
  4820. ];
  4821. /**
  4822. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  4823. * and the Firebug extension (any Firefox version) are known
  4824. * to support "%c" CSS customizations.
  4825. *
  4826. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  4827. */
  4828. // eslint-disable-next-line complexity
  4829. function useColors() {
  4830. // NB: In an Electron preload script, document will be defined but not fully
  4831. // initialized. Since we know we're in Chrome, we'll just detect this case
  4832. // explicitly
  4833. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  4834. return true;
  4835. }
  4836. // Internet Explorer and Edge do not support colors.
  4837. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  4838. return false;
  4839. }
  4840. // Is webkit? http://stackoverflow.com/a/16459606/376773
  4841. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  4842. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  4843. // Is firebug? http://stackoverflow.com/a/398120/376773
  4844. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  4845. // Is firefox >= v31?
  4846. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  4847. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  4848. // Double check webkit in userAgent just in case we are in a worker
  4849. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  4850. }
  4851. /**
  4852. * Colorize log arguments if enabled.
  4853. *
  4854. * @api public
  4855. */
  4856. function formatArgs(args) {
  4857. args[0] = (this.useColors ? '%c' : '') +
  4858. this.namespace +
  4859. (this.useColors ? ' %c' : ' ') +
  4860. args[0] +
  4861. (this.useColors ? '%c ' : ' ') +
  4862. '+' + module.exports.humanize(this.diff);
  4863. if (!this.useColors) {
  4864. return;
  4865. }
  4866. const c = 'color: ' + this.color;
  4867. args.splice(1, 0, c, 'color: inherit');
  4868. // The final "%c" is somewhat tricky, because there could be other
  4869. // arguments passed either before or after the %c, so we need to
  4870. // figure out the correct index to insert the CSS into
  4871. let index = 0;
  4872. let lastC = 0;
  4873. args[0].replace(/%[a-zA-Z%]/g, match => {
  4874. if (match === '%%') {
  4875. return;
  4876. }
  4877. index++;
  4878. if (match === '%c') {
  4879. // We only are interested in the *last* %c
  4880. // (the user may have provided their own)
  4881. lastC = index;
  4882. }
  4883. });
  4884. args.splice(lastC, 0, c);
  4885. }
  4886. /**
  4887. * Invokes `console.debug()` when available.
  4888. * No-op when `console.debug` is not a "function".
  4889. * If `console.debug` is not available, falls back
  4890. * to `console.log`.
  4891. *
  4892. * @api public
  4893. */
  4894. exports.log = console.debug || console.log || (() => {});
  4895. /**
  4896. * Save `namespaces`.
  4897. *
  4898. * @param {String} namespaces
  4899. * @api private
  4900. */
  4901. function save(namespaces) {
  4902. try {
  4903. if (namespaces) {
  4904. exports.storage.setItem('debug', namespaces);
  4905. } else {
  4906. exports.storage.removeItem('debug');
  4907. }
  4908. } catch (error) {
  4909. // Swallow
  4910. // XXX (@Qix-) should we be logging these?
  4911. }
  4912. }
  4913. /**
  4914. * Load `namespaces`.
  4915. *
  4916. * @return {String} returns the previously persisted debug modes
  4917. * @api private
  4918. */
  4919. function load() {
  4920. let r;
  4921. try {
  4922. r = exports.storage.getItem('debug');
  4923. } catch (error) {
  4924. // Swallow
  4925. // XXX (@Qix-) should we be logging these?
  4926. }
  4927. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  4928. if (!r && typeof process !== 'undefined' && 'env' in process) {
  4929. r = process.env.DEBUG;
  4930. }
  4931. return r;
  4932. }
  4933. /**
  4934. * Localstorage attempts to return the localstorage.
  4935. *
  4936. * This is necessary because safari throws
  4937. * when a user disables cookies/localstorage
  4938. * and you attempt to access it.
  4939. *
  4940. * @return {LocalStorage}
  4941. * @api private
  4942. */
  4943. function localstorage() {
  4944. try {
  4945. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  4946. // The Browser also has localStorage in the global context.
  4947. return localStorage;
  4948. } catch (error) {
  4949. // Swallow
  4950. // XXX (@Qix-) should we be logging these?
  4951. }
  4952. }
  4953. module.exports = require('./common')(exports);
  4954. const {formatters} = module.exports;
  4955. /**
  4956. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  4957. */
  4958. formatters.j = function (v) {
  4959. try {
  4960. return JSON.stringify(v);
  4961. } catch (error) {
  4962. return '[UnexpectedJSONParseError]: ' + error.message;
  4963. }
  4964. };
  4965. }).call(this)}).call(this,require('_process'))
  4966. },{"./common":19,"_process":50}],19:[function(require,module,exports){
  4967. /**
  4968. * This is the common logic for both the Node.js and web browser
  4969. * implementations of `debug()`.
  4970. */
  4971. function setup(env) {
  4972. createDebug.debug = createDebug;
  4973. createDebug.default = createDebug;
  4974. createDebug.coerce = coerce;
  4975. createDebug.disable = disable;
  4976. createDebug.enable = enable;
  4977. createDebug.enabled = enabled;
  4978. createDebug.humanize = require('ms');
  4979. createDebug.destroy = destroy;
  4980. Object.keys(env).forEach(key => {
  4981. createDebug[key] = env[key];
  4982. });
  4983. /**
  4984. * The currently active debug mode names, and names to skip.
  4985. */
  4986. createDebug.names = [];
  4987. createDebug.skips = [];
  4988. /**
  4989. * Map of special "%n" handling functions, for the debug "format" argument.
  4990. *
  4991. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  4992. */
  4993. createDebug.formatters = {};
  4994. /**
  4995. * Selects a color for a debug namespace
  4996. * @param {String} namespace The namespace string for the debug instance to be colored
  4997. * @return {Number|String} An ANSI color code for the given namespace
  4998. * @api private
  4999. */
  5000. function selectColor(namespace) {
  5001. let hash = 0;
  5002. for (let i = 0; i < namespace.length; i++) {
  5003. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  5004. hash |= 0; // Convert to 32bit integer
  5005. }
  5006. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  5007. }
  5008. createDebug.selectColor = selectColor;
  5009. /**
  5010. * Create a debugger with the given `namespace`.
  5011. *
  5012. * @param {String} namespace
  5013. * @return {Function}
  5014. * @api public
  5015. */
  5016. function createDebug(namespace) {
  5017. let prevTime;
  5018. let enableOverride = null;
  5019. let namespacesCache;
  5020. let enabledCache;
  5021. function debug(...args) {
  5022. // Disabled?
  5023. if (!debug.enabled) {
  5024. return;
  5025. }
  5026. const self = debug;
  5027. // Set `diff` timestamp
  5028. const curr = Number(new Date());
  5029. const ms = curr - (prevTime || curr);
  5030. self.diff = ms;
  5031. self.prev = prevTime;
  5032. self.curr = curr;
  5033. prevTime = curr;
  5034. args[0] = createDebug.coerce(args[0]);
  5035. if (typeof args[0] !== 'string') {
  5036. // Anything else let's inspect with %O
  5037. args.unshift('%O');
  5038. }
  5039. // Apply any `formatters` transformations
  5040. let index = 0;
  5041. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  5042. // If we encounter an escaped % then don't increase the array index
  5043. if (match === '%%') {
  5044. return '%';
  5045. }
  5046. index++;
  5047. const formatter = createDebug.formatters[format];
  5048. if (typeof formatter === 'function') {
  5049. const val = args[index];
  5050. match = formatter.call(self, val);
  5051. // Now we need to remove `args[index]` since it's inlined in the `format`
  5052. args.splice(index, 1);
  5053. index--;
  5054. }
  5055. return match;
  5056. });
  5057. // Apply env-specific formatting (colors, etc.)
  5058. createDebug.formatArgs.call(self, args);
  5059. const logFn = self.log || createDebug.log;
  5060. logFn.apply(self, args);
  5061. }
  5062. debug.namespace = namespace;
  5063. debug.useColors = createDebug.useColors();
  5064. debug.color = createDebug.selectColor(namespace);
  5065. debug.extend = extend;
  5066. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  5067. Object.defineProperty(debug, 'enabled', {
  5068. enumerable: true,
  5069. configurable: false,
  5070. get: () => {
  5071. if (enableOverride !== null) {
  5072. return enableOverride;
  5073. }
  5074. if (namespacesCache !== createDebug.namespaces) {
  5075. namespacesCache = createDebug.namespaces;
  5076. enabledCache = createDebug.enabled(namespace);
  5077. }
  5078. return enabledCache;
  5079. },
  5080. set: v => {
  5081. enableOverride = v;
  5082. }
  5083. });
  5084. // Env-specific initialization logic for debug instances
  5085. if (typeof createDebug.init === 'function') {
  5086. createDebug.init(debug);
  5087. }
  5088. return debug;
  5089. }
  5090. function extend(namespace, delimiter) {
  5091. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  5092. newDebug.log = this.log;
  5093. return newDebug;
  5094. }
  5095. /**
  5096. * Enables a debug mode by namespaces. This can include modes
  5097. * separated by a colon and wildcards.
  5098. *
  5099. * @param {String} namespaces
  5100. * @api public
  5101. */
  5102. function enable(namespaces) {
  5103. createDebug.save(namespaces);
  5104. createDebug.namespaces = namespaces;
  5105. createDebug.names = [];
  5106. createDebug.skips = [];
  5107. let i;
  5108. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  5109. const len = split.length;
  5110. for (i = 0; i < len; i++) {
  5111. if (!split[i]) {
  5112. // ignore empty strings
  5113. continue;
  5114. }
  5115. namespaces = split[i].replace(/\*/g, '.*?');
  5116. if (namespaces[0] === '-') {
  5117. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  5118. } else {
  5119. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  5120. }
  5121. }
  5122. }
  5123. /**
  5124. * Disable debug output.
  5125. *
  5126. * @return {String} namespaces
  5127. * @api public
  5128. */
  5129. function disable() {
  5130. const namespaces = [
  5131. ...createDebug.names.map(toNamespace),
  5132. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  5133. ].join(',');
  5134. createDebug.enable('');
  5135. return namespaces;
  5136. }
  5137. /**
  5138. * Returns true if the given mode name is enabled, false otherwise.
  5139. *
  5140. * @param {String} name
  5141. * @return {Boolean}
  5142. * @api public
  5143. */
  5144. function enabled(name) {
  5145. if (name[name.length - 1] === '*') {
  5146. return true;
  5147. }
  5148. let i;
  5149. let len;
  5150. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  5151. if (createDebug.skips[i].test(name)) {
  5152. return false;
  5153. }
  5154. }
  5155. for (i = 0, len = createDebug.names.length; i < len; i++) {
  5156. if (createDebug.names[i].test(name)) {
  5157. return true;
  5158. }
  5159. }
  5160. return false;
  5161. }
  5162. /**
  5163. * Convert regexp to namespace
  5164. *
  5165. * @param {RegExp} regxep
  5166. * @return {String} namespace
  5167. * @api private
  5168. */
  5169. function toNamespace(regexp) {
  5170. return regexp.toString()
  5171. .substring(2, regexp.toString().length - 2)
  5172. .replace(/\.\*\?$/, '*');
  5173. }
  5174. /**
  5175. * Coerce `val`.
  5176. *
  5177. * @param {Mixed} val
  5178. * @return {Mixed}
  5179. * @api private
  5180. */
  5181. function coerce(val) {
  5182. if (val instanceof Error) {
  5183. return val.stack || val.message;
  5184. }
  5185. return val;
  5186. }
  5187. /**
  5188. * XXX DO NOT USE. This is a temporary stub function.
  5189. * XXX It WILL be removed in the next major release.
  5190. */
  5191. function destroy() {
  5192. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  5193. }
  5194. createDebug.enable(createDebug.load());
  5195. return createDebug;
  5196. }
  5197. module.exports = setup;
  5198. },{"ms":45}],20:[function(require,module,exports){
  5199. (function (process,Buffer){(function (){
  5200. var stream = require('readable-stream')
  5201. var eos = require('end-of-stream')
  5202. var inherits = require('inherits')
  5203. var shift = require('stream-shift')
  5204. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  5205. ? Buffer.from([0])
  5206. : new Buffer([0])
  5207. var onuncork = function(self, fn) {
  5208. if (self._corked) self.once('uncork', fn)
  5209. else fn()
  5210. }
  5211. var autoDestroy = function (self, err) {
  5212. if (self._autoDestroy) self.destroy(err)
  5213. }
  5214. var destroyer = function(self, end) {
  5215. return function(err) {
  5216. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  5217. else if (end && !self._ended) self.end()
  5218. }
  5219. }
  5220. var end = function(ws, fn) {
  5221. if (!ws) return fn()
  5222. if (ws._writableState && ws._writableState.finished) return fn()
  5223. if (ws._writableState) return ws.end(fn)
  5224. ws.end()
  5225. fn()
  5226. }
  5227. var noop = function() {}
  5228. var toStreams2 = function(rs) {
  5229. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  5230. }
  5231. var Duplexify = function(writable, readable, opts) {
  5232. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  5233. stream.Duplex.call(this, opts)
  5234. this._writable = null
  5235. this._readable = null
  5236. this._readable2 = null
  5237. this._autoDestroy = !opts || opts.autoDestroy !== false
  5238. this._forwardDestroy = !opts || opts.destroy !== false
  5239. this._forwardEnd = !opts || opts.end !== false
  5240. this._corked = 1 // start corked
  5241. this._ondrain = null
  5242. this._drained = false
  5243. this._forwarding = false
  5244. this._unwrite = null
  5245. this._unread = null
  5246. this._ended = false
  5247. this.destroyed = false
  5248. if (writable) this.setWritable(writable)
  5249. if (readable) this.setReadable(readable)
  5250. }
  5251. inherits(Duplexify, stream.Duplex)
  5252. Duplexify.obj = function(writable, readable, opts) {
  5253. if (!opts) opts = {}
  5254. opts.objectMode = true
  5255. opts.highWaterMark = 16
  5256. return new Duplexify(writable, readable, opts)
  5257. }
  5258. Duplexify.prototype.cork = function() {
  5259. if (++this._corked === 1) this.emit('cork')
  5260. }
  5261. Duplexify.prototype.uncork = function() {
  5262. if (this._corked && --this._corked === 0) this.emit('uncork')
  5263. }
  5264. Duplexify.prototype.setWritable = function(writable) {
  5265. if (this._unwrite) this._unwrite()
  5266. if (this.destroyed) {
  5267. if (writable && writable.destroy) writable.destroy()
  5268. return
  5269. }
  5270. if (writable === null || writable === false) {
  5271. this.end()
  5272. return
  5273. }
  5274. var self = this
  5275. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  5276. var ondrain = function() {
  5277. var ondrain = self._ondrain
  5278. self._ondrain = null
  5279. if (ondrain) ondrain()
  5280. }
  5281. var clear = function() {
  5282. self._writable.removeListener('drain', ondrain)
  5283. unend()
  5284. }
  5285. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  5286. this._writable = writable
  5287. this._writable.on('drain', ondrain)
  5288. this._unwrite = clear
  5289. this.uncork() // always uncork setWritable
  5290. }
  5291. Duplexify.prototype.setReadable = function(readable) {
  5292. if (this._unread) this._unread()
  5293. if (this.destroyed) {
  5294. if (readable && readable.destroy) readable.destroy()
  5295. return
  5296. }
  5297. if (readable === null || readable === false) {
  5298. this.push(null)
  5299. this.resume()
  5300. return
  5301. }
  5302. var self = this
  5303. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  5304. var onreadable = function() {
  5305. self._forward()
  5306. }
  5307. var onend = function() {
  5308. self.push(null)
  5309. }
  5310. var clear = function() {
  5311. self._readable2.removeListener('readable', onreadable)
  5312. self._readable2.removeListener('end', onend)
  5313. unend()
  5314. }
  5315. this._drained = true
  5316. this._readable = readable
  5317. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  5318. this._readable2.on('readable', onreadable)
  5319. this._readable2.on('end', onend)
  5320. this._unread = clear
  5321. this._forward()
  5322. }
  5323. Duplexify.prototype._read = function() {
  5324. this._drained = true
  5325. this._forward()
  5326. }
  5327. Duplexify.prototype._forward = function() {
  5328. if (this._forwarding || !this._readable2 || !this._drained) return
  5329. this._forwarding = true
  5330. var data
  5331. while (this._drained && (data = shift(this._readable2)) !== null) {
  5332. if (this.destroyed) continue
  5333. this._drained = this.push(data)
  5334. }
  5335. this._forwarding = false
  5336. }
  5337. Duplexify.prototype.destroy = function(err, cb) {
  5338. if (!cb) cb = noop
  5339. if (this.destroyed) return cb(null)
  5340. this.destroyed = true
  5341. var self = this
  5342. process.nextTick(function() {
  5343. self._destroy(err)
  5344. cb(null)
  5345. })
  5346. }
  5347. Duplexify.prototype._destroy = function(err) {
  5348. if (err) {
  5349. var ondrain = this._ondrain
  5350. this._ondrain = null
  5351. if (ondrain) ondrain(err)
  5352. else this.emit('error', err)
  5353. }
  5354. if (this._forwardDestroy) {
  5355. if (this._readable && this._readable.destroy) this._readable.destroy()
  5356. if (this._writable && this._writable.destroy) this._writable.destroy()
  5357. }
  5358. this.emit('close')
  5359. }
  5360. Duplexify.prototype._write = function(data, enc, cb) {
  5361. if (this.destroyed) return
  5362. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  5363. if (data === SIGNAL_FLUSH) return this._finish(cb)
  5364. if (!this._writable) return cb()
  5365. if (this._writable.write(data) === false) this._ondrain = cb
  5366. else if (!this.destroyed) cb()
  5367. }
  5368. Duplexify.prototype._finish = function(cb) {
  5369. var self = this
  5370. this.emit('preend')
  5371. onuncork(this, function() {
  5372. end(self._forwardEnd && self._writable, function() {
  5373. // haxx to not emit prefinish twice
  5374. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  5375. self.emit('prefinish')
  5376. onuncork(self, cb)
  5377. })
  5378. })
  5379. }
  5380. Duplexify.prototype.end = function(data, enc, cb) {
  5381. if (typeof data === 'function') return this.end(null, null, data)
  5382. if (typeof enc === 'function') return this.end(data, null, enc)
  5383. this._ended = true
  5384. if (data) this.write(data)
  5385. if (!this._writableState.ending && !this._writableState.destroyed) this.write(SIGNAL_FLUSH)
  5386. return stream.Writable.prototype.end.call(this, cb)
  5387. }
  5388. module.exports = Duplexify
  5389. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  5390. },{"_process":50,"buffer":17,"end-of-stream":21,"inherits":24,"readable-stream":69,"stream-shift":74}],21:[function(require,module,exports){
  5391. (function (process){(function (){
  5392. var once = require('once');
  5393. var noop = function() {};
  5394. var isRequest = function(stream) {
  5395. return stream.setHeader && typeof stream.abort === 'function';
  5396. };
  5397. var isChildProcess = function(stream) {
  5398. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  5399. };
  5400. var eos = function(stream, opts, callback) {
  5401. if (typeof opts === 'function') return eos(stream, null, opts);
  5402. if (!opts) opts = {};
  5403. callback = once(callback || noop);
  5404. var ws = stream._writableState;
  5405. var rs = stream._readableState;
  5406. var readable = opts.readable || (opts.readable !== false && stream.readable);
  5407. var writable = opts.writable || (opts.writable !== false && stream.writable);
  5408. var cancelled = false;
  5409. var onlegacyfinish = function() {
  5410. if (!stream.writable) onfinish();
  5411. };
  5412. var onfinish = function() {
  5413. writable = false;
  5414. if (!readable) callback.call(stream);
  5415. };
  5416. var onend = function() {
  5417. readable = false;
  5418. if (!writable) callback.call(stream);
  5419. };
  5420. var onexit = function(exitCode) {
  5421. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  5422. };
  5423. var onerror = function(err) {
  5424. callback.call(stream, err);
  5425. };
  5426. var onclose = function() {
  5427. process.nextTick(onclosenexttick);
  5428. };
  5429. var onclosenexttick = function() {
  5430. if (cancelled) return;
  5431. if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
  5432. if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
  5433. };
  5434. var onrequest = function() {
  5435. stream.req.on('finish', onfinish);
  5436. };
  5437. if (isRequest(stream)) {
  5438. stream.on('complete', onfinish);
  5439. stream.on('abort', onclose);
  5440. if (stream.req) onrequest();
  5441. else stream.on('request', onrequest);
  5442. } else if (writable && !ws) { // legacy streams
  5443. stream.on('end', onlegacyfinish);
  5444. stream.on('close', onlegacyfinish);
  5445. }
  5446. if (isChildProcess(stream)) stream.on('exit', onexit);
  5447. stream.on('end', onend);
  5448. stream.on('finish', onfinish);
  5449. if (opts.error !== false) stream.on('error', onerror);
  5450. stream.on('close', onclose);
  5451. return function() {
  5452. cancelled = true;
  5453. stream.removeListener('complete', onfinish);
  5454. stream.removeListener('abort', onclose);
  5455. stream.removeListener('request', onrequest);
  5456. if (stream.req) stream.req.removeListener('finish', onfinish);
  5457. stream.removeListener('end', onlegacyfinish);
  5458. stream.removeListener('close', onlegacyfinish);
  5459. stream.removeListener('finish', onfinish);
  5460. stream.removeListener('exit', onexit);
  5461. stream.removeListener('end', onend);
  5462. stream.removeListener('error', onerror);
  5463. stream.removeListener('close', onclose);
  5464. };
  5465. };
  5466. module.exports = eos;
  5467. }).call(this)}).call(this,require('_process'))
  5468. },{"_process":50,"once":48}],22:[function(require,module,exports){
  5469. // Copyright Joyent, Inc. and other Node contributors.
  5470. //
  5471. // Permission is hereby granted, free of charge, to any person obtaining a
  5472. // copy of this software and associated documentation files (the
  5473. // "Software"), to deal in the Software without restriction, including
  5474. // without limitation the rights to use, copy, modify, merge, publish,
  5475. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5476. // persons to whom the Software is furnished to do so, subject to the
  5477. // following conditions:
  5478. //
  5479. // The above copyright notice and this permission notice shall be included
  5480. // in all copies or substantial portions of the Software.
  5481. //
  5482. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5483. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5484. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5485. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5486. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5487. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5488. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5489. var objectCreate = Object.create || objectCreatePolyfill
  5490. var objectKeys = Object.keys || objectKeysPolyfill
  5491. var bind = Function.prototype.bind || functionBindPolyfill
  5492. function EventEmitter() {
  5493. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  5494. this._events = objectCreate(null);
  5495. this._eventsCount = 0;
  5496. }
  5497. this._maxListeners = this._maxListeners || undefined;
  5498. }
  5499. module.exports = EventEmitter;
  5500. // Backwards-compat with node 0.10.x
  5501. EventEmitter.EventEmitter = EventEmitter;
  5502. EventEmitter.prototype._events = undefined;
  5503. EventEmitter.prototype._maxListeners = undefined;
  5504. // By default EventEmitters will print a warning if more than 10 listeners are
  5505. // added to it. This is a useful default which helps finding memory leaks.
  5506. var defaultMaxListeners = 10;
  5507. var hasDefineProperty;
  5508. try {
  5509. var o = {};
  5510. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  5511. hasDefineProperty = o.x === 0;
  5512. } catch (err) { hasDefineProperty = false }
  5513. if (hasDefineProperty) {
  5514. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  5515. enumerable: true,
  5516. get: function() {
  5517. return defaultMaxListeners;
  5518. },
  5519. set: function(arg) {
  5520. // check whether the input is a positive number (whose value is zero or
  5521. // greater and not a NaN).
  5522. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  5523. throw new TypeError('"defaultMaxListeners" must be a positive number');
  5524. defaultMaxListeners = arg;
  5525. }
  5526. });
  5527. } else {
  5528. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  5529. }
  5530. // Obviously not all Emitters should be limited to 10. This function allows
  5531. // that to be increased. Set to zero for unlimited.
  5532. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  5533. if (typeof n !== 'number' || n < 0 || isNaN(n))
  5534. throw new TypeError('"n" argument must be a positive number');
  5535. this._maxListeners = n;
  5536. return this;
  5537. };
  5538. function $getMaxListeners(that) {
  5539. if (that._maxListeners === undefined)
  5540. return EventEmitter.defaultMaxListeners;
  5541. return that._maxListeners;
  5542. }
  5543. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  5544. return $getMaxListeners(this);
  5545. };
  5546. // These standalone emit* functions are used to optimize calling of event
  5547. // handlers for fast cases because emit() itself often has a variable number of
  5548. // arguments and can be deoptimized because of that. These functions always have
  5549. // the same number of arguments and thus do not get deoptimized, so the code
  5550. // inside them can execute faster.
  5551. function emitNone(handler, isFn, self) {
  5552. if (isFn)
  5553. handler.call(self);
  5554. else {
  5555. var len = handler.length;
  5556. var listeners = arrayClone(handler, len);
  5557. for (var i = 0; i < len; ++i)
  5558. listeners[i].call(self);
  5559. }
  5560. }
  5561. function emitOne(handler, isFn, self, arg1) {
  5562. if (isFn)
  5563. handler.call(self, arg1);
  5564. else {
  5565. var len = handler.length;
  5566. var listeners = arrayClone(handler, len);
  5567. for (var i = 0; i < len; ++i)
  5568. listeners[i].call(self, arg1);
  5569. }
  5570. }
  5571. function emitTwo(handler, isFn, self, arg1, arg2) {
  5572. if (isFn)
  5573. handler.call(self, arg1, arg2);
  5574. else {
  5575. var len = handler.length;
  5576. var listeners = arrayClone(handler, len);
  5577. for (var i = 0; i < len; ++i)
  5578. listeners[i].call(self, arg1, arg2);
  5579. }
  5580. }
  5581. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  5582. if (isFn)
  5583. handler.call(self, arg1, arg2, arg3);
  5584. else {
  5585. var len = handler.length;
  5586. var listeners = arrayClone(handler, len);
  5587. for (var i = 0; i < len; ++i)
  5588. listeners[i].call(self, arg1, arg2, arg3);
  5589. }
  5590. }
  5591. function emitMany(handler, isFn, self, args) {
  5592. if (isFn)
  5593. handler.apply(self, args);
  5594. else {
  5595. var len = handler.length;
  5596. var listeners = arrayClone(handler, len);
  5597. for (var i = 0; i < len; ++i)
  5598. listeners[i].apply(self, args);
  5599. }
  5600. }
  5601. EventEmitter.prototype.emit = function emit(type) {
  5602. var er, handler, len, args, i, events;
  5603. var doError = (type === 'error');
  5604. events = this._events;
  5605. if (events)
  5606. doError = (doError && events.error == null);
  5607. else if (!doError)
  5608. return false;
  5609. // If there is no 'error' event listener then throw.
  5610. if (doError) {
  5611. if (arguments.length > 1)
  5612. er = arguments[1];
  5613. if (er instanceof Error) {
  5614. throw er; // Unhandled 'error' event
  5615. } else {
  5616. // At least give some kind of context to the user
  5617. var err = new Error('Unhandled "error" event. (' + er + ')');
  5618. err.context = er;
  5619. throw err;
  5620. }
  5621. return false;
  5622. }
  5623. handler = events[type];
  5624. if (!handler)
  5625. return false;
  5626. var isFn = typeof handler === 'function';
  5627. len = arguments.length;
  5628. switch (len) {
  5629. // fast cases
  5630. case 1:
  5631. emitNone(handler, isFn, this);
  5632. break;
  5633. case 2:
  5634. emitOne(handler, isFn, this, arguments[1]);
  5635. break;
  5636. case 3:
  5637. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  5638. break;
  5639. case 4:
  5640. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  5641. break;
  5642. // slower
  5643. default:
  5644. args = new Array(len - 1);
  5645. for (i = 1; i < len; i++)
  5646. args[i - 1] = arguments[i];
  5647. emitMany(handler, isFn, this, args);
  5648. }
  5649. return true;
  5650. };
  5651. function _addListener(target, type, listener, prepend) {
  5652. var m;
  5653. var events;
  5654. var existing;
  5655. if (typeof listener !== 'function')
  5656. throw new TypeError('"listener" argument must be a function');
  5657. events = target._events;
  5658. if (!events) {
  5659. events = target._events = objectCreate(null);
  5660. target._eventsCount = 0;
  5661. } else {
  5662. // To avoid recursion in the case that type === "newListener"! Before
  5663. // adding it to the listeners, first emit "newListener".
  5664. if (events.newListener) {
  5665. target.emit('newListener', type,
  5666. listener.listener ? listener.listener : listener);
  5667. // Re-assign `events` because a newListener handler could have caused the
  5668. // this._events to be assigned to a new object
  5669. events = target._events;
  5670. }
  5671. existing = events[type];
  5672. }
  5673. if (!existing) {
  5674. // Optimize the case of one listener. Don't need the extra array object.
  5675. existing = events[type] = listener;
  5676. ++target._eventsCount;
  5677. } else {
  5678. if (typeof existing === 'function') {
  5679. // Adding the second element, need to change to array.
  5680. existing = events[type] =
  5681. prepend ? [listener, existing] : [existing, listener];
  5682. } else {
  5683. // If we've already got an array, just append.
  5684. if (prepend) {
  5685. existing.unshift(listener);
  5686. } else {
  5687. existing.push(listener);
  5688. }
  5689. }
  5690. // Check for listener leak
  5691. if (!existing.warned) {
  5692. m = $getMaxListeners(target);
  5693. if (m && m > 0 && existing.length > m) {
  5694. existing.warned = true;
  5695. var w = new Error('Possible EventEmitter memory leak detected. ' +
  5696. existing.length + ' "' + String(type) + '" listeners ' +
  5697. 'added. Use emitter.setMaxListeners() to ' +
  5698. 'increase limit.');
  5699. w.name = 'MaxListenersExceededWarning';
  5700. w.emitter = target;
  5701. w.type = type;
  5702. w.count = existing.length;
  5703. if (typeof console === 'object' && console.warn) {
  5704. console.warn('%s: %s', w.name, w.message);
  5705. }
  5706. }
  5707. }
  5708. }
  5709. return target;
  5710. }
  5711. EventEmitter.prototype.addListener = function addListener(type, listener) {
  5712. return _addListener(this, type, listener, false);
  5713. };
  5714. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  5715. EventEmitter.prototype.prependListener =
  5716. function prependListener(type, listener) {
  5717. return _addListener(this, type, listener, true);
  5718. };
  5719. function onceWrapper() {
  5720. if (!this.fired) {
  5721. this.target.removeListener(this.type, this.wrapFn);
  5722. this.fired = true;
  5723. switch (arguments.length) {
  5724. case 0:
  5725. return this.listener.call(this.target);
  5726. case 1:
  5727. return this.listener.call(this.target, arguments[0]);
  5728. case 2:
  5729. return this.listener.call(this.target, arguments[0], arguments[1]);
  5730. case 3:
  5731. return this.listener.call(this.target, arguments[0], arguments[1],
  5732. arguments[2]);
  5733. default:
  5734. var args = new Array(arguments.length);
  5735. for (var i = 0; i < args.length; ++i)
  5736. args[i] = arguments[i];
  5737. this.listener.apply(this.target, args);
  5738. }
  5739. }
  5740. }
  5741. function _onceWrap(target, type, listener) {
  5742. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  5743. var wrapped = bind.call(onceWrapper, state);
  5744. wrapped.listener = listener;
  5745. state.wrapFn = wrapped;
  5746. return wrapped;
  5747. }
  5748. EventEmitter.prototype.once = function once(type, listener) {
  5749. if (typeof listener !== 'function')
  5750. throw new TypeError('"listener" argument must be a function');
  5751. this.on(type, _onceWrap(this, type, listener));
  5752. return this;
  5753. };
  5754. EventEmitter.prototype.prependOnceListener =
  5755. function prependOnceListener(type, listener) {
  5756. if (typeof listener !== 'function')
  5757. throw new TypeError('"listener" argument must be a function');
  5758. this.prependListener(type, _onceWrap(this, type, listener));
  5759. return this;
  5760. };
  5761. // Emits a 'removeListener' event if and only if the listener was removed.
  5762. EventEmitter.prototype.removeListener =
  5763. function removeListener(type, listener) {
  5764. var list, events, position, i, originalListener;
  5765. if (typeof listener !== 'function')
  5766. throw new TypeError('"listener" argument must be a function');
  5767. events = this._events;
  5768. if (!events)
  5769. return this;
  5770. list = events[type];
  5771. if (!list)
  5772. return this;
  5773. if (list === listener || list.listener === listener) {
  5774. if (--this._eventsCount === 0)
  5775. this._events = objectCreate(null);
  5776. else {
  5777. delete events[type];
  5778. if (events.removeListener)
  5779. this.emit('removeListener', type, list.listener || listener);
  5780. }
  5781. } else if (typeof list !== 'function') {
  5782. position = -1;
  5783. for (i = list.length - 1; i >= 0; i--) {
  5784. if (list[i] === listener || list[i].listener === listener) {
  5785. originalListener = list[i].listener;
  5786. position = i;
  5787. break;
  5788. }
  5789. }
  5790. if (position < 0)
  5791. return this;
  5792. if (position === 0)
  5793. list.shift();
  5794. else
  5795. spliceOne(list, position);
  5796. if (list.length === 1)
  5797. events[type] = list[0];
  5798. if (events.removeListener)
  5799. this.emit('removeListener', type, originalListener || listener);
  5800. }
  5801. return this;
  5802. };
  5803. EventEmitter.prototype.removeAllListeners =
  5804. function removeAllListeners(type) {
  5805. var listeners, events, i;
  5806. events = this._events;
  5807. if (!events)
  5808. return this;
  5809. // not listening for removeListener, no need to emit
  5810. if (!events.removeListener) {
  5811. if (arguments.length === 0) {
  5812. this._events = objectCreate(null);
  5813. this._eventsCount = 0;
  5814. } else if (events[type]) {
  5815. if (--this._eventsCount === 0)
  5816. this._events = objectCreate(null);
  5817. else
  5818. delete events[type];
  5819. }
  5820. return this;
  5821. }
  5822. // emit removeListener for all listeners on all events
  5823. if (arguments.length === 0) {
  5824. var keys = objectKeys(events);
  5825. var key;
  5826. for (i = 0; i < keys.length; ++i) {
  5827. key = keys[i];
  5828. if (key === 'removeListener') continue;
  5829. this.removeAllListeners(key);
  5830. }
  5831. this.removeAllListeners('removeListener');
  5832. this._events = objectCreate(null);
  5833. this._eventsCount = 0;
  5834. return this;
  5835. }
  5836. listeners = events[type];
  5837. if (typeof listeners === 'function') {
  5838. this.removeListener(type, listeners);
  5839. } else if (listeners) {
  5840. // LIFO order
  5841. for (i = listeners.length - 1; i >= 0; i--) {
  5842. this.removeListener(type, listeners[i]);
  5843. }
  5844. }
  5845. return this;
  5846. };
  5847. function _listeners(target, type, unwrap) {
  5848. var events = target._events;
  5849. if (!events)
  5850. return [];
  5851. var evlistener = events[type];
  5852. if (!evlistener)
  5853. return [];
  5854. if (typeof evlistener === 'function')
  5855. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  5856. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  5857. }
  5858. EventEmitter.prototype.listeners = function listeners(type) {
  5859. return _listeners(this, type, true);
  5860. };
  5861. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  5862. return _listeners(this, type, false);
  5863. };
  5864. EventEmitter.listenerCount = function(emitter, type) {
  5865. if (typeof emitter.listenerCount === 'function') {
  5866. return emitter.listenerCount(type);
  5867. } else {
  5868. return listenerCount.call(emitter, type);
  5869. }
  5870. };
  5871. EventEmitter.prototype.listenerCount = listenerCount;
  5872. function listenerCount(type) {
  5873. var events = this._events;
  5874. if (events) {
  5875. var evlistener = events[type];
  5876. if (typeof evlistener === 'function') {
  5877. return 1;
  5878. } else if (evlistener) {
  5879. return evlistener.length;
  5880. }
  5881. }
  5882. return 0;
  5883. }
  5884. EventEmitter.prototype.eventNames = function eventNames() {
  5885. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  5886. };
  5887. // About 1.5x faster than the two-arg version of Array#splice().
  5888. function spliceOne(list, index) {
  5889. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  5890. list[i] = list[k];
  5891. list.pop();
  5892. }
  5893. function arrayClone(arr, n) {
  5894. var copy = new Array(n);
  5895. for (var i = 0; i < n; ++i)
  5896. copy[i] = arr[i];
  5897. return copy;
  5898. }
  5899. function unwrapListeners(arr) {
  5900. var ret = new Array(arr.length);
  5901. for (var i = 0; i < ret.length; ++i) {
  5902. ret[i] = arr[i].listener || arr[i];
  5903. }
  5904. return ret;
  5905. }
  5906. function objectCreatePolyfill(proto) {
  5907. var F = function() {};
  5908. F.prototype = proto;
  5909. return new F;
  5910. }
  5911. function objectKeysPolyfill(obj) {
  5912. var keys = [];
  5913. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  5914. keys.push(k);
  5915. }
  5916. return k;
  5917. }
  5918. function functionBindPolyfill(context) {
  5919. var fn = this;
  5920. return function () {
  5921. return fn.apply(context, arguments);
  5922. };
  5923. }
  5924. },{}],23:[function(require,module,exports){
  5925. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  5926. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5927. var e, m
  5928. var eLen = (nBytes * 8) - mLen - 1
  5929. var eMax = (1 << eLen) - 1
  5930. var eBias = eMax >> 1
  5931. var nBits = -7
  5932. var i = isLE ? (nBytes - 1) : 0
  5933. var d = isLE ? -1 : 1
  5934. var s = buffer[offset + i]
  5935. i += d
  5936. e = s & ((1 << (-nBits)) - 1)
  5937. s >>= (-nBits)
  5938. nBits += eLen
  5939. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5940. m = e & ((1 << (-nBits)) - 1)
  5941. e >>= (-nBits)
  5942. nBits += mLen
  5943. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5944. if (e === 0) {
  5945. e = 1 - eBias
  5946. } else if (e === eMax) {
  5947. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5948. } else {
  5949. m = m + Math.pow(2, mLen)
  5950. e = e - eBias
  5951. }
  5952. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5953. }
  5954. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5955. var e, m, c
  5956. var eLen = (nBytes * 8) - mLen - 1
  5957. var eMax = (1 << eLen) - 1
  5958. var eBias = eMax >> 1
  5959. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5960. var i = isLE ? 0 : (nBytes - 1)
  5961. var d = isLE ? 1 : -1
  5962. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5963. value = Math.abs(value)
  5964. if (isNaN(value) || value === Infinity) {
  5965. m = isNaN(value) ? 1 : 0
  5966. e = eMax
  5967. } else {
  5968. e = Math.floor(Math.log(value) / Math.LN2)
  5969. if (value * (c = Math.pow(2, -e)) < 1) {
  5970. e--
  5971. c *= 2
  5972. }
  5973. if (e + eBias >= 1) {
  5974. value += rt / c
  5975. } else {
  5976. value += rt * Math.pow(2, 1 - eBias)
  5977. }
  5978. if (value * c >= 2) {
  5979. e++
  5980. c /= 2
  5981. }
  5982. if (e + eBias >= eMax) {
  5983. m = 0
  5984. e = eMax
  5985. } else if (e + eBias >= 1) {
  5986. m = ((value * c) - 1) * Math.pow(2, mLen)
  5987. e = e + eBias
  5988. } else {
  5989. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5990. e = 0
  5991. }
  5992. }
  5993. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5994. e = (e << mLen) | m
  5995. eLen += mLen
  5996. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5997. buffer[offset + i - d] |= s * 128
  5998. }
  5999. },{}],24:[function(require,module,exports){
  6000. if (typeof Object.create === 'function') {
  6001. // implementation from standard node.js 'util' module
  6002. module.exports = function inherits(ctor, superCtor) {
  6003. if (superCtor) {
  6004. ctor.super_ = superCtor
  6005. ctor.prototype = Object.create(superCtor.prototype, {
  6006. constructor: {
  6007. value: ctor,
  6008. enumerable: false,
  6009. writable: true,
  6010. configurable: true
  6011. }
  6012. })
  6013. }
  6014. };
  6015. } else {
  6016. // old school shim for old browsers
  6017. module.exports = function inherits(ctor, superCtor) {
  6018. if (superCtor) {
  6019. ctor.super_ = superCtor
  6020. var TempCtor = function () {}
  6021. TempCtor.prototype = superCtor.prototype
  6022. ctor.prototype = new TempCtor()
  6023. ctor.prototype.constructor = ctor
  6024. }
  6025. }
  6026. }
  6027. },{}],25:[function(require,module,exports){
  6028. "use strict";
  6029. Object.defineProperty(exports, "__esModule", { value: true });
  6030. var TreeNode = /** @class */ (function () {
  6031. function TreeNode(key, value) {
  6032. this.color = true;
  6033. this.key = undefined;
  6034. this.value = undefined;
  6035. this.parent = undefined;
  6036. this.brother = undefined;
  6037. this.leftChild = undefined;
  6038. this.rightChild = undefined;
  6039. this.key = key;
  6040. this.value = value;
  6041. }
  6042. TreeNode.prototype.rotateLeft = function () {
  6043. var PP = this.parent;
  6044. var PB = this.brother;
  6045. var F = this.leftChild;
  6046. var V = this.rightChild;
  6047. if (!V)
  6048. throw new Error("unknown error");
  6049. var R = V.leftChild;
  6050. var X = V.rightChild;
  6051. if (PP) {
  6052. if (PP.leftChild === this)
  6053. PP.leftChild = V;
  6054. else if (PP.rightChild === this)
  6055. PP.rightChild = V;
  6056. }
  6057. V.parent = PP;
  6058. V.brother = PB;
  6059. V.leftChild = this;
  6060. V.rightChild = X;
  6061. if (PB)
  6062. PB.brother = V;
  6063. this.parent = V;
  6064. this.brother = X;
  6065. this.leftChild = F;
  6066. this.rightChild = R;
  6067. if (X) {
  6068. X.parent = V;
  6069. X.brother = this;
  6070. }
  6071. if (F) {
  6072. F.parent = this;
  6073. F.brother = R;
  6074. }
  6075. if (R) {
  6076. R.parent = this;
  6077. R.brother = F;
  6078. }
  6079. return V;
  6080. };
  6081. TreeNode.prototype.rotateRight = function () {
  6082. var PP = this.parent;
  6083. var PB = this.brother;
  6084. var F = this.leftChild;
  6085. if (!F)
  6086. throw new Error("unknown error");
  6087. var V = this.rightChild;
  6088. var D = F.leftChild;
  6089. var K = F.rightChild;
  6090. if (PP) {
  6091. if (PP.leftChild === this)
  6092. PP.leftChild = F;
  6093. else if (PP.rightChild === this)
  6094. PP.rightChild = F;
  6095. }
  6096. F.parent = PP;
  6097. F.brother = PB;
  6098. F.leftChild = D;
  6099. F.rightChild = this;
  6100. if (PB)
  6101. PB.brother = F;
  6102. if (D) {
  6103. D.parent = F;
  6104. D.brother = this;
  6105. }
  6106. this.parent = F;
  6107. this.brother = D;
  6108. this.leftChild = K;
  6109. this.rightChild = V;
  6110. if (K) {
  6111. K.parent = this;
  6112. K.brother = V;
  6113. }
  6114. if (V) {
  6115. V.parent = this;
  6116. V.brother = K;
  6117. }
  6118. return F;
  6119. };
  6120. TreeNode.prototype.remove = function () {
  6121. if (this.leftChild || this.rightChild)
  6122. throw new Error("can only remove leaf node");
  6123. if (this.parent) {
  6124. if (this === this.parent.leftChild)
  6125. this.parent.leftChild = undefined;
  6126. else if (this === this.parent.rightChild)
  6127. this.parent.rightChild = undefined;
  6128. }
  6129. if (this.brother)
  6130. this.brother.brother = undefined;
  6131. this.key = undefined;
  6132. this.value = undefined;
  6133. this.parent = undefined;
  6134. this.brother = undefined;
  6135. };
  6136. TreeNode.TreeNodeColorType = {
  6137. red: true,
  6138. black: false
  6139. };
  6140. return TreeNode;
  6141. }());
  6142. Object.freeze(TreeNode);
  6143. exports.default = TreeNode;
  6144. },{}],26:[function(require,module,exports){
  6145. "use strict";
  6146. var __generator = (this && this.__generator) || function (thisArg, body) {
  6147. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  6148. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  6149. function verb(n) { return function (v) { return step([n, v]); }; }
  6150. function step(op) {
  6151. if (f) throw new TypeError("Generator is already executing.");
  6152. while (_) try {
  6153. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  6154. if (y = 0, t) op = [op[0] & 2, t.value];
  6155. switch (op[0]) {
  6156. case 0: case 1: t = op; break;
  6157. case 4: _.label++; return { value: op[1], done: false };
  6158. case 5: _.label++; y = op[1]; op = [0]; continue;
  6159. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  6160. default:
  6161. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  6162. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  6163. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  6164. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  6165. if (t[2]) _.ops.pop();
  6166. _.trys.pop(); continue;
  6167. }
  6168. op = body.call(thisArg, _);
  6169. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  6170. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  6171. }
  6172. };
  6173. Object.defineProperty(exports, "__esModule", { value: true });
  6174. Deque.sigma = 3; // growth factor
  6175. Deque.bucketSize = 5000;
  6176. function Deque(container) {
  6177. var _this = this;
  6178. if (container === void 0) { container = []; }
  6179. var map = [];
  6180. var first = 0;
  6181. var curFirst = 0;
  6182. var last = 0;
  6183. var curLast = 0;
  6184. var bucketNum = 0;
  6185. var len = 0;
  6186. this.size = function () {
  6187. return len;
  6188. };
  6189. this.empty = function () {
  6190. return len === 0;
  6191. };
  6192. this.clear = function () {
  6193. first = last = curFirst = curLast = bucketNum = len = 0;
  6194. reAllocate.call(this, Deque.bucketSize);
  6195. len = 0;
  6196. };
  6197. this.front = function () {
  6198. return map[first][curFirst];
  6199. };
  6200. this.back = function () {
  6201. return map[last][curLast];
  6202. };
  6203. this.forEach = function (callback) {
  6204. if (this.empty())
  6205. return;
  6206. var index = 0;
  6207. if (first === last) {
  6208. for (var i = curFirst; i <= curLast; ++i) {
  6209. callback(map[first][i], index++);
  6210. }
  6211. return;
  6212. }
  6213. for (var i = curFirst; i < Deque.bucketSize; ++i) {
  6214. callback(map[first][i], index++);
  6215. }
  6216. for (var i = first + 1; i < last; ++i) {
  6217. for (var j = 0; j < Deque.bucketSize; ++j) {
  6218. callback(map[i][j], index++);
  6219. }
  6220. }
  6221. for (var i = 0; i <= curLast; ++i) {
  6222. callback(map[last][i], index++);
  6223. }
  6224. };
  6225. var getElementIndex = function (pos) {
  6226. var curFirstIndex = first * Deque.bucketSize + curFirst;
  6227. var curNodeIndex = curFirstIndex + pos;
  6228. var curLastIndex = last * Deque.bucketSize + curLast;
  6229. if (curNodeIndex < curFirstIndex || curNodeIndex > curLastIndex)
  6230. throw new Error("pos should more than 0 and less than queue's size");
  6231. var curNodeBucketIndex = Math.floor(curNodeIndex / Deque.bucketSize);
  6232. var curNodePointerIndex = curNodeIndex % Deque.bucketSize;
  6233. return { curNodeBucketIndex: curNodeBucketIndex, curNodePointerIndex: curNodePointerIndex };
  6234. };
  6235. /**
  6236. * @param pos index from 0 to size - 1
  6237. */
  6238. this.getElementByPos = function (pos) {
  6239. var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;
  6240. return map[curNodeBucketIndex][curNodePointerIndex];
  6241. };
  6242. this.eraseElementByPos = function (pos) {
  6243. var _this = this;
  6244. if (pos < 0 || pos > len)
  6245. throw new Error("pos should more than 0 and less than queue's size");
  6246. if (pos === 0)
  6247. this.popFront();
  6248. else if (pos === this.size())
  6249. this.popBack();
  6250. else {
  6251. var arr = [];
  6252. for (var i = pos + 1; i < len; ++i) {
  6253. arr.push(this.getElementByPos(i));
  6254. }
  6255. this.cut(pos);
  6256. this.popBack();
  6257. arr.forEach(function (element) { return _this.pushBack(element); });
  6258. }
  6259. };
  6260. this.eraseElementByValue = function (value) {
  6261. if (this.empty())
  6262. return;
  6263. var arr = [];
  6264. this.forEach(function (element) {
  6265. if (element !== value) {
  6266. arr.push(element);
  6267. }
  6268. });
  6269. var _len = arr.length;
  6270. for (var i = 0; i < _len; ++i)
  6271. this.setElementByPos(i, arr[i]);
  6272. this.cut(_len - 1);
  6273. };
  6274. var reAllocate = function (originalSize) {
  6275. var newMap = [];
  6276. var needSize = originalSize * Deque.sigma;
  6277. var newBucketNum = Math.max(Math.ceil(needSize / Deque.bucketSize), 2);
  6278. for (var i = 0; i < newBucketNum; ++i) {
  6279. newMap.push(new Array(Deque.bucketSize));
  6280. }
  6281. var needBucketNum = Math.ceil(originalSize / Deque.bucketSize);
  6282. var newFirst = Math.floor(newBucketNum / 2) - Math.floor(needBucketNum / 2);
  6283. var newLast = newFirst, newCurLast = 0;
  6284. if (this.size()) {
  6285. for (var i = 0; i < needBucketNum; ++i) {
  6286. for (var j = 0; j < Deque.bucketSize; ++j) {
  6287. newMap[newFirst + i][j] = this.front();
  6288. this.popFront();
  6289. if (this.empty()) {
  6290. newLast = newFirst + i;
  6291. newCurLast = j;
  6292. break;
  6293. }
  6294. }
  6295. if (this.empty())
  6296. break;
  6297. }
  6298. }
  6299. map = newMap;
  6300. first = newFirst;
  6301. curFirst = 0;
  6302. last = newLast;
  6303. curLast = newCurLast;
  6304. bucketNum = newBucketNum;
  6305. len = originalSize;
  6306. };
  6307. this.pushBack = function (element) {
  6308. if (!this.empty()) {
  6309. if (last === bucketNum - 1 && curLast === Deque.bucketSize - 1) {
  6310. reAllocate.call(this, this.size());
  6311. }
  6312. if (curLast < Deque.bucketSize - 1) {
  6313. ++curLast;
  6314. }
  6315. else if (last < bucketNum - 1) {
  6316. ++last;
  6317. curLast = 0;
  6318. }
  6319. }
  6320. ++len;
  6321. map[last][curLast] = element;
  6322. };
  6323. this.popBack = function () {
  6324. if (this.empty())
  6325. return;
  6326. if (this.size() !== 1) {
  6327. if (curLast > 0) {
  6328. --curLast;
  6329. }
  6330. else if (first < last) {
  6331. --last;
  6332. curLast = Deque.bucketSize - 1;
  6333. }
  6334. }
  6335. if (len > 0)
  6336. --len;
  6337. };
  6338. this.setElementByPos = function (pos, element) {
  6339. var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;
  6340. map[curNodeBucketIndex][curNodePointerIndex] = element;
  6341. };
  6342. /**
  6343. * @param {number} pos insert element before pos, should in [0, queue.size]
  6344. * @param {any} element the element you want to insert
  6345. * @param {number} [num = 1] the nums you want to insert
  6346. */
  6347. this.insert = function (pos, element, num) {
  6348. var _this = this;
  6349. if (num === void 0) { num = 1; }
  6350. if (pos === 0) {
  6351. while (num--)
  6352. this.pushFront(element);
  6353. }
  6354. else if (pos === this.size()) {
  6355. while (num--)
  6356. this.pushBack(element);
  6357. }
  6358. else {
  6359. var arr = [];
  6360. for (var i = pos; i < len; ++i) {
  6361. arr.push(this.getElementByPos(i));
  6362. }
  6363. this.cut(pos - 1);
  6364. for (var i = 0; i < num; ++i)
  6365. this.pushBack(element);
  6366. arr.forEach(function (element) { return _this.pushBack(element); });
  6367. }
  6368. };
  6369. this.find = function (element) {
  6370. if (first === last) {
  6371. for (var i = curFirst; i <= curLast; ++i) {
  6372. if (map[first][i] === element)
  6373. return true;
  6374. }
  6375. return false;
  6376. }
  6377. for (var i = curFirst; i < Deque.bucketSize; ++i) {
  6378. if (map[first][i] === element)
  6379. return true;
  6380. }
  6381. for (var i = first + 1; i < last; ++i) {
  6382. for (var j = 0; j < Deque.bucketSize; ++j) {
  6383. if (map[i][j] === element)
  6384. return true;
  6385. }
  6386. }
  6387. for (var i = 0; i <= curLast; ++i) {
  6388. if (map[last][i] === element)
  6389. return true;
  6390. }
  6391. return false;
  6392. };
  6393. this.reverse = function () {
  6394. var l = 0, r = len - 1;
  6395. while (l < r) {
  6396. var tmp = this.getElementByPos(l);
  6397. this.setElementByPos(l, this.getElementByPos(r));
  6398. this.setElementByPos(r, tmp);
  6399. ++l;
  6400. --r;
  6401. }
  6402. };
  6403. this.unique = function () {
  6404. if (this.empty())
  6405. return;
  6406. var arr = [];
  6407. var pre = this.front();
  6408. this.forEach(function (element, index) {
  6409. if (index === 0 || element !== pre) {
  6410. arr.push(element);
  6411. pre = element;
  6412. }
  6413. });
  6414. for (var i = 0; i < len; ++i) {
  6415. this.setElementByPos(i, arr[i]);
  6416. }
  6417. this.cut(arr.length - 1);
  6418. };
  6419. this.sort = function (cmp) {
  6420. var arr = [];
  6421. this.forEach(function (element) {
  6422. arr.push(element);
  6423. });
  6424. arr.sort(cmp);
  6425. for (var i = 0; i < len; ++i)
  6426. this.setElementByPos(i, arr[i]);
  6427. };
  6428. this.pushFront = function (element) {
  6429. if (!this.empty()) {
  6430. if (first === 0 && curFirst === 0) {
  6431. reAllocate.call(this, this.size());
  6432. }
  6433. if (curFirst > 0) {
  6434. --curFirst;
  6435. }
  6436. else if (first > 0) {
  6437. --first;
  6438. curFirst = Deque.bucketSize - 1;
  6439. }
  6440. }
  6441. ++len;
  6442. map[first][curFirst] = element;
  6443. };
  6444. this.popFront = function () {
  6445. if (this.empty())
  6446. return;
  6447. if (this.size() !== 1) {
  6448. if (curFirst < Deque.bucketSize - 1) {
  6449. ++curFirst;
  6450. }
  6451. else if (first < last) {
  6452. ++first;
  6453. curFirst = 0;
  6454. }
  6455. }
  6456. if (len > 0)
  6457. --len;
  6458. };
  6459. /**
  6460. * reduces memory usage by freeing unused memory
  6461. */
  6462. this.shrinkToFit = function () {
  6463. var _this = this;
  6464. var arr = [];
  6465. this.forEach(function (element) {
  6466. arr.push(element);
  6467. });
  6468. var _len = arr.length;
  6469. map = [];
  6470. var bucketNum = Math.ceil(_len / Deque.bucketSize);
  6471. for (var i = 0; i < bucketNum; ++i) {
  6472. map.push(new Array(Deque.bucketSize));
  6473. }
  6474. this.clear();
  6475. arr.forEach(function (element) { return _this.pushBack(element); });
  6476. };
  6477. /**
  6478. * @param pos cut elements after pos
  6479. */
  6480. this.cut = function (pos) {
  6481. if (pos < 0) {
  6482. this.clear();
  6483. return;
  6484. }
  6485. var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;
  6486. last = curNodeBucketIndex;
  6487. curLast = curNodePointerIndex;
  6488. len = pos + 1;
  6489. };
  6490. this[Symbol.iterator] = function () {
  6491. return (function () {
  6492. var i, i, i, j, i;
  6493. return __generator(this, function (_a) {
  6494. switch (_a.label) {
  6495. case 0:
  6496. if (len === 0)
  6497. return [2 /*return*/];
  6498. if (!(first === last)) return [3 /*break*/, 5];
  6499. i = curFirst;
  6500. _a.label = 1;
  6501. case 1:
  6502. if (!(i <= curLast)) return [3 /*break*/, 4];
  6503. return [4 /*yield*/, map[first][i]];
  6504. case 2:
  6505. _a.sent();
  6506. _a.label = 3;
  6507. case 3:
  6508. ++i;
  6509. return [3 /*break*/, 1];
  6510. case 4: return [2 /*return*/];
  6511. case 5:
  6512. i = curFirst;
  6513. _a.label = 6;
  6514. case 6:
  6515. if (!(i < Deque.bucketSize)) return [3 /*break*/, 9];
  6516. return [4 /*yield*/, map[first][i]];
  6517. case 7:
  6518. _a.sent();
  6519. _a.label = 8;
  6520. case 8:
  6521. ++i;
  6522. return [3 /*break*/, 6];
  6523. case 9:
  6524. i = first + 1;
  6525. _a.label = 10;
  6526. case 10:
  6527. if (!(i < last)) return [3 /*break*/, 15];
  6528. j = 0;
  6529. _a.label = 11;
  6530. case 11:
  6531. if (!(j < Deque.bucketSize)) return [3 /*break*/, 14];
  6532. return [4 /*yield*/, map[i][j]];
  6533. case 12:
  6534. _a.sent();
  6535. _a.label = 13;
  6536. case 13:
  6537. ++j;
  6538. return [3 /*break*/, 11];
  6539. case 14:
  6540. ++i;
  6541. return [3 /*break*/, 10];
  6542. case 15:
  6543. i = 0;
  6544. _a.label = 16;
  6545. case 16:
  6546. if (!(i <= curLast)) return [3 /*break*/, 19];
  6547. return [4 /*yield*/, map[last][i]];
  6548. case 17:
  6549. _a.sent();
  6550. _a.label = 18;
  6551. case 18:
  6552. ++i;
  6553. return [3 /*break*/, 16];
  6554. case 19: return [2 /*return*/];
  6555. }
  6556. });
  6557. })();
  6558. };
  6559. (function () {
  6560. var _len = Deque.bucketSize;
  6561. if (container.size) {
  6562. _len = container.size();
  6563. }
  6564. else if (container.length) {
  6565. _len = container.length;
  6566. }
  6567. var needSize = _len * Deque.sigma;
  6568. bucketNum = Math.ceil(needSize / Deque.bucketSize);
  6569. bucketNum = Math.max(bucketNum, 3);
  6570. for (var i = 0; i < bucketNum; ++i) {
  6571. map.push(new Array(Deque.bucketSize));
  6572. }
  6573. var needBucketNum = Math.ceil(_len / Deque.bucketSize);
  6574. first = Math.floor(bucketNum / 2) - Math.floor(needBucketNum / 2);
  6575. last = first;
  6576. container.forEach(function (element) { return _this.pushBack(element); });
  6577. })();
  6578. Object.freeze(this);
  6579. }
  6580. Object.freeze(Deque);
  6581. exports.default = Deque;
  6582. },{}],27:[function(require,module,exports){
  6583. "use strict";
  6584. var __generator = (this && this.__generator) || function (thisArg, body) {
  6585. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  6586. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  6587. function verb(n) { return function (v) { return step([n, v]); }; }
  6588. function step(op) {
  6589. if (f) throw new TypeError("Generator is already executing.");
  6590. while (_) try {
  6591. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  6592. if (y = 0, t) op = [op[0] & 2, t.value];
  6593. switch (op[0]) {
  6594. case 0: case 1: t = op; break;
  6595. case 4: _.label++; return { value: op[1], done: false };
  6596. case 5: _.label++; y = op[1]; op = [0]; continue;
  6597. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  6598. default:
  6599. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  6600. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  6601. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  6602. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  6603. if (t[2]) _.ops.pop();
  6604. _.trys.pop(); continue;
  6605. }
  6606. op = body.call(thisArg, _);
  6607. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  6608. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  6609. }
  6610. };
  6611. var __values = (this && this.__values) || function(o) {
  6612. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  6613. if (m) return m.call(o);
  6614. if (o && typeof o.length === "number") return {
  6615. next: function () {
  6616. if (o && i >= o.length) o = void 0;
  6617. return { value: o && o[i++], done: !o };
  6618. }
  6619. };
  6620. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  6621. };
  6622. Object.defineProperty(exports, "__esModule", { value: true });
  6623. var LinkList_1 = require("../LinkList/LinkList");
  6624. var Map_1 = require("../Map/Map");
  6625. HashMap.initSize = (1 << 4);
  6626. HashMap.maxSize = (1 << 30);
  6627. HashMap.sigma = 0.75; // default load factor
  6628. HashMap.treeifyThreshold = 8;
  6629. HashMap.untreeifyThreshold = 6;
  6630. HashMap.minTreeifySize = 64;
  6631. /**
  6632. * Note that resize is a time-consuming operation, please try to determine the number of buckets before use.
  6633. * @param container Initialize the container
  6634. * @param initBucketNum Initialize the bucket num, must be 2 to the power of n
  6635. * @param hashFunc Function to map elements to numbers
  6636. * @constructor
  6637. */
  6638. function HashMap(container, initBucketNum, hashFunc) {
  6639. var _this = this;
  6640. if (container === void 0) { container = []; }
  6641. if (initBucketNum === void 0) { initBucketNum = HashMap.initSize; }
  6642. hashFunc = hashFunc || (function (x) {
  6643. var e_1, _a;
  6644. var hashCode = 0;
  6645. var str = '';
  6646. if (typeof x === "number") {
  6647. hashCode = Math.floor(x);
  6648. hashCode = ((hashCode << 5) - hashCode);
  6649. hashCode = hashCode & hashCode;
  6650. }
  6651. else {
  6652. if (typeof x !== "string") {
  6653. str = JSON.stringify(x);
  6654. }
  6655. else
  6656. str = x;
  6657. try {
  6658. for (var str_1 = __values(str), str_1_1 = str_1.next(); !str_1_1.done; str_1_1 = str_1.next()) {
  6659. var ch = str_1_1.value;
  6660. var character = ch.charCodeAt(0);
  6661. hashCode = ((hashCode << 5) - hashCode) + character;
  6662. hashCode = hashCode & hashCode;
  6663. }
  6664. }
  6665. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  6666. finally {
  6667. try {
  6668. if (str_1_1 && !str_1_1.done && (_a = str_1.return)) _a.call(str_1);
  6669. }
  6670. finally { if (e_1) throw e_1.error; }
  6671. }
  6672. }
  6673. hashCode ^= (hashCode >>> 16);
  6674. return hashCode;
  6675. });
  6676. if ((initBucketNum & (initBucketNum - 1)) !== 0) {
  6677. throw new Error("initBucketNum must be 2 to the power of n");
  6678. }
  6679. var len = 0;
  6680. var hashTable = [];
  6681. var bucketNum = Math.max(HashMap.initSize, Math.min(HashMap.maxSize, initBucketNum));
  6682. this.size = function () {
  6683. return len;
  6684. };
  6685. this.empty = function () {
  6686. return len === 0;
  6687. };
  6688. this.clear = function () {
  6689. len = 0;
  6690. bucketNum = initBucketNum;
  6691. hashTable = [];
  6692. };
  6693. this.forEach = function (callback) {
  6694. var index = 0;
  6695. hashTable.forEach(function (container) {
  6696. container.forEach(function (element) {
  6697. callback(element, index++);
  6698. });
  6699. });
  6700. };
  6701. var reAllocate = function (originalBucketNum) {
  6702. if (originalBucketNum >= HashMap.maxSize)
  6703. return;
  6704. bucketNum = originalBucketNum * 2;
  6705. var newHashTable = [];
  6706. hashTable.forEach(function (container, index) {
  6707. if (container.empty())
  6708. return;
  6709. if (container instanceof LinkList_1.default && container.size() === 1) {
  6710. var _a = container.front(), key = _a.key, value = _a.value;
  6711. newHashTable[hashFunc(key) & (bucketNum - 1)] = new LinkList_1.default([{
  6712. key: key,
  6713. value: value
  6714. }]);
  6715. }
  6716. else if (container instanceof Map_1.default) {
  6717. var lowList_1 = new LinkList_1.default();
  6718. var highList_1 = new LinkList_1.default();
  6719. container.forEach(function (pair) {
  6720. var hashCode = hashFunc(pair.key);
  6721. if ((hashCode & originalBucketNum) === 0) {
  6722. lowList_1.pushBack(pair);
  6723. }
  6724. else
  6725. highList_1.pushBack(pair);
  6726. });
  6727. if (lowList_1.size() > HashMap.untreeifyThreshold)
  6728. newHashTable[index] = new Map_1.default(lowList_1);
  6729. else if (lowList_1.size())
  6730. newHashTable[index] = lowList_1;
  6731. if (highList_1.size() > HashMap.untreeifyThreshold)
  6732. newHashTable[index + originalBucketNum] = new Map_1.default(highList_1);
  6733. else if (highList_1.size())
  6734. newHashTable[index + originalBucketNum] = highList_1;
  6735. }
  6736. else {
  6737. var lowList_2 = new LinkList_1.default();
  6738. var highList_2 = new LinkList_1.default();
  6739. container.forEach(function (pair) {
  6740. var hashCode = hashFunc(pair.key);
  6741. if ((hashCode & originalBucketNum) === 0) {
  6742. lowList_2.pushBack(pair);
  6743. }
  6744. else
  6745. highList_2.pushBack(pair);
  6746. });
  6747. if (lowList_2.size())
  6748. newHashTable[index] = lowList_2;
  6749. if (highList_2.size())
  6750. newHashTable[index + originalBucketNum] = highList_2;
  6751. }
  6752. hashTable[index].clear();
  6753. });
  6754. hashTable = newHashTable;
  6755. };
  6756. this.setElement = function (key, value) {
  6757. var e_2, _a;
  6758. if (key === null || key === undefined) {
  6759. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  6760. }
  6761. if (value === null || value === undefined) {
  6762. this.eraseElementByKey(key);
  6763. return;
  6764. }
  6765. var index = hashFunc(key) & (bucketNum - 1);
  6766. if (!hashTable[index]) {
  6767. ++len;
  6768. hashTable[index] = new LinkList_1.default([{ key: key, value: value }]);
  6769. }
  6770. else {
  6771. var preSize = hashTable[index].size();
  6772. if (hashTable[index] instanceof LinkList_1.default) {
  6773. try {
  6774. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6775. var pair = _c.value;
  6776. if (pair.key === key) {
  6777. pair.value = value;
  6778. return;
  6779. }
  6780. }
  6781. }
  6782. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  6783. finally {
  6784. try {
  6785. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6786. }
  6787. finally { if (e_2) throw e_2.error; }
  6788. }
  6789. hashTable[index].pushBack({
  6790. key: key,
  6791. value: value,
  6792. });
  6793. if (hashTable[index].size() >= HashMap.treeifyThreshold) {
  6794. hashTable[index] = new Map_1.default(hashTable[index]);
  6795. }
  6796. }
  6797. else
  6798. hashTable[index].setElement(key, value);
  6799. var curSize = hashTable[index].size();
  6800. len += curSize - preSize;
  6801. }
  6802. if (len > bucketNum * HashMap.sigma) {
  6803. reAllocate.call(this, bucketNum);
  6804. }
  6805. };
  6806. this.getElementByKey = function (key) {
  6807. var e_3, _a;
  6808. var index = hashFunc(key) & (bucketNum - 1);
  6809. if (!hashTable[index])
  6810. return undefined;
  6811. if (hashTable[index] instanceof Map_1.default)
  6812. return hashTable[index].getElementByKey(key);
  6813. else {
  6814. try {
  6815. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6816. var pair = _c.value;
  6817. if (pair.key === key)
  6818. return pair.value;
  6819. }
  6820. }
  6821. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  6822. finally {
  6823. try {
  6824. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6825. }
  6826. finally { if (e_3) throw e_3.error; }
  6827. }
  6828. return undefined;
  6829. }
  6830. };
  6831. this.eraseElementByKey = function (key) {
  6832. var e_4, _a;
  6833. var index = hashFunc(key) & (bucketNum - 1);
  6834. if (!hashTable[index])
  6835. return;
  6836. var preSize = hashTable[index].size();
  6837. if (hashTable[index] instanceof Map_1.default) {
  6838. hashTable[index].eraseElementByKey(key);
  6839. if (hashTable[index].size() <= HashMap.untreeifyThreshold) {
  6840. hashTable[index] = new LinkList_1.default(hashTable[index]);
  6841. }
  6842. }
  6843. else {
  6844. var pos = -1;
  6845. try {
  6846. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6847. var pair = _c.value;
  6848. ++pos;
  6849. if (pair.key === key) {
  6850. hashTable[index].eraseElementByPos(pos);
  6851. break;
  6852. }
  6853. }
  6854. }
  6855. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  6856. finally {
  6857. try {
  6858. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6859. }
  6860. finally { if (e_4) throw e_4.error; }
  6861. }
  6862. }
  6863. var curSize = hashTable[index].size();
  6864. len += curSize - preSize;
  6865. };
  6866. this.find = function (key) {
  6867. var e_5, _a;
  6868. var index = hashFunc(key) & (bucketNum - 1);
  6869. if (!hashTable[index])
  6870. return false;
  6871. if (hashTable[index] instanceof Map_1.default)
  6872. return hashTable[index].find(key);
  6873. try {
  6874. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6875. var pair = _c.value;
  6876. if (pair.key === key)
  6877. return true;
  6878. }
  6879. }
  6880. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  6881. finally {
  6882. try {
  6883. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6884. }
  6885. finally { if (e_5) throw e_5.error; }
  6886. }
  6887. return false;
  6888. };
  6889. this[Symbol.iterator] = function () {
  6890. return (function () {
  6891. var index, _a, _b, pair, e_6_1;
  6892. var e_6, _c;
  6893. return __generator(this, function (_d) {
  6894. switch (_d.label) {
  6895. case 0:
  6896. index = 0;
  6897. _d.label = 1;
  6898. case 1:
  6899. if (!(index < bucketNum)) return [3 /*break*/, 10];
  6900. while (index < bucketNum && !hashTable[index])
  6901. ++index;
  6902. if (index >= bucketNum)
  6903. return [3 /*break*/, 10];
  6904. _d.label = 2;
  6905. case 2:
  6906. _d.trys.push([2, 7, 8, 9]);
  6907. _a = (e_6 = void 0, __values(hashTable[index])), _b = _a.next();
  6908. _d.label = 3;
  6909. case 3:
  6910. if (!!_b.done) return [3 /*break*/, 6];
  6911. pair = _b.value;
  6912. return [4 /*yield*/, pair];
  6913. case 4:
  6914. _d.sent();
  6915. _d.label = 5;
  6916. case 5:
  6917. _b = _a.next();
  6918. return [3 /*break*/, 3];
  6919. case 6: return [3 /*break*/, 9];
  6920. case 7:
  6921. e_6_1 = _d.sent();
  6922. e_6 = { error: e_6_1 };
  6923. return [3 /*break*/, 9];
  6924. case 8:
  6925. try {
  6926. if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
  6927. }
  6928. finally { if (e_6) throw e_6.error; }
  6929. return [7 /*endfinally*/];
  6930. case 9:
  6931. ++index;
  6932. return [3 /*break*/, 1];
  6933. case 10: return [2 /*return*/];
  6934. }
  6935. });
  6936. })();
  6937. };
  6938. container.forEach(function (_a) {
  6939. var key = _a.key, value = _a.value;
  6940. return _this.setElement(key, value);
  6941. });
  6942. Object.freeze(this);
  6943. }
  6944. Object.freeze(HashMap);
  6945. exports.default = HashMap;
  6946. },{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(require,module,exports){
  6947. "use strict";
  6948. var __generator = (this && this.__generator) || function (thisArg, body) {
  6949. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  6950. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  6951. function verb(n) { return function (v) { return step([n, v]); }; }
  6952. function step(op) {
  6953. if (f) throw new TypeError("Generator is already executing.");
  6954. while (_) try {
  6955. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  6956. if (y = 0, t) op = [op[0] & 2, t.value];
  6957. switch (op[0]) {
  6958. case 0: case 1: t = op; break;
  6959. case 4: _.label++; return { value: op[1], done: false };
  6960. case 5: _.label++; y = op[1]; op = [0]; continue;
  6961. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  6962. default:
  6963. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  6964. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  6965. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  6966. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  6967. if (t[2]) _.ops.pop();
  6968. _.trys.pop(); continue;
  6969. }
  6970. op = body.call(thisArg, _);
  6971. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  6972. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  6973. }
  6974. };
  6975. var __values = (this && this.__values) || function(o) {
  6976. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  6977. if (m) return m.call(o);
  6978. if (o && typeof o.length === "number") return {
  6979. next: function () {
  6980. if (o && i >= o.length) o = void 0;
  6981. return { value: o && o[i++], done: !o };
  6982. }
  6983. };
  6984. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  6985. };
  6986. Object.defineProperty(exports, "__esModule", { value: true });
  6987. var Set_1 = require("../Set/Set");
  6988. var LinkList_1 = require("../LinkList/LinkList");
  6989. HashSet.initSize = (1 << 4);
  6990. HashSet.maxSize = (1 << 30);
  6991. HashSet.sigma = 0.75; // default load factor
  6992. HashSet.treeifyThreshold = 8;
  6993. HashSet.untreeifyThreshold = 6;
  6994. HashSet.minTreeifySize = 64;
  6995. /**
  6996. * Note that resize is a time-consuming operation, please try to determine the number of buckets before use.
  6997. * @param container Initialize the container
  6998. * @param initBucketNum Initialize the bucket num
  6999. * @param hashFunc Function to map elements to numbers
  7000. * @constructor
  7001. */
  7002. function HashSet(container, initBucketNum, hashFunc) {
  7003. var _this = this;
  7004. if (container === void 0) { container = []; }
  7005. if (initBucketNum === void 0) { initBucketNum = HashSet.initSize; }
  7006. hashFunc = hashFunc || (function (x) {
  7007. var hashCode = 0;
  7008. var str = '';
  7009. if (typeof x === "number") {
  7010. hashCode = Math.floor(x);
  7011. hashCode = ((hashCode << 5) - hashCode);
  7012. hashCode = hashCode & hashCode;
  7013. }
  7014. else {
  7015. if (typeof x !== "string") {
  7016. str = JSON.stringify(x);
  7017. }
  7018. else
  7019. str = x;
  7020. for (var i = 0; i < str.length; i++) {
  7021. var character = str.charCodeAt(i);
  7022. hashCode = ((hashCode << 5) - hashCode) + character;
  7023. hashCode = hashCode & hashCode;
  7024. }
  7025. }
  7026. hashCode ^= (hashCode >>> 16);
  7027. return hashCode;
  7028. });
  7029. if ((initBucketNum & (initBucketNum - 1)) !== 0) {
  7030. throw new Error("initBucketNum must be 2 to the power of n");
  7031. }
  7032. var len = 0;
  7033. var hashTable = [];
  7034. var bucketNum = Math.max(HashSet.initSize, Math.min(HashSet.maxSize, initBucketNum));
  7035. this.size = function () {
  7036. return len;
  7037. };
  7038. this.empty = function () {
  7039. return len === 0;
  7040. };
  7041. this.clear = function () {
  7042. len = 0;
  7043. bucketNum = initBucketNum;
  7044. hashTable = [];
  7045. };
  7046. this.forEach = function (callback) {
  7047. var index = 0;
  7048. hashTable.forEach(function (container) {
  7049. container.forEach(function (element) {
  7050. callback(element, index++);
  7051. });
  7052. });
  7053. };
  7054. var reAllocate = function (originalBucketNum) {
  7055. if (originalBucketNum >= HashSet.maxSize)
  7056. return;
  7057. bucketNum = originalBucketNum * 2;
  7058. var newHashTable = [];
  7059. hashTable.forEach(function (container, index) {
  7060. if (container.empty())
  7061. return;
  7062. if (container instanceof LinkList_1.default && container.size() === 1) {
  7063. var element = container.front();
  7064. if (element === undefined)
  7065. throw new Error("unknown error");
  7066. newHashTable[hashFunc(element) & (bucketNum - 1)] = new LinkList_1.default([element]);
  7067. }
  7068. else if (container instanceof Set_1.default) {
  7069. var lowList_1 = new LinkList_1.default();
  7070. var highList_1 = new LinkList_1.default();
  7071. container.forEach(function (element) {
  7072. var hashCode = hashFunc(element);
  7073. if ((hashCode & originalBucketNum) === 0) {
  7074. lowList_1.pushBack(element);
  7075. }
  7076. else
  7077. highList_1.pushBack(element);
  7078. });
  7079. if (lowList_1.size() > HashSet.untreeifyThreshold)
  7080. newHashTable[index] = new Set_1.default(lowList_1);
  7081. else if (lowList_1.size())
  7082. newHashTable[index] = lowList_1;
  7083. if (highList_1.size() > HashSet.untreeifyThreshold)
  7084. newHashTable[index + originalBucketNum] = new Set_1.default(highList_1);
  7085. else if (highList_1.size())
  7086. newHashTable[index + originalBucketNum] = highList_1;
  7087. }
  7088. else {
  7089. var lowList_2 = new LinkList_1.default();
  7090. var highList_2 = new LinkList_1.default();
  7091. container.forEach(function (element) {
  7092. var hashCode = hashFunc(element);
  7093. if ((hashCode & originalBucketNum) === 0) {
  7094. lowList_2.pushBack(element);
  7095. }
  7096. else
  7097. highList_2.pushBack(element);
  7098. });
  7099. if (lowList_2.size())
  7100. newHashTable[index] = lowList_2;
  7101. if (highList_2.size())
  7102. newHashTable[index + originalBucketNum] = highList_2;
  7103. }
  7104. hashTable[index].clear();
  7105. });
  7106. hashTable = newHashTable;
  7107. };
  7108. this.insert = function (element) {
  7109. if (element === null || element === undefined) {
  7110. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  7111. }
  7112. var index = hashFunc(element) & (bucketNum - 1);
  7113. if (!hashTable[index]) {
  7114. hashTable[index] = new LinkList_1.default([element]);
  7115. ++len;
  7116. }
  7117. else {
  7118. var preSize = hashTable[index].size();
  7119. if (hashTable[index] instanceof LinkList_1.default) {
  7120. if (hashTable[index].find(element))
  7121. return;
  7122. hashTable[index].pushBack(element);
  7123. if (hashTable[index].size() >= HashSet.treeifyThreshold) {
  7124. hashTable[index] = new Set_1.default(hashTable[index]);
  7125. }
  7126. }
  7127. else
  7128. hashTable[index].insert(element);
  7129. var curSize = hashTable[index].size();
  7130. len += curSize - preSize;
  7131. }
  7132. if (len > bucketNum * HashSet.sigma) {
  7133. reAllocate.call(this, bucketNum);
  7134. }
  7135. };
  7136. this.eraseElementByValue = function (element) {
  7137. var index = hashFunc(element) & (bucketNum - 1);
  7138. if (!hashTable[index])
  7139. return;
  7140. var preSize = hashTable[index].size();
  7141. hashTable[index].eraseElementByValue(element);
  7142. if (hashTable[index] instanceof Set_1.default) {
  7143. if (hashTable[index].size() <= HashSet.untreeifyThreshold) {
  7144. hashTable[index] = new LinkList_1.default(hashTable[index]);
  7145. }
  7146. }
  7147. var curSize = hashTable[index].size();
  7148. len += curSize - preSize;
  7149. };
  7150. this.find = function (element) {
  7151. var index = hashFunc(element) & (bucketNum - 1);
  7152. if (!hashTable[index])
  7153. return false;
  7154. return hashTable[index].find(element);
  7155. };
  7156. this[Symbol.iterator] = function () {
  7157. return (function () {
  7158. var index, _a, _b, element, e_1_1;
  7159. var e_1, _c;
  7160. return __generator(this, function (_d) {
  7161. switch (_d.label) {
  7162. case 0:
  7163. index = 0;
  7164. _d.label = 1;
  7165. case 1:
  7166. if (!(index < bucketNum)) return [3 /*break*/, 10];
  7167. while (index < bucketNum && !hashTable[index])
  7168. ++index;
  7169. if (index >= bucketNum)
  7170. return [3 /*break*/, 10];
  7171. _d.label = 2;
  7172. case 2:
  7173. _d.trys.push([2, 7, 8, 9]);
  7174. _a = (e_1 = void 0, __values(hashTable[index])), _b = _a.next();
  7175. _d.label = 3;
  7176. case 3:
  7177. if (!!_b.done) return [3 /*break*/, 6];
  7178. element = _b.value;
  7179. return [4 /*yield*/, element];
  7180. case 4:
  7181. _d.sent();
  7182. _d.label = 5;
  7183. case 5:
  7184. _b = _a.next();
  7185. return [3 /*break*/, 3];
  7186. case 6: return [3 /*break*/, 9];
  7187. case 7:
  7188. e_1_1 = _d.sent();
  7189. e_1 = { error: e_1_1 };
  7190. return [3 /*break*/, 9];
  7191. case 8:
  7192. try {
  7193. if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
  7194. }
  7195. finally { if (e_1) throw e_1.error; }
  7196. return [7 /*endfinally*/];
  7197. case 9:
  7198. ++index;
  7199. return [3 /*break*/, 1];
  7200. case 10: return [2 /*return*/];
  7201. }
  7202. });
  7203. })();
  7204. };
  7205. container.forEach(function (element) { return _this.insert(element); });
  7206. Object.freeze(this);
  7207. }
  7208. Object.freeze(HashSet);
  7209. exports.default = HashSet;
  7210. },{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(require,module,exports){
  7211. "use strict";
  7212. var __generator = (this && this.__generator) || function (thisArg, body) {
  7213. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  7214. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  7215. function verb(n) { return function (v) { return step([n, v]); }; }
  7216. function step(op) {
  7217. if (f) throw new TypeError("Generator is already executing.");
  7218. while (_) try {
  7219. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  7220. if (y = 0, t) op = [op[0] & 2, t.value];
  7221. switch (op[0]) {
  7222. case 0: case 1: t = op; break;
  7223. case 4: _.label++; return { value: op[1], done: false };
  7224. case 5: _.label++; y = op[1]; op = [0]; continue;
  7225. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  7226. default:
  7227. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  7228. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  7229. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  7230. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  7231. if (t[2]) _.ops.pop();
  7232. _.trys.pop(); continue;
  7233. }
  7234. op = body.call(thisArg, _);
  7235. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  7236. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  7237. }
  7238. };
  7239. Object.defineProperty(exports, "__esModule", { value: true });
  7240. var LinkNode = /** @class */ (function () {
  7241. function LinkNode(element) {
  7242. this.value = undefined;
  7243. this.pre = undefined;
  7244. this.next = undefined;
  7245. this.value = element;
  7246. }
  7247. return LinkNode;
  7248. }());
  7249. function LinkList(container) {
  7250. var _this = this;
  7251. if (container === void 0) { container = []; }
  7252. var len = 0;
  7253. var head = undefined;
  7254. var tail = undefined;
  7255. this.size = function () {
  7256. return len;
  7257. };
  7258. this.empty = function () {
  7259. return len === 0;
  7260. };
  7261. this.clear = function () {
  7262. head = tail = undefined;
  7263. len = 0;
  7264. };
  7265. this.front = function () {
  7266. return head === null || head === void 0 ? void 0 : head.value;
  7267. };
  7268. this.back = function () {
  7269. return tail === null || tail === void 0 ? void 0 : tail.value;
  7270. };
  7271. this.forEach = function (callback) {
  7272. var curNode = head;
  7273. var index = 0;
  7274. while (curNode) {
  7275. if (curNode.value === undefined)
  7276. throw new Error("unknown error");
  7277. callback(curNode.value, index++);
  7278. curNode = curNode.next;
  7279. }
  7280. };
  7281. this.getElementByPos = function (pos) {
  7282. if (pos < 0 || pos >= len)
  7283. throw new Error("pos must more then 0 and less then the list length");
  7284. var curNode = head;
  7285. while (pos--) {
  7286. if (!curNode)
  7287. break;
  7288. curNode = curNode.next;
  7289. }
  7290. if (!curNode || curNode.value === undefined)
  7291. throw new Error("unknown error");
  7292. return curNode.value;
  7293. };
  7294. this.eraseElementByPos = function (pos) {
  7295. if (pos < 0 || pos >= len)
  7296. throw new Error("erase pos must more then 0 and less then the list length");
  7297. if (pos === 0)
  7298. this.popFront();
  7299. else if (pos === len - 1)
  7300. this.popBack();
  7301. else {
  7302. var curNode = head;
  7303. while (pos--) {
  7304. if (!(curNode === null || curNode === void 0 ? void 0 : curNode.next))
  7305. throw new Error("unknown error");
  7306. curNode = curNode.next;
  7307. }
  7308. if (!curNode || !curNode.pre || !curNode.next) {
  7309. throw new Error("unknown error");
  7310. }
  7311. var pre = curNode.pre;
  7312. var next = curNode.next;
  7313. next.pre = pre;
  7314. pre.next = next;
  7315. if (len > 0)
  7316. --len;
  7317. }
  7318. };
  7319. this.eraseElementByValue = function (value) {
  7320. while (head && head.value === value)
  7321. this.popFront();
  7322. while (tail && tail.value === value)
  7323. this.popBack();
  7324. if (!head)
  7325. return;
  7326. var curNode = head;
  7327. while (curNode) {
  7328. if (curNode.value === value) {
  7329. var pre = curNode.pre;
  7330. var next = curNode.next;
  7331. if (next)
  7332. next.pre = pre;
  7333. if (pre)
  7334. pre.next = next;
  7335. if (len > 0)
  7336. --len;
  7337. }
  7338. curNode = curNode.next;
  7339. }
  7340. };
  7341. this.pushBack = function (element) {
  7342. if (element === null || element === undefined) {
  7343. throw new Error("you can't push null or undefined here");
  7344. }
  7345. ++len;
  7346. var newTail = new LinkNode(element);
  7347. if (!tail) {
  7348. head = tail = newTail;
  7349. }
  7350. else {
  7351. tail.next = newTail;
  7352. newTail.pre = tail;
  7353. tail = newTail;
  7354. }
  7355. };
  7356. this.popBack = function () {
  7357. if (!tail)
  7358. return;
  7359. if (len > 0)
  7360. --len;
  7361. if (!tail)
  7362. return;
  7363. if (head === tail) {
  7364. head = tail = undefined;
  7365. }
  7366. else {
  7367. tail = tail.pre;
  7368. if (tail)
  7369. tail.next = undefined;
  7370. }
  7371. };
  7372. this.setElementByPos = function (pos, element) {
  7373. if (element === null || element === undefined) {
  7374. throw new Error("you can't set null or undefined here");
  7375. }
  7376. if (pos < 0 || pos >= len)
  7377. throw new Error("pos must more then 0 and less then the list length");
  7378. var curNode = head;
  7379. while (pos--) {
  7380. if (!curNode)
  7381. throw new Error("unknown error");
  7382. curNode = curNode.next;
  7383. }
  7384. if (curNode)
  7385. curNode.value = element;
  7386. };
  7387. /**
  7388. * @param {number} pos insert element before pos, should in [0, list.size]
  7389. * @param {any} element the element you want to insert
  7390. * @param {number} [num = 1] the nums you want to insert
  7391. */
  7392. this.insert = function (pos, element, num) {
  7393. if (num === void 0) { num = 1; }
  7394. if (element === null || element === undefined) {
  7395. throw new Error("you can't insert null or undefined here");
  7396. }
  7397. if (pos < 0 || pos > len)
  7398. throw new Error("insert pos must more then 0 and less then or equal to the list length");
  7399. if (num < 0)
  7400. throw new Error("insert size must more than 0");
  7401. if (pos === 0) {
  7402. while (num--)
  7403. this.pushFront(element);
  7404. }
  7405. else if (pos === len) {
  7406. while (num--)
  7407. this.pushBack(element);
  7408. }
  7409. else {
  7410. var curNode = head;
  7411. for (var i = 1; i < pos; ++i) {
  7412. if (!(curNode === null || curNode === void 0 ? void 0 : curNode.next))
  7413. throw new Error("unknown error");
  7414. curNode = curNode === null || curNode === void 0 ? void 0 : curNode.next;
  7415. }
  7416. if (!curNode) {
  7417. throw new Error("unknown error");
  7418. }
  7419. var next = curNode.next;
  7420. len += num;
  7421. while (num--) {
  7422. curNode.next = new LinkNode(element);
  7423. curNode.next.pre = curNode;
  7424. curNode = curNode.next;
  7425. }
  7426. curNode.next = next;
  7427. if (next)
  7428. next.pre = curNode;
  7429. }
  7430. };
  7431. this.find = function (element) {
  7432. var curNode = head;
  7433. while (curNode) {
  7434. if (curNode.value === element)
  7435. return true;
  7436. curNode = curNode.next;
  7437. }
  7438. return false;
  7439. };
  7440. this.reverse = function () {
  7441. var pHead = head;
  7442. var pTail = tail;
  7443. var cnt = 0;
  7444. while (pHead && pTail && cnt * 2 < len) {
  7445. var tmp = pHead.value;
  7446. pHead.value = pTail.value;
  7447. pTail.value = tmp;
  7448. pHead = pHead.next;
  7449. pTail = pTail.pre;
  7450. ++cnt;
  7451. }
  7452. };
  7453. this.unique = function () {
  7454. var curNode = head;
  7455. while (curNode) {
  7456. var tmpNode = curNode;
  7457. while (tmpNode && tmpNode.next && tmpNode.value === tmpNode.next.value) {
  7458. tmpNode = tmpNode.next;
  7459. if (len > 0)
  7460. --len;
  7461. }
  7462. curNode.next = tmpNode.next;
  7463. if (curNode.next)
  7464. curNode.next.pre = curNode;
  7465. curNode = curNode.next;
  7466. }
  7467. };
  7468. this.sort = function (cmp) {
  7469. var arr = [];
  7470. this.forEach(function (element) {
  7471. arr.push(element);
  7472. });
  7473. arr.sort(cmp);
  7474. var curNode = head;
  7475. arr.forEach(function (element) {
  7476. if (curNode) {
  7477. curNode.value = element;
  7478. curNode = curNode.next;
  7479. }
  7480. });
  7481. };
  7482. this.pushFront = function (element) {
  7483. if (element === null || element === undefined) {
  7484. throw new Error("you can't push null or undefined here");
  7485. }
  7486. ++len;
  7487. var newHead = new LinkNode(element);
  7488. if (!head) {
  7489. head = tail = newHead;
  7490. }
  7491. else {
  7492. newHead.next = head;
  7493. head.pre = newHead;
  7494. head = newHead;
  7495. }
  7496. };
  7497. this.popFront = function () {
  7498. if (!head)
  7499. return;
  7500. if (len > 0)
  7501. --len;
  7502. if (!head)
  7503. return;
  7504. if (head === tail) {
  7505. head = tail = undefined;
  7506. }
  7507. else {
  7508. head = head.next;
  7509. if (head)
  7510. head.pre = undefined;
  7511. }
  7512. };
  7513. /**
  7514. * merge two sorted lists
  7515. * @param list other list
  7516. */
  7517. this.merge = function (list) {
  7518. var _this = this;
  7519. var curNode = head;
  7520. list.forEach(function (element) {
  7521. while (curNode && curNode.value !== undefined && curNode.value <= element) {
  7522. curNode = curNode.next;
  7523. }
  7524. if (curNode === undefined) {
  7525. _this.pushBack(element);
  7526. curNode = tail;
  7527. }
  7528. else if (curNode === head) {
  7529. _this.pushFront(element);
  7530. curNode = head;
  7531. }
  7532. else {
  7533. ++len;
  7534. var pre = curNode.pre;
  7535. if (pre) {
  7536. pre.next = new LinkNode(element);
  7537. pre.next.pre = pre;
  7538. pre.next.next = curNode;
  7539. if (curNode)
  7540. curNode.pre = pre.next;
  7541. }
  7542. }
  7543. });
  7544. };
  7545. this[Symbol.iterator] = function () {
  7546. return (function () {
  7547. var curNode;
  7548. return __generator(this, function (_a) {
  7549. switch (_a.label) {
  7550. case 0:
  7551. curNode = head;
  7552. _a.label = 1;
  7553. case 1:
  7554. if (!(curNode !== undefined)) return [3 /*break*/, 3];
  7555. if (!curNode.value)
  7556. throw new Error("unknown error");
  7557. return [4 /*yield*/, curNode.value];
  7558. case 2:
  7559. _a.sent();
  7560. curNode = curNode.next;
  7561. return [3 /*break*/, 1];
  7562. case 3: return [2 /*return*/];
  7563. }
  7564. });
  7565. })();
  7566. };
  7567. container.forEach(function (element) { return _this.pushBack(element); });
  7568. Object.freeze(this);
  7569. }
  7570. Object.freeze(LinkList);
  7571. exports.default = LinkList;
  7572. },{}],30:[function(require,module,exports){
  7573. "use strict";
  7574. var __generator = (this && this.__generator) || function (thisArg, body) {
  7575. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  7576. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  7577. function verb(n) { return function (v) { return step([n, v]); }; }
  7578. function step(op) {
  7579. if (f) throw new TypeError("Generator is already executing.");
  7580. while (_) try {
  7581. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  7582. if (y = 0, t) op = [op[0] & 2, t.value];
  7583. switch (op[0]) {
  7584. case 0: case 1: t = op; break;
  7585. case 4: _.label++; return { value: op[1], done: false };
  7586. case 5: _.label++; y = op[1]; op = [0]; continue;
  7587. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  7588. default:
  7589. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  7590. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  7591. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  7592. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  7593. if (t[2]) _.ops.pop();
  7594. _.trys.pop(); continue;
  7595. }
  7596. op = body.call(thisArg, _);
  7597. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  7598. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  7599. }
  7600. };
  7601. var __values = (this && this.__values) || function(o) {
  7602. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  7603. if (m) return m.call(o);
  7604. if (o && typeof o.length === "number") return {
  7605. next: function () {
  7606. if (o && i >= o.length) o = void 0;
  7607. return { value: o && o[i++], done: !o };
  7608. }
  7609. };
  7610. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  7611. };
  7612. Object.defineProperty(exports, "__esModule", { value: true });
  7613. var TreeNode_1 = require("../Base/TreeNode");
  7614. function Map(container, cmp) {
  7615. var _this = this;
  7616. if (container === void 0) { container = []; }
  7617. cmp = cmp || (function (x, y) {
  7618. if (x < y)
  7619. return -1;
  7620. if (x > y)
  7621. return 1;
  7622. return 0;
  7623. });
  7624. var len = 0;
  7625. var root = new TreeNode_1.default();
  7626. root.color = TreeNode_1.default.TreeNodeColorType.black;
  7627. this.size = function () {
  7628. return len;
  7629. };
  7630. this.empty = function () {
  7631. return len === 0;
  7632. };
  7633. this.clear = function () {
  7634. len = 0;
  7635. root.key = root.value = undefined;
  7636. root.leftChild = root.rightChild = root.brother = undefined;
  7637. };
  7638. var findSubTreeMinNode = function (curNode) {
  7639. if (!curNode || curNode.key === undefined)
  7640. throw new Error("unknown error");
  7641. return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;
  7642. };
  7643. var findSubTreeMaxNode = function (curNode) {
  7644. if (!curNode || curNode.key === undefined)
  7645. throw new Error("unknown error");
  7646. return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;
  7647. };
  7648. this.front = function () {
  7649. if (this.empty())
  7650. return undefined;
  7651. var minNode = findSubTreeMinNode(root);
  7652. if (minNode.key === undefined || minNode.value === undefined)
  7653. throw new Error("unknown error");
  7654. return {
  7655. key: minNode.key,
  7656. value: minNode.value
  7657. };
  7658. };
  7659. this.back = function () {
  7660. if (this.empty())
  7661. return undefined;
  7662. var maxNode = findSubTreeMaxNode(root);
  7663. if (maxNode.key === undefined || maxNode.value === undefined)
  7664. throw new Error("unknown error");
  7665. return {
  7666. key: maxNode.key,
  7667. value: maxNode.value
  7668. };
  7669. };
  7670. this.forEach = function (callback) {
  7671. var e_1, _a;
  7672. var index = 0;
  7673. try {
  7674. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  7675. var pair = _c.value;
  7676. callback(pair, index++);
  7677. }
  7678. }
  7679. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  7680. finally {
  7681. try {
  7682. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  7683. }
  7684. finally { if (e_1) throw e_1.error; }
  7685. }
  7686. };
  7687. this.getElementByPos = function (pos) {
  7688. var e_2, _a;
  7689. if (pos < 0 || pos >= this.size())
  7690. throw new Error("pos must more than 0 and less than set's size");
  7691. var index = 0;
  7692. try {
  7693. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  7694. var pair = _c.value;
  7695. if (index === pos)
  7696. return pair;
  7697. ++index;
  7698. }
  7699. }
  7700. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  7701. finally {
  7702. try {
  7703. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  7704. }
  7705. finally { if (e_2) throw e_2.error; }
  7706. }
  7707. throw new Error("unknown Error");
  7708. };
  7709. var _lowerBound = function (curNode, key) {
  7710. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7711. return undefined;
  7712. var cmpResult = cmp(curNode.key, key);
  7713. if (cmpResult === 0)
  7714. return { key: curNode.key, value: curNode.value };
  7715. if (cmpResult < 0)
  7716. return _lowerBound(curNode.rightChild, key);
  7717. return _lowerBound(curNode.leftChild, key) || {
  7718. key: curNode.key,
  7719. value: curNode.value
  7720. };
  7721. };
  7722. this.lowerBound = function (key) {
  7723. return _lowerBound(root, key);
  7724. };
  7725. var _upperBound = function (curNode, key) {
  7726. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7727. return undefined;
  7728. var cmpResult = cmp(curNode.key, key);
  7729. if (cmpResult <= 0)
  7730. return _upperBound(curNode.rightChild, key);
  7731. return _upperBound(curNode.leftChild, key) || {
  7732. key: curNode.key,
  7733. value: curNode.value
  7734. };
  7735. };
  7736. this.upperBound = function (key) {
  7737. return _upperBound(root, key);
  7738. };
  7739. var _reverseLowerBound = function (curNode, key) {
  7740. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7741. return undefined;
  7742. var cmpResult = cmp(curNode.key, key);
  7743. if (cmpResult === 0)
  7744. return { key: curNode.key, value: curNode.value };
  7745. if (cmpResult > 0)
  7746. return _reverseLowerBound(curNode.leftChild, key);
  7747. return _reverseLowerBound(curNode.rightChild, key) || {
  7748. key: curNode.key,
  7749. value: curNode.value
  7750. };
  7751. };
  7752. this.reverseLowerBound = function (key) {
  7753. return _reverseLowerBound(root, key);
  7754. };
  7755. var _reverseUpperBound = function (curNode, key) {
  7756. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7757. return undefined;
  7758. var cmpResult = cmp(curNode.key, key);
  7759. if (cmpResult >= 0)
  7760. return _reverseUpperBound(curNode.leftChild, key);
  7761. return _reverseUpperBound(curNode.rightChild, key) || {
  7762. key: curNode.key,
  7763. value: curNode.value
  7764. };
  7765. };
  7766. this.reverseUpperBound = function (key) {
  7767. return _reverseUpperBound(root, key);
  7768. };
  7769. var eraseNodeSelfBalance = function (curNode) {
  7770. var parentNode = curNode.parent;
  7771. if (!parentNode) {
  7772. if (curNode === root)
  7773. return;
  7774. throw new Error("unknown error");
  7775. }
  7776. if (curNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7777. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7778. return;
  7779. }
  7780. var brotherNode = curNode.brother;
  7781. if (!brotherNode)
  7782. throw new Error("unknown error");
  7783. if (curNode === parentNode.leftChild) {
  7784. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7785. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7786. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7787. var newRoot = parentNode.rotateLeft();
  7788. if (root === parentNode)
  7789. root = newRoot;
  7790. eraseNodeSelfBalance(curNode);
  7791. }
  7792. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  7793. if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7794. brotherNode.color = parentNode.color;
  7795. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7796. if (brotherNode.rightChild)
  7797. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7798. var newRoot = parentNode.rotateLeft();
  7799. if (root === parentNode)
  7800. root = newRoot;
  7801. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7802. }
  7803. else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7804. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7805. if (brotherNode.leftChild)
  7806. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7807. var newRoot = brotherNode.rotateRight();
  7808. if (root === brotherNode)
  7809. root = newRoot;
  7810. eraseNodeSelfBalance(curNode);
  7811. }
  7812. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  7813. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7814. eraseNodeSelfBalance(parentNode);
  7815. }
  7816. }
  7817. }
  7818. else if (curNode === parentNode.rightChild) {
  7819. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7820. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7821. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7822. var newRoot = parentNode.rotateRight();
  7823. if (root === parentNode)
  7824. root = newRoot;
  7825. eraseNodeSelfBalance(curNode);
  7826. }
  7827. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  7828. if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7829. brotherNode.color = parentNode.color;
  7830. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7831. if (brotherNode.leftChild)
  7832. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7833. var newRoot = parentNode.rotateRight();
  7834. if (root === parentNode)
  7835. root = newRoot;
  7836. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7837. }
  7838. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7839. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7840. if (brotherNode.rightChild)
  7841. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7842. var newRoot = brotherNode.rotateLeft();
  7843. if (root === brotherNode)
  7844. root = newRoot;
  7845. eraseNodeSelfBalance(curNode);
  7846. }
  7847. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  7848. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7849. eraseNodeSelfBalance(parentNode);
  7850. }
  7851. }
  7852. }
  7853. };
  7854. var eraseNode = function (curNode) {
  7855. var swapNode = curNode;
  7856. while (swapNode.leftChild || swapNode.rightChild) {
  7857. if (swapNode.rightChild) {
  7858. swapNode = findSubTreeMinNode(swapNode.rightChild);
  7859. var tmpKey = curNode.key;
  7860. curNode.key = swapNode.key;
  7861. swapNode.key = tmpKey;
  7862. var tmpValue = curNode.value;
  7863. curNode.value = swapNode.value;
  7864. swapNode.value = tmpValue;
  7865. curNode = swapNode;
  7866. }
  7867. if (swapNode.leftChild) {
  7868. swapNode = findSubTreeMaxNode(swapNode.leftChild);
  7869. var tmpKey = curNode.key;
  7870. curNode.key = swapNode.key;
  7871. swapNode.key = tmpKey;
  7872. var tmpValue = curNode.value;
  7873. curNode.value = swapNode.value;
  7874. swapNode.value = tmpValue;
  7875. curNode = swapNode;
  7876. }
  7877. }
  7878. eraseNodeSelfBalance(swapNode);
  7879. if (swapNode)
  7880. swapNode.remove();
  7881. --len;
  7882. root.color = TreeNode_1.default.TreeNodeColorType.black;
  7883. };
  7884. var inOrderTraversal = function (curNode, callback) {
  7885. if (!curNode || curNode.key === undefined)
  7886. return false;
  7887. var ifReturn = inOrderTraversal(curNode.leftChild, callback);
  7888. if (ifReturn)
  7889. return true;
  7890. if (callback(curNode))
  7891. return true;
  7892. return inOrderTraversal(curNode.rightChild, callback);
  7893. };
  7894. this.eraseElementByPos = function (pos) {
  7895. if (pos < 0 || pos >= len)
  7896. throw new Error("pos must more than 0 and less than set's size");
  7897. var index = 0;
  7898. inOrderTraversal(root, function (curNode) {
  7899. if (pos === index) {
  7900. eraseNode(curNode);
  7901. return true;
  7902. }
  7903. ++index;
  7904. return false;
  7905. });
  7906. };
  7907. this.eraseElementByKey = function (key) {
  7908. if (this.empty())
  7909. return;
  7910. var curNode = findElementPos(root, key);
  7911. if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, key) !== 0)
  7912. return;
  7913. eraseNode(curNode);
  7914. };
  7915. var findInsertPos = function (curNode, element) {
  7916. if (!curNode || curNode.key === undefined)
  7917. throw new Error("unknown error");
  7918. var cmpResult = cmp(element, curNode.key);
  7919. if (cmpResult < 0) {
  7920. if (!curNode.leftChild) {
  7921. curNode.leftChild = new TreeNode_1.default();
  7922. curNode.leftChild.parent = curNode;
  7923. curNode.leftChild.brother = curNode.rightChild;
  7924. if (curNode.rightChild)
  7925. curNode.rightChild.brother = curNode.leftChild;
  7926. return curNode.leftChild;
  7927. }
  7928. return findInsertPos(curNode.leftChild, element);
  7929. }
  7930. else if (cmpResult > 0) {
  7931. if (!curNode.rightChild) {
  7932. curNode.rightChild = new TreeNode_1.default();
  7933. curNode.rightChild.parent = curNode;
  7934. curNode.rightChild.brother = curNode.leftChild;
  7935. if (curNode.leftChild)
  7936. curNode.leftChild.brother = curNode.rightChild;
  7937. return curNode.rightChild;
  7938. }
  7939. return findInsertPos(curNode.rightChild, element);
  7940. }
  7941. return curNode;
  7942. };
  7943. var insertNodeSelfBalance = function (curNode) {
  7944. var parentNode = curNode.parent;
  7945. if (!parentNode) {
  7946. if (curNode === root)
  7947. return;
  7948. throw new Error("unknown error");
  7949. }
  7950. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.black)
  7951. return;
  7952. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7953. var uncleNode = parentNode.brother;
  7954. var grandParent = parentNode.parent;
  7955. if (!grandParent)
  7956. throw new Error("unknown error");
  7957. if (uncleNode && uncleNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7958. uncleNode.color = parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7959. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  7960. insertNodeSelfBalance(grandParent);
  7961. }
  7962. else if (!uncleNode || uncleNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  7963. if (parentNode === grandParent.leftChild) {
  7964. if (curNode === parentNode.leftChild) {
  7965. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7966. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  7967. var newRoot = grandParent.rotateRight();
  7968. if (grandParent === root)
  7969. root = newRoot;
  7970. }
  7971. else if (curNode === parentNode.rightChild) {
  7972. var newRoot = parentNode.rotateLeft();
  7973. if (grandParent === root)
  7974. root = newRoot;
  7975. insertNodeSelfBalance(parentNode);
  7976. }
  7977. }
  7978. else if (parentNode === grandParent.rightChild) {
  7979. if (curNode === parentNode.leftChild) {
  7980. var newRoot = parentNode.rotateRight();
  7981. if (grandParent === root)
  7982. root = newRoot;
  7983. insertNodeSelfBalance(parentNode);
  7984. }
  7985. else if (curNode === parentNode.rightChild) {
  7986. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7987. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  7988. var newRoot = grandParent.rotateLeft();
  7989. if (grandParent === root)
  7990. root = newRoot;
  7991. }
  7992. }
  7993. }
  7994. }
  7995. };
  7996. this.setElement = function (key, value) {
  7997. if (key === null || key === undefined) {
  7998. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  7999. }
  8000. if (value === null || value === undefined) {
  8001. this.eraseElementByKey(key);
  8002. return;
  8003. }
  8004. if (this.empty()) {
  8005. ++len;
  8006. root.key = key;
  8007. root.value = value;
  8008. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8009. return;
  8010. }
  8011. var curNode = findInsertPos(root, key);
  8012. if (curNode.key !== undefined && cmp(curNode.key, key) === 0) {
  8013. curNode.value = value;
  8014. return;
  8015. }
  8016. ++len;
  8017. curNode.key = key;
  8018. curNode.value = value;
  8019. insertNodeSelfBalance(curNode);
  8020. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8021. };
  8022. var findElementPos = function (curNode, element) {
  8023. if (!curNode || curNode.key === undefined)
  8024. return undefined;
  8025. var cmpResult = cmp(element, curNode.key);
  8026. if (cmpResult < 0)
  8027. return findElementPos(curNode.leftChild, element);
  8028. else if (cmpResult > 0)
  8029. return findElementPos(curNode.rightChild, element);
  8030. return curNode;
  8031. };
  8032. this.find = function (element) {
  8033. return !!findElementPos(root, element);
  8034. };
  8035. this.getElementByKey = function (element) {
  8036. var curNode = findElementPos(root, element);
  8037. if ((curNode === null || curNode === void 0 ? void 0 : curNode.key) === undefined || (curNode === null || curNode === void 0 ? void 0 : curNode.value) === undefined)
  8038. throw new Error("unknown error");
  8039. return curNode.value;
  8040. };
  8041. // waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).
  8042. // (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)
  8043. this.union = function (other) {
  8044. var _this = this;
  8045. other.forEach(function (_a) {
  8046. var key = _a.key, value = _a.value;
  8047. return _this.setElement(key, value);
  8048. });
  8049. };
  8050. this.getHeight = function () {
  8051. if (this.empty())
  8052. return 0;
  8053. var traversal = function (curNode) {
  8054. if (!curNode)
  8055. return 1;
  8056. return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;
  8057. };
  8058. return traversal(root);
  8059. };
  8060. var iterationFunc = function (curNode) {
  8061. return __generator(this, function (_a) {
  8062. switch (_a.label) {
  8063. case 0:
  8064. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  8065. return [2 /*return*/];
  8066. return [5 /*yield**/, __values(iterationFunc(curNode.leftChild))];
  8067. case 1:
  8068. _a.sent();
  8069. return [4 /*yield*/, { key: curNode.key, value: curNode.value }];
  8070. case 2:
  8071. _a.sent();
  8072. return [5 /*yield**/, __values(iterationFunc(curNode.rightChild))];
  8073. case 3:
  8074. _a.sent();
  8075. return [2 /*return*/];
  8076. }
  8077. });
  8078. };
  8079. this[Symbol.iterator] = function () {
  8080. return iterationFunc(root);
  8081. };
  8082. container.forEach(function (_a) {
  8083. var key = _a.key, value = _a.value;
  8084. return _this.setElement(key, value);
  8085. });
  8086. Object.freeze(this);
  8087. }
  8088. Object.freeze(Map);
  8089. exports.default = Map;
  8090. },{"../Base/TreeNode":25}],31:[function(require,module,exports){
  8091. "use strict";
  8092. Object.defineProperty(exports, "__esModule", { value: true });
  8093. /**
  8094. * @param container
  8095. * @param cmp default cmp will generate a max heap
  8096. * @constructor
  8097. */
  8098. function PriorityQueue(container, cmp) {
  8099. if (container === void 0) { container = []; }
  8100. cmp = cmp || (function (x, y) {
  8101. if (x > y)
  8102. return -1;
  8103. if (x < y)
  8104. return 1;
  8105. return 0;
  8106. });
  8107. var priorityQueue = [];
  8108. container.forEach(function (element) { return priorityQueue.push(element); });
  8109. var len = priorityQueue.length;
  8110. var swap = function (x, y) {
  8111. if (x < 0 || x >= len)
  8112. throw new Error("unknown error");
  8113. if (y < 0 || y >= len)
  8114. throw new Error("unknown error");
  8115. var tmp = priorityQueue[x];
  8116. priorityQueue[x] = priorityQueue[y];
  8117. priorityQueue[y] = tmp;
  8118. };
  8119. var adjust = function (parent) {
  8120. if (parent < 0 || parent >= len)
  8121. throw new Error("unknown error");
  8122. var leftChild = parent * 2 + 1;
  8123. var rightChild = parent * 2 + 2;
  8124. if (leftChild < len && cmp(priorityQueue[parent], priorityQueue[leftChild]) > 0)
  8125. swap(parent, leftChild);
  8126. if (rightChild < len && cmp(priorityQueue[parent], priorityQueue[rightChild]) > 0)
  8127. swap(parent, rightChild);
  8128. };
  8129. (function () {
  8130. for (var parent_1 = Math.floor((len - 1) / 2); parent_1 >= 0; --parent_1) {
  8131. var curParent = parent_1;
  8132. var curChild = curParent * 2 + 1;
  8133. while (curChild < len) {
  8134. var leftChild = curChild;
  8135. var rightChild = leftChild + 1;
  8136. var minChild = leftChild;
  8137. if (rightChild < len && cmp(priorityQueue[leftChild], priorityQueue[rightChild]) > 0)
  8138. minChild = rightChild;
  8139. if (cmp(priorityQueue[curParent], priorityQueue[minChild]) <= 0)
  8140. break;
  8141. swap(curParent, minChild);
  8142. curParent = minChild;
  8143. curChild = curParent * 2 + 1;
  8144. }
  8145. }
  8146. })();
  8147. this.size = function () {
  8148. return len;
  8149. };
  8150. this.empty = function () {
  8151. return len === 0;
  8152. };
  8153. this.clear = function () {
  8154. len = 0;
  8155. priorityQueue.length = 0;
  8156. };
  8157. this.push = function (element) {
  8158. priorityQueue.push(element);
  8159. ++len;
  8160. if (len === 1)
  8161. return;
  8162. var curNode = len - 1;
  8163. while (curNode > 0) {
  8164. var parent_2 = Math.floor((curNode - 1) / 2);
  8165. if (cmp(priorityQueue[parent_2], element) <= 0)
  8166. break;
  8167. adjust(parent_2);
  8168. curNode = parent_2;
  8169. }
  8170. };
  8171. this.pop = function () {
  8172. if (this.empty())
  8173. return;
  8174. if (this.size() === 1) {
  8175. --len;
  8176. return;
  8177. }
  8178. var last = priorityQueue[len - 1];
  8179. --len;
  8180. var parent = 0;
  8181. while (parent < this.size()) {
  8182. var leftChild = parent * 2 + 1;
  8183. var rightChild = parent * 2 + 2;
  8184. if (leftChild >= this.size())
  8185. break;
  8186. var minChild = leftChild;
  8187. if (rightChild < this.size() && cmp(priorityQueue[leftChild], priorityQueue[rightChild]) > 0)
  8188. minChild = rightChild;
  8189. if (cmp(priorityQueue[minChild], last) >= 0)
  8190. break;
  8191. priorityQueue[parent] = priorityQueue[minChild];
  8192. parent = minChild;
  8193. }
  8194. priorityQueue[parent] = last;
  8195. };
  8196. this.top = function () {
  8197. return priorityQueue[0];
  8198. };
  8199. Object.freeze(this);
  8200. }
  8201. Object.freeze(PriorityQueue);
  8202. exports.default = PriorityQueue;
  8203. },{}],32:[function(require,module,exports){
  8204. "use strict";
  8205. Object.defineProperty(exports, "__esModule", { value: true });
  8206. var LinkList_1 = require("../LinkList/LinkList");
  8207. function Queue(container) {
  8208. if (container === void 0) { container = []; }
  8209. var queue = new LinkList_1.default(container);
  8210. this.size = function () {
  8211. return queue.size();
  8212. };
  8213. this.empty = function () {
  8214. return queue.empty();
  8215. };
  8216. this.clear = function () {
  8217. queue.clear();
  8218. };
  8219. this.push = function (element) {
  8220. queue.pushBack(element);
  8221. };
  8222. this.pop = function () {
  8223. queue.popFront();
  8224. };
  8225. this.front = function () {
  8226. return queue.front();
  8227. };
  8228. Object.freeze(this);
  8229. }
  8230. Object.freeze(Queue);
  8231. exports.default = Queue;
  8232. },{"../LinkList/LinkList":29}],33:[function(require,module,exports){
  8233. "use strict";
  8234. var __generator = (this && this.__generator) || function (thisArg, body) {
  8235. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  8236. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  8237. function verb(n) { return function (v) { return step([n, v]); }; }
  8238. function step(op) {
  8239. if (f) throw new TypeError("Generator is already executing.");
  8240. while (_) try {
  8241. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  8242. if (y = 0, t) op = [op[0] & 2, t.value];
  8243. switch (op[0]) {
  8244. case 0: case 1: t = op; break;
  8245. case 4: _.label++; return { value: op[1], done: false };
  8246. case 5: _.label++; y = op[1]; op = [0]; continue;
  8247. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  8248. default:
  8249. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  8250. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  8251. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  8252. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  8253. if (t[2]) _.ops.pop();
  8254. _.trys.pop(); continue;
  8255. }
  8256. op = body.call(thisArg, _);
  8257. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  8258. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  8259. }
  8260. };
  8261. var __values = (this && this.__values) || function(o) {
  8262. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  8263. if (m) return m.call(o);
  8264. if (o && typeof o.length === "number") return {
  8265. next: function () {
  8266. if (o && i >= o.length) o = void 0;
  8267. return { value: o && o[i++], done: !o };
  8268. }
  8269. };
  8270. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  8271. };
  8272. Object.defineProperty(exports, "__esModule", { value: true });
  8273. var TreeNode_1 = require("../Base/TreeNode");
  8274. function Set(container, cmp) {
  8275. var _this = this;
  8276. if (container === void 0) { container = []; }
  8277. cmp = cmp || (function (x, y) {
  8278. if (x < y)
  8279. return -1;
  8280. if (x > y)
  8281. return 1;
  8282. return 0;
  8283. });
  8284. var len = 0;
  8285. var root = new TreeNode_1.default();
  8286. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8287. this.size = function () {
  8288. return len;
  8289. };
  8290. this.empty = function () {
  8291. return len === 0;
  8292. };
  8293. this.clear = function () {
  8294. len = 0;
  8295. root.key = undefined;
  8296. root.leftChild = root.rightChild = root.brother = root.parent = undefined;
  8297. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8298. };
  8299. var findSubTreeMinNode = function (curNode) {
  8300. if (!curNode || curNode.key === undefined)
  8301. throw new Error("unknown error");
  8302. return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;
  8303. };
  8304. var findSubTreeMaxNode = function (curNode) {
  8305. if (!curNode || curNode.key === undefined)
  8306. throw new Error("unknown error");
  8307. return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;
  8308. };
  8309. this.front = function () {
  8310. if (this.empty())
  8311. return undefined;
  8312. var minNode = findSubTreeMinNode(root);
  8313. return minNode.key;
  8314. };
  8315. this.back = function () {
  8316. if (this.empty())
  8317. return undefined;
  8318. var maxNode = findSubTreeMaxNode(root);
  8319. return maxNode.key;
  8320. };
  8321. this.forEach = function (callback) {
  8322. var e_1, _a;
  8323. var index = 0;
  8324. try {
  8325. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  8326. var element = _c.value;
  8327. callback(element, index++);
  8328. }
  8329. }
  8330. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  8331. finally {
  8332. try {
  8333. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  8334. }
  8335. finally { if (e_1) throw e_1.error; }
  8336. }
  8337. };
  8338. this.getElementByPos = function (pos) {
  8339. var e_2, _a;
  8340. if (pos < 0 || pos >= this.size())
  8341. throw new Error("pos must more than 0 and less than set's size");
  8342. var index = 0;
  8343. try {
  8344. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  8345. var element = _c.value;
  8346. if (index === pos)
  8347. return element;
  8348. ++index;
  8349. }
  8350. }
  8351. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  8352. finally {
  8353. try {
  8354. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  8355. }
  8356. finally { if (e_2) throw e_2.error; }
  8357. }
  8358. throw new Error("unknown error");
  8359. };
  8360. var eraseNodeSelfBalance = function (curNode) {
  8361. var parentNode = curNode.parent;
  8362. if (!parentNode) {
  8363. if (curNode === root)
  8364. return;
  8365. throw new Error("unknown error");
  8366. }
  8367. if (curNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8368. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8369. return;
  8370. }
  8371. var brotherNode = curNode.brother;
  8372. if (!brotherNode)
  8373. throw new Error("unknown error");
  8374. if (curNode === parentNode.leftChild) {
  8375. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8376. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8377. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8378. var newRoot = parentNode.rotateLeft();
  8379. if (root === parentNode)
  8380. root = newRoot;
  8381. eraseNodeSelfBalance(curNode);
  8382. }
  8383. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  8384. if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8385. brotherNode.color = parentNode.color;
  8386. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8387. if (brotherNode.rightChild)
  8388. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8389. var newRoot = parentNode.rotateLeft();
  8390. if (root === parentNode)
  8391. root = newRoot;
  8392. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8393. }
  8394. else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8395. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8396. if (brotherNode.leftChild)
  8397. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8398. var newRoot = brotherNode.rotateRight();
  8399. if (root === brotherNode)
  8400. root = newRoot;
  8401. eraseNodeSelfBalance(curNode);
  8402. }
  8403. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  8404. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8405. eraseNodeSelfBalance(parentNode);
  8406. }
  8407. }
  8408. }
  8409. else if (curNode === parentNode.rightChild) {
  8410. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8411. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8412. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8413. var newRoot = parentNode.rotateRight();
  8414. if (root === parentNode)
  8415. root = newRoot;
  8416. eraseNodeSelfBalance(curNode);
  8417. }
  8418. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  8419. if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8420. brotherNode.color = parentNode.color;
  8421. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8422. if (brotherNode.leftChild)
  8423. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8424. var newRoot = parentNode.rotateRight();
  8425. if (root === parentNode)
  8426. root = newRoot;
  8427. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8428. }
  8429. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8430. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8431. if (brotherNode.rightChild)
  8432. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8433. var newRoot = brotherNode.rotateLeft();
  8434. if (root === brotherNode)
  8435. root = newRoot;
  8436. eraseNodeSelfBalance(curNode);
  8437. }
  8438. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  8439. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8440. eraseNodeSelfBalance(parentNode);
  8441. }
  8442. }
  8443. }
  8444. };
  8445. var eraseNode = function (curNode) {
  8446. var swapNode = curNode;
  8447. while (swapNode.leftChild || swapNode.rightChild) {
  8448. if (swapNode.rightChild) {
  8449. swapNode = findSubTreeMinNode(swapNode.rightChild);
  8450. var tmpKey = curNode.key;
  8451. curNode.key = swapNode.key;
  8452. swapNode.key = tmpKey;
  8453. curNode = swapNode;
  8454. }
  8455. if (swapNode.leftChild) {
  8456. swapNode = findSubTreeMaxNode(swapNode.leftChild);
  8457. var tmpKey = curNode.key;
  8458. curNode.key = swapNode.key;
  8459. swapNode.key = tmpKey;
  8460. curNode = swapNode;
  8461. }
  8462. }
  8463. eraseNodeSelfBalance(swapNode);
  8464. if (swapNode)
  8465. swapNode.remove();
  8466. --len;
  8467. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8468. };
  8469. var inOrderTraversal = function (curNode, callback) {
  8470. if (!curNode || curNode.key === undefined)
  8471. return false;
  8472. var ifReturn = inOrderTraversal(curNode.leftChild, callback);
  8473. if (ifReturn)
  8474. return true;
  8475. if (callback(curNode))
  8476. return true;
  8477. return inOrderTraversal(curNode.rightChild, callback);
  8478. };
  8479. this.eraseElementByPos = function (pos) {
  8480. if (pos < 0 || pos >= len)
  8481. throw new Error("pos must more than 0 and less than set's size");
  8482. var index = 0;
  8483. inOrderTraversal(root, function (curNode) {
  8484. if (pos === index) {
  8485. eraseNode(curNode);
  8486. return true;
  8487. }
  8488. ++index;
  8489. return false;
  8490. });
  8491. };
  8492. this.eraseElementByValue = function (value) {
  8493. if (this.empty())
  8494. return;
  8495. var curNode = findElementPos(root, value);
  8496. if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, value) !== 0)
  8497. return;
  8498. eraseNode(curNode);
  8499. };
  8500. var findInsertPos = function (curNode, element) {
  8501. if (!curNode || curNode.key === undefined)
  8502. throw new Error("unknown error");
  8503. var cmpResult = cmp(element, curNode.key);
  8504. if (cmpResult < 0) {
  8505. if (!curNode.leftChild) {
  8506. curNode.leftChild = new TreeNode_1.default();
  8507. curNode.leftChild.parent = curNode;
  8508. curNode.leftChild.brother = curNode.rightChild;
  8509. if (curNode.rightChild)
  8510. curNode.rightChild.brother = curNode.leftChild;
  8511. return curNode.leftChild;
  8512. }
  8513. return findInsertPos(curNode.leftChild, element);
  8514. }
  8515. else if (cmpResult > 0) {
  8516. if (!curNode.rightChild) {
  8517. curNode.rightChild = new TreeNode_1.default();
  8518. curNode.rightChild.parent = curNode;
  8519. curNode.rightChild.brother = curNode.leftChild;
  8520. if (curNode.leftChild)
  8521. curNode.leftChild.brother = curNode.rightChild;
  8522. return curNode.rightChild;
  8523. }
  8524. return findInsertPos(curNode.rightChild, element);
  8525. }
  8526. return curNode;
  8527. };
  8528. var insertNodeSelfBalance = function (curNode) {
  8529. var parentNode = curNode.parent;
  8530. if (!parentNode) {
  8531. if (curNode === root)
  8532. return;
  8533. throw new Error("unknown error");
  8534. }
  8535. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.black)
  8536. return;
  8537. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8538. var uncleNode = parentNode.brother;
  8539. var grandParent = parentNode.parent;
  8540. if (!grandParent)
  8541. throw new Error("unknown error");
  8542. if (uncleNode && uncleNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8543. uncleNode.color = parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8544. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  8545. insertNodeSelfBalance(grandParent);
  8546. }
  8547. else if (!uncleNode || uncleNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  8548. if (parentNode === grandParent.leftChild) {
  8549. if (curNode === parentNode.leftChild) {
  8550. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8551. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  8552. var newRoot = grandParent.rotateRight();
  8553. if (grandParent === root)
  8554. root = newRoot;
  8555. }
  8556. else if (curNode === parentNode.rightChild) {
  8557. var newRoot = parentNode.rotateLeft();
  8558. if (grandParent === root)
  8559. root = newRoot;
  8560. insertNodeSelfBalance(parentNode);
  8561. }
  8562. }
  8563. else if (parentNode === grandParent.rightChild) {
  8564. if (curNode === parentNode.leftChild) {
  8565. var newRoot = parentNode.rotateRight();
  8566. if (grandParent === root)
  8567. root = newRoot;
  8568. insertNodeSelfBalance(parentNode);
  8569. }
  8570. else if (curNode === parentNode.rightChild) {
  8571. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8572. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  8573. var newRoot = grandParent.rotateLeft();
  8574. if (grandParent === root)
  8575. root = newRoot;
  8576. }
  8577. }
  8578. }
  8579. }
  8580. };
  8581. this.insert = function (element) {
  8582. if (element === null || element === undefined) {
  8583. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  8584. }
  8585. if (this.empty()) {
  8586. ++len;
  8587. root.key = element;
  8588. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8589. return;
  8590. }
  8591. var curNode = findInsertPos(root, element);
  8592. if (curNode.key !== undefined && cmp(curNode.key, element) === 0)
  8593. return;
  8594. ++len;
  8595. curNode.key = element;
  8596. insertNodeSelfBalance(curNode);
  8597. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8598. };
  8599. var findElementPos = function (curNode, element) {
  8600. if (!curNode || curNode.key === undefined)
  8601. return undefined;
  8602. var cmpResult = cmp(element, curNode.key);
  8603. if (cmpResult < 0)
  8604. return findElementPos(curNode.leftChild, element);
  8605. else if (cmpResult > 0)
  8606. return findElementPos(curNode.rightChild, element);
  8607. return curNode;
  8608. };
  8609. this.find = function (element) {
  8610. var curNode = findElementPos(root, element);
  8611. return curNode !== undefined && curNode.key !== undefined && cmp(curNode.key, element) === 0;
  8612. };
  8613. var _lowerBound = function (curNode, key) {
  8614. if (!curNode || curNode.key === undefined)
  8615. return undefined;
  8616. var cmpResult = cmp(curNode.key, key);
  8617. if (cmpResult === 0)
  8618. return curNode.key;
  8619. if (cmpResult < 0)
  8620. return _lowerBound(curNode.rightChild, key);
  8621. var res = _lowerBound(curNode.leftChild, key);
  8622. if (res !== undefined)
  8623. return res;
  8624. return curNode.key;
  8625. };
  8626. this.lowerBound = function (key) {
  8627. return _lowerBound(root, key);
  8628. };
  8629. var _upperBound = function (curNode, key) {
  8630. if (!curNode || curNode.key === undefined)
  8631. return undefined;
  8632. var cmpResult = cmp(curNode.key, key);
  8633. if (cmpResult <= 0)
  8634. return _upperBound(curNode.rightChild, key);
  8635. var res = _upperBound(curNode.leftChild, key);
  8636. if (res !== undefined)
  8637. return res;
  8638. return curNode.key;
  8639. };
  8640. this.upperBound = function (key) {
  8641. return _upperBound(root, key);
  8642. };
  8643. var _reverseLowerBound = function (curNode, key) {
  8644. if (!curNode || curNode.key === undefined)
  8645. return undefined;
  8646. var cmpResult = cmp(curNode.key, key);
  8647. if (cmpResult === 0)
  8648. return curNode.key;
  8649. if (cmpResult > 0)
  8650. return _reverseLowerBound(curNode.leftChild, key);
  8651. var res = _reverseLowerBound(curNode.rightChild, key);
  8652. if (res !== undefined)
  8653. return res;
  8654. return curNode.key;
  8655. };
  8656. this.reverseLowerBound = function (key) {
  8657. return _reverseLowerBound(root, key);
  8658. };
  8659. var _reverseUpperBound = function (curNode, key) {
  8660. if (!curNode || curNode.key === undefined)
  8661. return undefined;
  8662. var cmpResult = cmp(curNode.key, key);
  8663. if (cmpResult >= 0)
  8664. return _reverseUpperBound(curNode.leftChild, key);
  8665. var res = _reverseUpperBound(curNode.rightChild, key);
  8666. if (res !== undefined)
  8667. return res;
  8668. return curNode.key;
  8669. };
  8670. this.reverseUpperBound = function (key) {
  8671. return _reverseUpperBound(root, key);
  8672. };
  8673. // waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).
  8674. // (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)
  8675. this.union = function (other) {
  8676. var _this = this;
  8677. other.forEach(function (element) { return _this.insert(element); });
  8678. };
  8679. this.getHeight = function () {
  8680. if (this.empty())
  8681. return 0;
  8682. var traversal = function (curNode) {
  8683. if (!curNode)
  8684. return 1;
  8685. return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;
  8686. };
  8687. return traversal(root);
  8688. };
  8689. var iterationFunc = function (curNode) {
  8690. return __generator(this, function (_a) {
  8691. switch (_a.label) {
  8692. case 0:
  8693. if (!curNode || curNode.key === undefined)
  8694. return [2 /*return*/];
  8695. return [5 /*yield**/, __values(iterationFunc(curNode.leftChild))];
  8696. case 1:
  8697. _a.sent();
  8698. return [4 /*yield*/, curNode.key];
  8699. case 2:
  8700. _a.sent();
  8701. return [5 /*yield**/, __values(iterationFunc(curNode.rightChild))];
  8702. case 3:
  8703. _a.sent();
  8704. return [2 /*return*/];
  8705. }
  8706. });
  8707. };
  8708. this[Symbol.iterator] = function () {
  8709. return iterationFunc(root);
  8710. };
  8711. container.forEach(function (element) { return _this.insert(element); });
  8712. Object.freeze(this);
  8713. }
  8714. Object.freeze(Set);
  8715. exports.default = Set;
  8716. },{"../Base/TreeNode":25}],34:[function(require,module,exports){
  8717. "use strict";
  8718. Object.defineProperty(exports, "__esModule", { value: true });
  8719. function Stack(container) {
  8720. var _this = this;
  8721. if (container === void 0) { container = []; }
  8722. var len = 0;
  8723. var stack = [];
  8724. this.size = function () {
  8725. return len;
  8726. };
  8727. this.empty = function () {
  8728. return len === 0;
  8729. };
  8730. this.clear = function () {
  8731. len = 0;
  8732. stack.length = 0;
  8733. };
  8734. this.push = function (element) {
  8735. stack.push(element);
  8736. ++len;
  8737. };
  8738. this.pop = function () {
  8739. stack.pop();
  8740. if (len > 0)
  8741. --len;
  8742. };
  8743. this.top = function () {
  8744. return stack[len - 1];
  8745. };
  8746. container.forEach(function (element) { return _this.push(element); });
  8747. Object.freeze(this);
  8748. }
  8749. Object.freeze(Stack);
  8750. exports.default = Stack;
  8751. },{}],35:[function(require,module,exports){
  8752. "use strict";
  8753. var __generator = (this && this.__generator) || function (thisArg, body) {
  8754. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  8755. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  8756. function verb(n) { return function (v) { return step([n, v]); }; }
  8757. function step(op) {
  8758. if (f) throw new TypeError("Generator is already executing.");
  8759. while (_) try {
  8760. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  8761. if (y = 0, t) op = [op[0] & 2, t.value];
  8762. switch (op[0]) {
  8763. case 0: case 1: t = op; break;
  8764. case 4: _.label++; return { value: op[1], done: false };
  8765. case 5: _.label++; y = op[1]; op = [0]; continue;
  8766. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  8767. default:
  8768. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  8769. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  8770. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  8771. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  8772. if (t[2]) _.ops.pop();
  8773. _.trys.pop(); continue;
  8774. }
  8775. op = body.call(thisArg, _);
  8776. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  8777. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  8778. }
  8779. };
  8780. var __read = (this && this.__read) || function (o, n) {
  8781. var m = typeof Symbol === "function" && o[Symbol.iterator];
  8782. if (!m) return o;
  8783. var i = m.call(o), r, ar = [], e;
  8784. try {
  8785. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  8786. }
  8787. catch (error) { e = { error: error }; }
  8788. finally {
  8789. try {
  8790. if (r && !r.done && (m = i["return"])) m.call(i);
  8791. }
  8792. finally { if (e) throw e.error; }
  8793. }
  8794. return ar;
  8795. };
  8796. var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  8797. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  8798. if (ar || !(i in from)) {
  8799. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  8800. ar[i] = from[i];
  8801. }
  8802. }
  8803. return to.concat(ar || Array.prototype.slice.call(from));
  8804. };
  8805. var __values = (this && this.__values) || function(o) {
  8806. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  8807. if (m) return m.call(o);
  8808. if (o && typeof o.length === "number") return {
  8809. next: function () {
  8810. if (o && i >= o.length) o = void 0;
  8811. return { value: o && o[i++], done: !o };
  8812. }
  8813. };
  8814. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  8815. };
  8816. Object.defineProperty(exports, "__esModule", { value: true });
  8817. function Vector(container) {
  8818. var _this = this;
  8819. if (container === void 0) { container = []; }
  8820. var len = 0;
  8821. var vector = [];
  8822. this.size = function () {
  8823. return len;
  8824. };
  8825. this.empty = function () {
  8826. return len === 0;
  8827. };
  8828. this.clear = function () {
  8829. len = 0;
  8830. vector.length = 0;
  8831. };
  8832. this.front = function () {
  8833. if (this.empty())
  8834. return undefined;
  8835. return vector[0];
  8836. };
  8837. this.back = function () {
  8838. if (this.empty())
  8839. return undefined;
  8840. return vector[len - 1];
  8841. };
  8842. this.forEach = function (callback) {
  8843. vector.forEach(callback);
  8844. };
  8845. this.getElementByPos = function (pos) {
  8846. if (pos < 0 || pos >= len)
  8847. throw new Error("pos must more than 0 and less than vector's size");
  8848. return vector[pos];
  8849. };
  8850. this.eraseElementByPos = function (pos) {
  8851. if (pos < 0 || pos >= len)
  8852. throw new Error("pos must more than 0 and less than vector's size");
  8853. for (var i = pos; i < len - 1; ++i)
  8854. vector[i] = vector[i + 1];
  8855. this.popBack();
  8856. };
  8857. this.eraseElementByValue = function (value) {
  8858. var newArr = [];
  8859. this.forEach(function (element) {
  8860. if (element !== value)
  8861. newArr.push(element);
  8862. });
  8863. newArr.forEach(function (element, index) {
  8864. vector[index] = element;
  8865. });
  8866. var newLen = newArr.length;
  8867. while (len > newLen)
  8868. this.popBack();
  8869. };
  8870. this.pushBack = function (element) {
  8871. vector.push(element);
  8872. ++len;
  8873. };
  8874. this.popBack = function () {
  8875. vector.pop();
  8876. if (len > 0)
  8877. --len;
  8878. };
  8879. this.setElementByPos = function (pos, element) {
  8880. if (pos < 0 || pos >= len)
  8881. throw new Error("pos must more than 0 and less than vector's size");
  8882. vector[pos] = element;
  8883. };
  8884. this.insert = function (pos, element, num) {
  8885. if (num === void 0) { num = 1; }
  8886. if (pos < 0 || pos > len)
  8887. throw new Error("pos must more than 0 and less than or equal to vector's size");
  8888. vector.splice.apply(vector, __spreadArray([pos, 0], __read(new Array(num).fill(element)), false));
  8889. len += num;
  8890. };
  8891. this.find = function (element) {
  8892. return vector.includes(element);
  8893. };
  8894. this.reverse = function () {
  8895. vector.reverse();
  8896. };
  8897. this.unique = function () {
  8898. var pre;
  8899. var newArr = [];
  8900. this.forEach(function (element, index) {
  8901. if (index === 0 || element !== pre) {
  8902. newArr.push(element);
  8903. pre = element;
  8904. }
  8905. });
  8906. newArr.forEach(function (element, index) {
  8907. vector[index] = element;
  8908. });
  8909. var newLen = newArr.length;
  8910. while (len > newLen)
  8911. this.popBack();
  8912. };
  8913. this.sort = function (cmp) {
  8914. vector.sort(cmp);
  8915. };
  8916. this[Symbol.iterator] = function () {
  8917. return (function () {
  8918. return __generator(this, function (_a) {
  8919. switch (_a.label) {
  8920. case 0: return [5 /*yield**/, __values(vector)];
  8921. case 1: return [2 /*return*/, _a.sent()];
  8922. }
  8923. });
  8924. })();
  8925. };
  8926. container.forEach(function (element) { return _this.pushBack(element); });
  8927. Object.freeze(this);
  8928. }
  8929. Object.freeze(Vector);
  8930. exports.default = Vector;
  8931. },{}],36:[function(require,module,exports){
  8932. "use strict";
  8933. Object.defineProperty(exports, "__esModule", { value: true });
  8934. exports.HashMap = exports.HashSet = exports.Map = exports.Set = exports.PriorityQueue = exports.Deque = exports.LinkList = exports.Queue = exports.Stack = exports.Vector = void 0;
  8935. var Vector_1 = require("./Vector/Vector");
  8936. exports.Vector = Vector_1.default;
  8937. var Stack_1 = require("./Stack/Stack");
  8938. exports.Stack = Stack_1.default;
  8939. var Queue_1 = require("./Queue/Queue");
  8940. exports.Queue = Queue_1.default;
  8941. var LinkList_1 = require("./LinkList/LinkList");
  8942. exports.LinkList = LinkList_1.default;
  8943. var Deque_1 = require("./Deque/Deque");
  8944. exports.Deque = Deque_1.default;
  8945. var PriorityQueue_1 = require("./PriorityQueue/PriorityQueue");
  8946. exports.PriorityQueue = PriorityQueue_1.default;
  8947. var Set_1 = require("./Set/Set");
  8948. exports.Set = Set_1.default;
  8949. var Map_1 = require("./Map/Map");
  8950. exports.Map = Map_1.default;
  8951. var HashSet_1 = require("./HashSet/HashSet");
  8952. exports.HashSet = HashSet_1.default;
  8953. var HashMap_1 = require("./HashMap/HashMap");
  8954. exports.HashMap = HashMap_1.default;
  8955. },{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(require,module,exports){
  8956. 'use strict'
  8957. // A linked list to keep track of recently-used-ness
  8958. const Yallist = require('yallist')
  8959. const MAX = Symbol('max')
  8960. const LENGTH = Symbol('length')
  8961. const LENGTH_CALCULATOR = Symbol('lengthCalculator')
  8962. const ALLOW_STALE = Symbol('allowStale')
  8963. const MAX_AGE = Symbol('maxAge')
  8964. const DISPOSE = Symbol('dispose')
  8965. const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
  8966. const LRU_LIST = Symbol('lruList')
  8967. const CACHE = Symbol('cache')
  8968. const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
  8969. const naiveLength = () => 1
  8970. // lruList is a yallist where the head is the youngest
  8971. // item, and the tail is the oldest. the list contains the Hit
  8972. // objects as the entries.
  8973. // Each Hit object has a reference to its Yallist.Node. This
  8974. // never changes.
  8975. //
  8976. // cache is a Map (or PseudoMap) that matches the keys to
  8977. // the Yallist.Node object.
  8978. class LRUCache {
  8979. constructor (options) {
  8980. if (typeof options === 'number')
  8981. options = { max: options }
  8982. if (!options)
  8983. options = {}
  8984. if (options.max && (typeof options.max !== 'number' || options.max < 0))
  8985. throw new TypeError('max must be a non-negative number')
  8986. // Kind of weird to have a default max of Infinity, but oh well.
  8987. const max = this[MAX] = options.max || Infinity
  8988. const lc = options.length || naiveLength
  8989. this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
  8990. this[ALLOW_STALE] = options.stale || false
  8991. if (options.maxAge && typeof options.maxAge !== 'number')
  8992. throw new TypeError('maxAge must be a number')
  8993. this[MAX_AGE] = options.maxAge || 0
  8994. this[DISPOSE] = options.dispose
  8995. this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
  8996. this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
  8997. this.reset()
  8998. }
  8999. // resize the cache when the max changes.
  9000. set max (mL) {
  9001. if (typeof mL !== 'number' || mL < 0)
  9002. throw new TypeError('max must be a non-negative number')
  9003. this[MAX] = mL || Infinity
  9004. trim(this)
  9005. }
  9006. get max () {
  9007. return this[MAX]
  9008. }
  9009. set allowStale (allowStale) {
  9010. this[ALLOW_STALE] = !!allowStale
  9011. }
  9012. get allowStale () {
  9013. return this[ALLOW_STALE]
  9014. }
  9015. set maxAge (mA) {
  9016. if (typeof mA !== 'number')
  9017. throw new TypeError('maxAge must be a non-negative number')
  9018. this[MAX_AGE] = mA
  9019. trim(this)
  9020. }
  9021. get maxAge () {
  9022. return this[MAX_AGE]
  9023. }
  9024. // resize the cache when the lengthCalculator changes.
  9025. set lengthCalculator (lC) {
  9026. if (typeof lC !== 'function')
  9027. lC = naiveLength
  9028. if (lC !== this[LENGTH_CALCULATOR]) {
  9029. this[LENGTH_CALCULATOR] = lC
  9030. this[LENGTH] = 0
  9031. this[LRU_LIST].forEach(hit => {
  9032. hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
  9033. this[LENGTH] += hit.length
  9034. })
  9035. }
  9036. trim(this)
  9037. }
  9038. get lengthCalculator () { return this[LENGTH_CALCULATOR] }
  9039. get length () { return this[LENGTH] }
  9040. get itemCount () { return this[LRU_LIST].length }
  9041. rforEach (fn, thisp) {
  9042. thisp = thisp || this
  9043. for (let walker = this[LRU_LIST].tail; walker !== null;) {
  9044. const prev = walker.prev
  9045. forEachStep(this, fn, walker, thisp)
  9046. walker = prev
  9047. }
  9048. }
  9049. forEach (fn, thisp) {
  9050. thisp = thisp || this
  9051. for (let walker = this[LRU_LIST].head; walker !== null;) {
  9052. const next = walker.next
  9053. forEachStep(this, fn, walker, thisp)
  9054. walker = next
  9055. }
  9056. }
  9057. keys () {
  9058. return this[LRU_LIST].toArray().map(k => k.key)
  9059. }
  9060. values () {
  9061. return this[LRU_LIST].toArray().map(k => k.value)
  9062. }
  9063. reset () {
  9064. if (this[DISPOSE] &&
  9065. this[LRU_LIST] &&
  9066. this[LRU_LIST].length) {
  9067. this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
  9068. }
  9069. this[CACHE] = new Map() // hash of items by key
  9070. this[LRU_LIST] = new Yallist() // list of items in order of use recency
  9071. this[LENGTH] = 0 // length of items in the list
  9072. }
  9073. dump () {
  9074. return this[LRU_LIST].map(hit =>
  9075. isStale(this, hit) ? false : {
  9076. k: hit.key,
  9077. v: hit.value,
  9078. e: hit.now + (hit.maxAge || 0)
  9079. }).toArray().filter(h => h)
  9080. }
  9081. dumpLru () {
  9082. return this[LRU_LIST]
  9083. }
  9084. set (key, value, maxAge) {
  9085. maxAge = maxAge || this[MAX_AGE]
  9086. if (maxAge && typeof maxAge !== 'number')
  9087. throw new TypeError('maxAge must be a number')
  9088. const now = maxAge ? Date.now() : 0
  9089. const len = this[LENGTH_CALCULATOR](value, key)
  9090. if (this[CACHE].has(key)) {
  9091. if (len > this[MAX]) {
  9092. del(this, this[CACHE].get(key))
  9093. return false
  9094. }
  9095. const node = this[CACHE].get(key)
  9096. const item = node.value
  9097. // dispose of the old one before overwriting
  9098. // split out into 2 ifs for better coverage tracking
  9099. if (this[DISPOSE]) {
  9100. if (!this[NO_DISPOSE_ON_SET])
  9101. this[DISPOSE](key, item.value)
  9102. }
  9103. item.now = now
  9104. item.maxAge = maxAge
  9105. item.value = value
  9106. this[LENGTH] += len - item.length
  9107. item.length = len
  9108. this.get(key)
  9109. trim(this)
  9110. return true
  9111. }
  9112. const hit = new Entry(key, value, len, now, maxAge)
  9113. // oversized objects fall out of cache automatically.
  9114. if (hit.length > this[MAX]) {
  9115. if (this[DISPOSE])
  9116. this[DISPOSE](key, value)
  9117. return false
  9118. }
  9119. this[LENGTH] += hit.length
  9120. this[LRU_LIST].unshift(hit)
  9121. this[CACHE].set(key, this[LRU_LIST].head)
  9122. trim(this)
  9123. return true
  9124. }
  9125. has (key) {
  9126. if (!this[CACHE].has(key)) return false
  9127. const hit = this[CACHE].get(key).value
  9128. return !isStale(this, hit)
  9129. }
  9130. get (key) {
  9131. return get(this, key, true)
  9132. }
  9133. peek (key) {
  9134. return get(this, key, false)
  9135. }
  9136. pop () {
  9137. const node = this[LRU_LIST].tail
  9138. if (!node)
  9139. return null
  9140. del(this, node)
  9141. return node.value
  9142. }
  9143. del (key) {
  9144. del(this, this[CACHE].get(key))
  9145. }
  9146. load (arr) {
  9147. // reset the cache
  9148. this.reset()
  9149. const now = Date.now()
  9150. // A previous serialized cache has the most recent items first
  9151. for (let l = arr.length - 1; l >= 0; l--) {
  9152. const hit = arr[l]
  9153. const expiresAt = hit.e || 0
  9154. if (expiresAt === 0)
  9155. // the item was created without expiration in a non aged cache
  9156. this.set(hit.k, hit.v)
  9157. else {
  9158. const maxAge = expiresAt - now
  9159. // dont add already expired items
  9160. if (maxAge > 0) {
  9161. this.set(hit.k, hit.v, maxAge)
  9162. }
  9163. }
  9164. }
  9165. }
  9166. prune () {
  9167. this[CACHE].forEach((value, key) => get(this, key, false))
  9168. }
  9169. }
  9170. const get = (self, key, doUse) => {
  9171. const node = self[CACHE].get(key)
  9172. if (node) {
  9173. const hit = node.value
  9174. if (isStale(self, hit)) {
  9175. del(self, node)
  9176. if (!self[ALLOW_STALE])
  9177. return undefined
  9178. } else {
  9179. if (doUse) {
  9180. if (self[UPDATE_AGE_ON_GET])
  9181. node.value.now = Date.now()
  9182. self[LRU_LIST].unshiftNode(node)
  9183. }
  9184. }
  9185. return hit.value
  9186. }
  9187. }
  9188. const isStale = (self, hit) => {
  9189. if (!hit || (!hit.maxAge && !self[MAX_AGE]))
  9190. return false
  9191. const diff = Date.now() - hit.now
  9192. return hit.maxAge ? diff > hit.maxAge
  9193. : self[MAX_AGE] && (diff > self[MAX_AGE])
  9194. }
  9195. const trim = self => {
  9196. if (self[LENGTH] > self[MAX]) {
  9197. for (let walker = self[LRU_LIST].tail;
  9198. self[LENGTH] > self[MAX] && walker !== null;) {
  9199. // We know that we're about to delete this one, and also
  9200. // what the next least recently used key will be, so just
  9201. // go ahead and set it now.
  9202. const prev = walker.prev
  9203. del(self, walker)
  9204. walker = prev
  9205. }
  9206. }
  9207. }
  9208. const del = (self, node) => {
  9209. if (node) {
  9210. const hit = node.value
  9211. if (self[DISPOSE])
  9212. self[DISPOSE](hit.key, hit.value)
  9213. self[LENGTH] -= hit.length
  9214. self[CACHE].delete(hit.key)
  9215. self[LRU_LIST].removeNode(node)
  9216. }
  9217. }
  9218. class Entry {
  9219. constructor (key, value, length, now, maxAge) {
  9220. this.key = key
  9221. this.value = value
  9222. this.length = length
  9223. this.now = now
  9224. this.maxAge = maxAge || 0
  9225. }
  9226. }
  9227. const forEachStep = (self, fn, node, thisp) => {
  9228. let hit = node.value
  9229. if (isStale(self, hit)) {
  9230. del(self, node)
  9231. if (!self[ALLOW_STALE])
  9232. hit = undefined
  9233. }
  9234. if (hit)
  9235. fn.call(thisp, hit.value, hit.key, self)
  9236. }
  9237. module.exports = LRUCache
  9238. },{"yallist":83}],38:[function(require,module,exports){
  9239. (function (Buffer){(function (){
  9240. /* Protocol - protocol constants */
  9241. const protocol = module.exports
  9242. /* Command code => mnemonic */
  9243. protocol.types = {
  9244. 0: 'reserved',
  9245. 1: 'connect',
  9246. 2: 'connack',
  9247. 3: 'publish',
  9248. 4: 'puback',
  9249. 5: 'pubrec',
  9250. 6: 'pubrel',
  9251. 7: 'pubcomp',
  9252. 8: 'subscribe',
  9253. 9: 'suback',
  9254. 10: 'unsubscribe',
  9255. 11: 'unsuback',
  9256. 12: 'pingreq',
  9257. 13: 'pingresp',
  9258. 14: 'disconnect',
  9259. 15: 'auth'
  9260. }
  9261. /* Mnemonic => Command code */
  9262. protocol.codes = {}
  9263. for (const k in protocol.types) {
  9264. const v = protocol.types[k]
  9265. protocol.codes[v] = k
  9266. }
  9267. /* Header */
  9268. protocol.CMD_SHIFT = 4
  9269. protocol.CMD_MASK = 0xF0
  9270. protocol.DUP_MASK = 0x08
  9271. protocol.QOS_MASK = 0x03
  9272. protocol.QOS_SHIFT = 1
  9273. protocol.RETAIN_MASK = 0x01
  9274. /* Length */
  9275. protocol.VARBYTEINT_MASK = 0x7F
  9276. protocol.VARBYTEINT_FIN_MASK = 0x80
  9277. protocol.VARBYTEINT_MAX = 268435455
  9278. /* Connack */
  9279. protocol.SESSIONPRESENT_MASK = 0x01
  9280. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  9281. protocol.CONNACK_HEADER = Buffer.from([protocol.codes.connack << protocol.CMD_SHIFT])
  9282. /* Connect */
  9283. protocol.USERNAME_MASK = 0x80
  9284. protocol.PASSWORD_MASK = 0x40
  9285. protocol.WILL_RETAIN_MASK = 0x20
  9286. protocol.WILL_QOS_MASK = 0x18
  9287. protocol.WILL_QOS_SHIFT = 3
  9288. protocol.WILL_FLAG_MASK = 0x04
  9289. protocol.CLEAN_SESSION_MASK = 0x02
  9290. protocol.CONNECT_HEADER = Buffer.from([protocol.codes.connect << protocol.CMD_SHIFT])
  9291. /* Properties */
  9292. protocol.properties = {
  9293. sessionExpiryInterval: 17,
  9294. willDelayInterval: 24,
  9295. receiveMaximum: 33,
  9296. maximumPacketSize: 39,
  9297. topicAliasMaximum: 34,
  9298. requestResponseInformation: 25,
  9299. requestProblemInformation: 23,
  9300. userProperties: 38,
  9301. authenticationMethod: 21,
  9302. authenticationData: 22,
  9303. payloadFormatIndicator: 1,
  9304. messageExpiryInterval: 2,
  9305. contentType: 3,
  9306. responseTopic: 8,
  9307. correlationData: 9,
  9308. maximumQoS: 36,
  9309. retainAvailable: 37,
  9310. assignedClientIdentifier: 18,
  9311. reasonString: 31,
  9312. wildcardSubscriptionAvailable: 40,
  9313. subscriptionIdentifiersAvailable: 41,
  9314. sharedSubscriptionAvailable: 42,
  9315. serverKeepAlive: 19,
  9316. responseInformation: 26,
  9317. serverReference: 28,
  9318. topicAlias: 35,
  9319. subscriptionIdentifier: 11
  9320. }
  9321. protocol.propertiesCodes = {}
  9322. for (const prop in protocol.properties) {
  9323. const id = protocol.properties[prop]
  9324. protocol.propertiesCodes[id] = prop
  9325. }
  9326. protocol.propertiesTypes = {
  9327. sessionExpiryInterval: 'int32',
  9328. willDelayInterval: 'int32',
  9329. receiveMaximum: 'int16',
  9330. maximumPacketSize: 'int32',
  9331. topicAliasMaximum: 'int16',
  9332. requestResponseInformation: 'byte',
  9333. requestProblemInformation: 'byte',
  9334. userProperties: 'pair',
  9335. authenticationMethod: 'string',
  9336. authenticationData: 'binary',
  9337. payloadFormatIndicator: 'byte',
  9338. messageExpiryInterval: 'int32',
  9339. contentType: 'string',
  9340. responseTopic: 'string',
  9341. correlationData: 'binary',
  9342. maximumQoS: 'int8',
  9343. retainAvailable: 'byte',
  9344. assignedClientIdentifier: 'string',
  9345. reasonString: 'string',
  9346. wildcardSubscriptionAvailable: 'byte',
  9347. subscriptionIdentifiersAvailable: 'byte',
  9348. sharedSubscriptionAvailable: 'byte',
  9349. serverKeepAlive: 'int16',
  9350. responseInformation: 'string',
  9351. serverReference: 'string',
  9352. topicAlias: 'int16',
  9353. subscriptionIdentifier: 'var'
  9354. }
  9355. function genHeader (type) {
  9356. return [0, 1, 2].map(qos => {
  9357. return [0, 1].map(dup => {
  9358. return [0, 1].map(retain => {
  9359. const buf = Buffer.alloc(1)
  9360. buf.writeUInt8(
  9361. protocol.codes[type] << protocol.CMD_SHIFT |
  9362. (dup ? protocol.DUP_MASK : 0) |
  9363. qos << protocol.QOS_SHIFT | retain, 0, true)
  9364. return buf
  9365. })
  9366. })
  9367. })
  9368. }
  9369. /* Publish */
  9370. protocol.PUBLISH_HEADER = genHeader('publish')
  9371. /* Subscribe */
  9372. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  9373. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  9374. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  9375. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  9376. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  9377. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  9378. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  9379. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  9380. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  9381. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  9382. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  9383. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  9384. /* Unsubscribe */
  9385. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  9386. /* Confirmations */
  9387. protocol.ACKS = {
  9388. unsuback: genHeader('unsuback'),
  9389. puback: genHeader('puback'),
  9390. pubcomp: genHeader('pubcomp'),
  9391. pubrel: genHeader('pubrel'),
  9392. pubrec: genHeader('pubrec')
  9393. }
  9394. protocol.SUBACK_HEADER = Buffer.from([protocol.codes.suback << protocol.CMD_SHIFT])
  9395. /* Protocol versions */
  9396. protocol.VERSION3 = Buffer.from([3])
  9397. protocol.VERSION4 = Buffer.from([4])
  9398. protocol.VERSION5 = Buffer.from([5])
  9399. protocol.VERSION131 = Buffer.from([131])
  9400. protocol.VERSION132 = Buffer.from([132])
  9401. /* QoS */
  9402. protocol.QOS = [0, 1, 2].map(qos => {
  9403. return Buffer.from([qos])
  9404. })
  9405. /* Empty packets */
  9406. protocol.EMPTY = {
  9407. pingreq: Buffer.from([protocol.codes.pingreq << 4, 0]),
  9408. pingresp: Buffer.from([protocol.codes.pingresp << 4, 0]),
  9409. disconnect: Buffer.from([protocol.codes.disconnect << 4, 0])
  9410. }
  9411. }).call(this)}).call(this,require("buffer").Buffer)
  9412. },{"buffer":17}],39:[function(require,module,exports){
  9413. (function (Buffer){(function (){
  9414. const writeToStream = require('./writeToStream')
  9415. const EventEmitter = require('events')
  9416. function generate (packet, opts) {
  9417. const stream = new Accumulator()
  9418. writeToStream(packet, stream, opts)
  9419. return stream.concat()
  9420. }
  9421. class Accumulator extends EventEmitter {
  9422. constructor () {
  9423. super()
  9424. this._array = new Array(20)
  9425. this._i = 0
  9426. }
  9427. write (chunk) {
  9428. this._array[this._i++] = chunk
  9429. return true
  9430. }
  9431. concat () {
  9432. let length = 0
  9433. const lengths = new Array(this._array.length)
  9434. const list = this._array
  9435. let pos = 0
  9436. let i
  9437. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  9438. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  9439. else lengths[i] = Buffer.byteLength(list[i])
  9440. length += lengths[i]
  9441. }
  9442. const result = Buffer.allocUnsafe(length)
  9443. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  9444. if (typeof list[i] !== 'string') {
  9445. list[i].copy(result, pos)
  9446. pos += lengths[i]
  9447. } else {
  9448. result.write(list[i], pos)
  9449. pos += lengths[i]
  9450. }
  9451. }
  9452. return result
  9453. }
  9454. }
  9455. module.exports = generate
  9456. }).call(this)}).call(this,require("buffer").Buffer)
  9457. },{"./writeToStream":44,"buffer":17,"events":22}],40:[function(require,module,exports){
  9458. exports.parser = require('./parser').parser
  9459. exports.generate = require('./generate')
  9460. exports.writeToStream = require('./writeToStream')
  9461. },{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(require,module,exports){
  9462. (function (Buffer){(function (){
  9463. const max = 65536
  9464. const cache = {}
  9465. // in node 6 Buffer.subarray returns a Uint8Array instead of a Buffer
  9466. // later versions return a Buffer
  9467. // alternative is Buffer.slice but that creates a new buffer
  9468. // creating new buffers takes time
  9469. // SubOk is only false on node < 8
  9470. const SubOk = Buffer.isBuffer(Buffer.from([1, 2]).subarray(0, 1))
  9471. function generateBuffer (i) {
  9472. const buffer = Buffer.allocUnsafe(2)
  9473. buffer.writeUInt8(i >> 8, 0)
  9474. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  9475. return buffer
  9476. }
  9477. function generateCache () {
  9478. for (let i = 0; i < max; i++) {
  9479. cache[i] = generateBuffer(i)
  9480. }
  9481. }
  9482. function genBufVariableByteInt (num) {
  9483. const maxLength = 4 // max 4 bytes
  9484. let digit = 0
  9485. let pos = 0
  9486. const buffer = Buffer.allocUnsafe(maxLength)
  9487. do {
  9488. digit = num % 128 | 0
  9489. num = num / 128 | 0
  9490. if (num > 0) digit = digit | 0x80
  9491. buffer.writeUInt8(digit, pos++)
  9492. } while (num > 0 && pos < maxLength)
  9493. if (num > 0) {
  9494. pos = 0
  9495. }
  9496. return SubOk ? buffer.subarray(0, pos) : buffer.slice(0, pos)
  9497. }
  9498. function generate4ByteBuffer (num) {
  9499. const buffer = Buffer.allocUnsafe(4)
  9500. buffer.writeUInt32BE(num, 0)
  9501. return buffer
  9502. }
  9503. module.exports = {
  9504. cache,
  9505. generateCache,
  9506. generateNumber: generateBuffer,
  9507. genBufVariableByteInt,
  9508. generate4ByteBuffer
  9509. }
  9510. }).call(this)}).call(this,require("buffer").Buffer)
  9511. },{"buffer":17}],42:[function(require,module,exports){
  9512. class Packet {
  9513. constructor () {
  9514. this.cmd = null
  9515. this.retain = false
  9516. this.qos = 0
  9517. this.dup = false
  9518. this.length = -1
  9519. this.topic = null
  9520. this.payload = null
  9521. }
  9522. }
  9523. module.exports = Packet
  9524. },{}],43:[function(require,module,exports){
  9525. const bl = require('bl')
  9526. const EventEmitter = require('events')
  9527. const Packet = require('./packet')
  9528. const constants = require('./constants')
  9529. const debug = require('debug')('mqtt-packet:parser')
  9530. class Parser extends EventEmitter {
  9531. constructor () {
  9532. super()
  9533. this.parser = this.constructor.parser
  9534. }
  9535. static parser (opt) {
  9536. if (!(this instanceof Parser)) return (new Parser()).parser(opt)
  9537. this.settings = opt || {}
  9538. this._states = [
  9539. '_parseHeader',
  9540. '_parseLength',
  9541. '_parsePayload',
  9542. '_newPacket'
  9543. ]
  9544. this._resetState()
  9545. return this
  9546. }
  9547. _resetState () {
  9548. debug('_resetState: resetting packet, error, _list, and _stateCounter')
  9549. this.packet = new Packet()
  9550. this.error = null
  9551. this._list = bl()
  9552. this._stateCounter = 0
  9553. }
  9554. parse (buf) {
  9555. if (this.error) this._resetState()
  9556. this._list.append(buf)
  9557. debug('parse: current state: %s', this._states[this._stateCounter])
  9558. while ((this.packet.length !== -1 || this._list.length > 0) &&
  9559. this[this._states[this._stateCounter]]() &&
  9560. !this.error) {
  9561. this._stateCounter++
  9562. debug('parse: state complete. _stateCounter is now: %d', this._stateCounter)
  9563. debug('parse: packet.length: %d, buffer list length: %d', this.packet.length, this._list.length)
  9564. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  9565. }
  9566. debug('parse: exited while loop. packet: %d, buffer list length: %d', this.packet.length, this._list.length)
  9567. return this._list.length
  9568. }
  9569. _parseHeader () {
  9570. // There is at least one byte in the buffer
  9571. const zero = this._list.readUInt8(0)
  9572. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  9573. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  9574. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  9575. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  9576. debug('_parseHeader: packet: %o', this.packet)
  9577. this._list.consume(1)
  9578. return true
  9579. }
  9580. _parseLength () {
  9581. // There is at least one byte in the list
  9582. const result = this._parseVarByteNum(true)
  9583. if (result) {
  9584. this.packet.length = result.value
  9585. this._list.consume(result.bytes)
  9586. }
  9587. debug('_parseLength %d', result.value)
  9588. return !!result
  9589. }
  9590. _parsePayload () {
  9591. debug('_parsePayload: payload %O', this._list)
  9592. let result = false
  9593. // Do we have a payload? Do we have enough data to complete the payload?
  9594. // PINGs have no payload
  9595. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  9596. this._pos = 0
  9597. switch (this.packet.cmd) {
  9598. case 'connect':
  9599. this._parseConnect()
  9600. break
  9601. case 'connack':
  9602. this._parseConnack()
  9603. break
  9604. case 'publish':
  9605. this._parsePublish()
  9606. break
  9607. case 'puback':
  9608. case 'pubrec':
  9609. case 'pubrel':
  9610. case 'pubcomp':
  9611. this._parseConfirmation()
  9612. break
  9613. case 'subscribe':
  9614. this._parseSubscribe()
  9615. break
  9616. case 'suback':
  9617. this._parseSuback()
  9618. break
  9619. case 'unsubscribe':
  9620. this._parseUnsubscribe()
  9621. break
  9622. case 'unsuback':
  9623. this._parseUnsuback()
  9624. break
  9625. case 'pingreq':
  9626. case 'pingresp':
  9627. // These are empty, nothing to do
  9628. break
  9629. case 'disconnect':
  9630. this._parseDisconnect()
  9631. break
  9632. case 'auth':
  9633. this._parseAuth()
  9634. break
  9635. default:
  9636. this._emitError(new Error('Not supported'))
  9637. }
  9638. result = true
  9639. }
  9640. debug('_parsePayload complete result: %s', result)
  9641. return result
  9642. }
  9643. _parseConnect () {
  9644. debug('_parseConnect')
  9645. let topic // Will topic
  9646. let payload // Will payload
  9647. let password // Password
  9648. let username // Username
  9649. const flags = {}
  9650. const packet = this.packet
  9651. // Parse protocolId
  9652. const protocolId = this._parseString()
  9653. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  9654. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  9655. return this._emitError(new Error('Invalid protocolId'))
  9656. }
  9657. packet.protocolId = protocolId
  9658. // Parse constants version number
  9659. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  9660. packet.protocolVersion = this._list.readUInt8(this._pos)
  9661. if (packet.protocolVersion >= 128) {
  9662. packet.bridgeMode = true
  9663. packet.protocolVersion = packet.protocolVersion - 128
  9664. }
  9665. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  9666. return this._emitError(new Error('Invalid protocol version'))
  9667. }
  9668. this._pos++
  9669. if (this._pos >= this._list.length) {
  9670. return this._emitError(new Error('Packet too short'))
  9671. }
  9672. // Parse connect flags
  9673. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  9674. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  9675. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  9676. if (flags.will) {
  9677. packet.will = {}
  9678. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  9679. packet.will.qos = (this._list.readUInt8(this._pos) &
  9680. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  9681. }
  9682. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  9683. this._pos++
  9684. // Parse keepalive
  9685. packet.keepalive = this._parseNum()
  9686. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  9687. // parse properties
  9688. if (packet.protocolVersion === 5) {
  9689. const properties = this._parseProperties()
  9690. if (Object.getOwnPropertyNames(properties).length) {
  9691. packet.properties = properties
  9692. }
  9693. }
  9694. // Parse clientId
  9695. const clientId = this._parseString()
  9696. if (clientId === null) return this._emitError(new Error('Packet too short'))
  9697. packet.clientId = clientId
  9698. debug('_parseConnect: packet.clientId: %s', packet.clientId)
  9699. if (flags.will) {
  9700. if (packet.protocolVersion === 5) {
  9701. const willProperties = this._parseProperties()
  9702. if (Object.getOwnPropertyNames(willProperties).length) {
  9703. packet.will.properties = willProperties
  9704. }
  9705. }
  9706. // Parse will topic
  9707. topic = this._parseString()
  9708. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  9709. packet.will.topic = topic
  9710. debug('_parseConnect: packet.will.topic: %s', packet.will.topic)
  9711. // Parse will payload
  9712. payload = this._parseBuffer()
  9713. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  9714. packet.will.payload = payload
  9715. debug('_parseConnect: packet.will.paylaod: %s', packet.will.payload)
  9716. }
  9717. // Parse username
  9718. if (flags.username) {
  9719. username = this._parseString()
  9720. if (username === null) return this._emitError(new Error('Cannot parse username'))
  9721. packet.username = username
  9722. debug('_parseConnect: packet.username: %s', packet.username)
  9723. }
  9724. // Parse password
  9725. if (flags.password) {
  9726. password = this._parseBuffer()
  9727. if (password === null) return this._emitError(new Error('Cannot parse password'))
  9728. packet.password = password
  9729. }
  9730. // need for right parse auth packet and self set up
  9731. this.settings = packet
  9732. debug('_parseConnect: complete')
  9733. return packet
  9734. }
  9735. _parseConnack () {
  9736. debug('_parseConnack')
  9737. const packet = this.packet
  9738. if (this._list.length < 1) return null
  9739. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  9740. if (this.settings.protocolVersion === 5) {
  9741. if (this._list.length >= 2) {
  9742. packet.reasonCode = this._list.readUInt8(this._pos++)
  9743. } else {
  9744. packet.reasonCode = 0
  9745. }
  9746. } else {
  9747. if (this._list.length < 2) return null
  9748. packet.returnCode = this._list.readUInt8(this._pos++)
  9749. }
  9750. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  9751. // mqtt 5 properties
  9752. if (this.settings.protocolVersion === 5) {
  9753. const properties = this._parseProperties()
  9754. if (Object.getOwnPropertyNames(properties).length) {
  9755. packet.properties = properties
  9756. }
  9757. }
  9758. debug('_parseConnack: complete')
  9759. }
  9760. _parsePublish () {
  9761. debug('_parsePublish')
  9762. const packet = this.packet
  9763. packet.topic = this._parseString()
  9764. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  9765. // Parse messageId
  9766. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  9767. // Properties mqtt 5
  9768. if (this.settings.protocolVersion === 5) {
  9769. const properties = this._parseProperties()
  9770. if (Object.getOwnPropertyNames(properties).length) {
  9771. packet.properties = properties
  9772. }
  9773. }
  9774. packet.payload = this._list.slice(this._pos, packet.length)
  9775. debug('_parsePublish: payload from buffer list: %o', packet.payload)
  9776. }
  9777. _parseSubscribe () {
  9778. debug('_parseSubscribe')
  9779. const packet = this.packet
  9780. let topic
  9781. let options
  9782. let qos
  9783. let rh
  9784. let rap
  9785. let nl
  9786. let subscription
  9787. if (packet.qos !== 1) {
  9788. return this._emitError(new Error('Wrong subscribe header'))
  9789. }
  9790. packet.subscriptions = []
  9791. if (!this._parseMessageId()) { return }
  9792. // Properties mqtt 5
  9793. if (this.settings.protocolVersion === 5) {
  9794. const properties = this._parseProperties()
  9795. if (Object.getOwnPropertyNames(properties).length) {
  9796. packet.properties = properties
  9797. }
  9798. }
  9799. while (this._pos < packet.length) {
  9800. // Parse topic
  9801. topic = this._parseString()
  9802. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  9803. if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload'))
  9804. options = this._parseByte()
  9805. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  9806. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  9807. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  9808. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  9809. subscription = { topic, qos }
  9810. // mqtt 5 options
  9811. if (this.settings.protocolVersion === 5) {
  9812. subscription.nl = nl
  9813. subscription.rap = rap
  9814. subscription.rh = rh
  9815. } else if (this.settings.bridgeMode) {
  9816. subscription.rh = 0
  9817. subscription.rap = true
  9818. subscription.nl = true
  9819. }
  9820. // Push pair to subscriptions
  9821. debug('_parseSubscribe: push subscription `%s` to subscription', subscription)
  9822. packet.subscriptions.push(subscription)
  9823. }
  9824. }
  9825. _parseSuback () {
  9826. debug('_parseSuback')
  9827. const packet = this.packet
  9828. this.packet.granted = []
  9829. if (!this._parseMessageId()) { return }
  9830. // Properties mqtt 5
  9831. if (this.settings.protocolVersion === 5) {
  9832. const properties = this._parseProperties()
  9833. if (Object.getOwnPropertyNames(properties).length) {
  9834. packet.properties = properties
  9835. }
  9836. }
  9837. // Parse granted QoSes
  9838. while (this._pos < this.packet.length) {
  9839. this.packet.granted.push(this._list.readUInt8(this._pos++))
  9840. }
  9841. }
  9842. _parseUnsubscribe () {
  9843. debug('_parseUnsubscribe')
  9844. const packet = this.packet
  9845. packet.unsubscriptions = []
  9846. // Parse messageId
  9847. if (!this._parseMessageId()) { return }
  9848. // Properties mqtt 5
  9849. if (this.settings.protocolVersion === 5) {
  9850. const properties = this._parseProperties()
  9851. if (Object.getOwnPropertyNames(properties).length) {
  9852. packet.properties = properties
  9853. }
  9854. }
  9855. while (this._pos < packet.length) {
  9856. // Parse topic
  9857. const topic = this._parseString()
  9858. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  9859. // Push topic to unsubscriptions
  9860. debug('_parseUnsubscribe: push topic `%s` to unsubscriptions', topic)
  9861. packet.unsubscriptions.push(topic)
  9862. }
  9863. }
  9864. _parseUnsuback () {
  9865. debug('_parseUnsuback')
  9866. const packet = this.packet
  9867. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  9868. // Properties mqtt 5
  9869. if (this.settings.protocolVersion === 5) {
  9870. const properties = this._parseProperties()
  9871. if (Object.getOwnPropertyNames(properties).length) {
  9872. packet.properties = properties
  9873. }
  9874. // Parse granted QoSes
  9875. packet.granted = []
  9876. while (this._pos < this.packet.length) {
  9877. this.packet.granted.push(this._list.readUInt8(this._pos++))
  9878. }
  9879. }
  9880. }
  9881. // parse packets like puback, pubrec, pubrel, pubcomp
  9882. _parseConfirmation () {
  9883. debug('_parseConfirmation: packet.cmd: `%s`', this.packet.cmd)
  9884. const packet = this.packet
  9885. this._parseMessageId()
  9886. if (this.settings.protocolVersion === 5) {
  9887. if (packet.length > 2) {
  9888. // response code
  9889. packet.reasonCode = this._parseByte()
  9890. debug('_parseConfirmation: packet.reasonCode `%d`', packet.reasonCode)
  9891. } else {
  9892. packet.reasonCode = 0
  9893. }
  9894. if (packet.length > 3) {
  9895. // properies mqtt 5
  9896. const properties = this._parseProperties()
  9897. if (Object.getOwnPropertyNames(properties).length) {
  9898. packet.properties = properties
  9899. }
  9900. }
  9901. }
  9902. return true
  9903. }
  9904. // parse disconnect packet
  9905. _parseDisconnect () {
  9906. const packet = this.packet
  9907. debug('_parseDisconnect')
  9908. if (this.settings.protocolVersion === 5) {
  9909. // response code
  9910. if (this._list.length > 0) {
  9911. packet.reasonCode = this._parseByte()
  9912. } else {
  9913. packet.reasonCode = 0
  9914. }
  9915. // properies mqtt 5
  9916. const properties = this._parseProperties()
  9917. if (Object.getOwnPropertyNames(properties).length) {
  9918. packet.properties = properties
  9919. }
  9920. }
  9921. debug('_parseDisconnect result: true')
  9922. return true
  9923. }
  9924. // parse auth packet
  9925. _parseAuth () {
  9926. debug('_parseAuth')
  9927. const packet = this.packet
  9928. if (this.settings.protocolVersion !== 5) {
  9929. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  9930. }
  9931. // response code
  9932. packet.reasonCode = this._parseByte()
  9933. // properies mqtt 5
  9934. const properties = this._parseProperties()
  9935. if (Object.getOwnPropertyNames(properties).length) {
  9936. packet.properties = properties
  9937. }
  9938. debug('_parseAuth: result: true')
  9939. return true
  9940. }
  9941. _parseMessageId () {
  9942. const packet = this.packet
  9943. packet.messageId = this._parseNum()
  9944. if (packet.messageId === null) {
  9945. this._emitError(new Error('Cannot parse messageId'))
  9946. return false
  9947. }
  9948. debug('_parseMessageId: packet.messageId %d', packet.messageId)
  9949. return true
  9950. }
  9951. _parseString (maybeBuffer) {
  9952. const length = this._parseNum()
  9953. const end = length + this._pos
  9954. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  9955. const result = this._list.toString('utf8', this._pos, end)
  9956. this._pos += length
  9957. debug('_parseString: result: %s', result)
  9958. return result
  9959. }
  9960. _parseStringPair () {
  9961. debug('_parseStringPair')
  9962. return {
  9963. name: this._parseString(),
  9964. value: this._parseString()
  9965. }
  9966. }
  9967. _parseBuffer () {
  9968. const length = this._parseNum()
  9969. const end = length + this._pos
  9970. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  9971. const result = this._list.slice(this._pos, end)
  9972. this._pos += length
  9973. debug('_parseBuffer: result: %o', result)
  9974. return result
  9975. }
  9976. _parseNum () {
  9977. if (this._list.length - this._pos < 2) return -1
  9978. const result = this._list.readUInt16BE(this._pos)
  9979. this._pos += 2
  9980. debug('_parseNum: result: %s', result)
  9981. return result
  9982. }
  9983. _parse4ByteNum () {
  9984. if (this._list.length - this._pos < 4) return -1
  9985. const result = this._list.readUInt32BE(this._pos)
  9986. this._pos += 4
  9987. debug('_parse4ByteNum: result: %s', result)
  9988. return result
  9989. }
  9990. _parseVarByteNum (fullInfoFlag) {
  9991. debug('_parseVarByteNum')
  9992. const maxBytes = 4
  9993. let bytes = 0
  9994. let mul = 1
  9995. let value = 0
  9996. let result = false
  9997. let current
  9998. const padding = this._pos ? this._pos : 0
  9999. while (bytes < maxBytes && (padding + bytes) < this._list.length) {
  10000. current = this._list.readUInt8(padding + bytes++)
  10001. value += mul * (current & constants.VARBYTEINT_MASK)
  10002. mul *= 0x80
  10003. if ((current & constants.VARBYTEINT_FIN_MASK) === 0) {
  10004. result = true
  10005. break
  10006. }
  10007. if (this._list.length <= bytes) {
  10008. break
  10009. }
  10010. }
  10011. if (!result && bytes === maxBytes && this._list.length >= bytes) {
  10012. this._emitError(new Error('Invalid variable byte integer'))
  10013. }
  10014. if (padding) {
  10015. this._pos += bytes
  10016. }
  10017. result = result
  10018. ? fullInfoFlag ? {
  10019. bytes,
  10020. value
  10021. } : value
  10022. : false
  10023. debug('_parseVarByteNum: result: %o', result)
  10024. return result
  10025. }
  10026. _parseByte () {
  10027. let result
  10028. if (this._pos < this._list.length) {
  10029. result = this._list.readUInt8(this._pos)
  10030. this._pos++
  10031. }
  10032. debug('_parseByte: result: %o', result)
  10033. return result
  10034. }
  10035. _parseByType (type) {
  10036. debug('_parseByType: type: %s', type)
  10037. switch (type) {
  10038. case 'byte': {
  10039. return this._parseByte() !== 0
  10040. }
  10041. case 'int8': {
  10042. return this._parseByte()
  10043. }
  10044. case 'int16': {
  10045. return this._parseNum()
  10046. }
  10047. case 'int32': {
  10048. return this._parse4ByteNum()
  10049. }
  10050. case 'var': {
  10051. return this._parseVarByteNum()
  10052. }
  10053. case 'string': {
  10054. return this._parseString()
  10055. }
  10056. case 'pair': {
  10057. return this._parseStringPair()
  10058. }
  10059. case 'binary': {
  10060. return this._parseBuffer()
  10061. }
  10062. }
  10063. }
  10064. _parseProperties () {
  10065. debug('_parseProperties')
  10066. const length = this._parseVarByteNum()
  10067. const start = this._pos
  10068. const end = start + length
  10069. const result = {}
  10070. while (this._pos < end) {
  10071. const type = this._parseByte()
  10072. if (!type) {
  10073. this._emitError(new Error('Cannot parse property code type'))
  10074. return false
  10075. }
  10076. const name = constants.propertiesCodes[type]
  10077. if (!name) {
  10078. this._emitError(new Error('Unknown property'))
  10079. return false
  10080. }
  10081. // user properties process
  10082. if (name === 'userProperties') {
  10083. if (!result[name]) {
  10084. result[name] = Object.create(null)
  10085. }
  10086. const currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  10087. if (result[name][currentUserProperty.name]) {
  10088. if (Array.isArray(result[name][currentUserProperty.name])) {
  10089. result[name][currentUserProperty.name].push(currentUserProperty.value)
  10090. } else {
  10091. const currentValue = result[name][currentUserProperty.name]
  10092. result[name][currentUserProperty.name] = [currentValue]
  10093. result[name][currentUserProperty.name].push(currentUserProperty.value)
  10094. }
  10095. } else {
  10096. result[name][currentUserProperty.name] = currentUserProperty.value
  10097. }
  10098. continue
  10099. }
  10100. if (result[name]) {
  10101. if (Array.isArray(result[name])) {
  10102. result[name].push(this._parseByType(constants.propertiesTypes[name]))
  10103. } else {
  10104. result[name] = [result[name]]
  10105. result[name].push(this._parseByType(constants.propertiesTypes[name]))
  10106. }
  10107. } else {
  10108. result[name] = this._parseByType(constants.propertiesTypes[name])
  10109. }
  10110. }
  10111. return result
  10112. }
  10113. _newPacket () {
  10114. debug('_newPacket')
  10115. if (this.packet) {
  10116. this._list.consume(this.packet.length)
  10117. debug('_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d', this.packet.cmd, this.packet.payload, this.packet.length)
  10118. this.emit('packet', this.packet)
  10119. }
  10120. debug('_newPacket: new packet')
  10121. this.packet = new Packet()
  10122. this._pos = 0
  10123. return true
  10124. }
  10125. _emitError (err) {
  10126. debug('_emitError')
  10127. this.error = err
  10128. this.emit('error', err)
  10129. }
  10130. }
  10131. module.exports = Parser
  10132. },{"./constants":38,"./packet":42,"bl":15,"debug":18,"events":22}],44:[function(require,module,exports){
  10133. (function (Buffer){(function (){
  10134. const protocol = require('./constants')
  10135. const empty = Buffer.allocUnsafe(0)
  10136. const zeroBuf = Buffer.from([0])
  10137. const numbers = require('./numbers')
  10138. const nextTick = require('process-nextick-args').nextTick
  10139. const debug = require('debug')('mqtt-packet:writeToStream')
  10140. const numCache = numbers.cache
  10141. const generateNumber = numbers.generateNumber
  10142. const generateCache = numbers.generateCache
  10143. const genBufVariableByteInt = numbers.genBufVariableByteInt
  10144. const generate4ByteBuffer = numbers.generate4ByteBuffer
  10145. let writeNumber = writeNumberCached
  10146. let toGenerate = true
  10147. function generate (packet, stream, opts) {
  10148. debug('generate called')
  10149. if (stream.cork) {
  10150. stream.cork()
  10151. nextTick(uncork, stream)
  10152. }
  10153. if (toGenerate) {
  10154. toGenerate = false
  10155. generateCache()
  10156. }
  10157. debug('generate: packet.cmd: %s', packet.cmd)
  10158. switch (packet.cmd) {
  10159. case 'connect':
  10160. return connect(packet, stream, opts)
  10161. case 'connack':
  10162. return connack(packet, stream, opts)
  10163. case 'publish':
  10164. return publish(packet, stream, opts)
  10165. case 'puback':
  10166. case 'pubrec':
  10167. case 'pubrel':
  10168. case 'pubcomp':
  10169. return confirmation(packet, stream, opts)
  10170. case 'subscribe':
  10171. return subscribe(packet, stream, opts)
  10172. case 'suback':
  10173. return suback(packet, stream, opts)
  10174. case 'unsubscribe':
  10175. return unsubscribe(packet, stream, opts)
  10176. case 'unsuback':
  10177. return unsuback(packet, stream, opts)
  10178. case 'pingreq':
  10179. case 'pingresp':
  10180. return emptyPacket(packet, stream, opts)
  10181. case 'disconnect':
  10182. return disconnect(packet, stream, opts)
  10183. case 'auth':
  10184. return auth(packet, stream, opts)
  10185. default:
  10186. stream.emit('error', new Error('Unknown command'))
  10187. return false
  10188. }
  10189. }
  10190. /**
  10191. * Controls numbers cache.
  10192. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  10193. */
  10194. Object.defineProperty(generate, 'cacheNumbers', {
  10195. get () {
  10196. return writeNumber === writeNumberCached
  10197. },
  10198. set (value) {
  10199. if (value) {
  10200. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  10201. writeNumber = writeNumberCached
  10202. } else {
  10203. toGenerate = false
  10204. writeNumber = writeNumberGenerated
  10205. }
  10206. }
  10207. })
  10208. function uncork (stream) {
  10209. stream.uncork()
  10210. }
  10211. function connect (packet, stream, opts) {
  10212. const settings = packet || {}
  10213. const protocolId = settings.protocolId || 'MQTT'
  10214. let protocolVersion = settings.protocolVersion || 4
  10215. const will = settings.will
  10216. let clean = settings.clean
  10217. const keepalive = settings.keepalive || 0
  10218. const clientId = settings.clientId || ''
  10219. const username = settings.username
  10220. const password = settings.password
  10221. /* mqtt5 new oprions */
  10222. const properties = settings.properties
  10223. if (clean === undefined) clean = true
  10224. let length = 0
  10225. // Must be a string and non-falsy
  10226. if (!protocolId ||
  10227. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  10228. stream.emit('error', new Error('Invalid protocolId'))
  10229. return false
  10230. } else length += protocolId.length + 2
  10231. // Must be 3 or 4 or 5
  10232. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  10233. stream.emit('error', new Error('Invalid protocol version'))
  10234. return false
  10235. } else length += 1
  10236. // ClientId might be omitted in 3.1.1 and 5, but only if cleanSession is set to 1
  10237. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  10238. (clientId || protocolVersion >= 4) && (clientId || clean)) {
  10239. length += Buffer.byteLength(clientId) + 2
  10240. } else {
  10241. if (protocolVersion < 4) {
  10242. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  10243. return false
  10244. }
  10245. if ((clean * 1) === 0) {
  10246. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  10247. return false
  10248. }
  10249. }
  10250. // Must be a two byte number
  10251. if (typeof keepalive !== 'number' ||
  10252. keepalive < 0 ||
  10253. keepalive > 65535 ||
  10254. keepalive % 1 !== 0) {
  10255. stream.emit('error', new Error('Invalid keepalive'))
  10256. return false
  10257. } else length += 2
  10258. // Connect flags
  10259. length += 1
  10260. // Properties
  10261. if (protocolVersion === 5) {
  10262. var propertiesData = getProperties(stream, properties)
  10263. if (!propertiesData) { return false }
  10264. length += propertiesData.length
  10265. }
  10266. // If will exists...
  10267. if (will) {
  10268. // It must be an object
  10269. if (typeof will !== 'object') {
  10270. stream.emit('error', new Error('Invalid will'))
  10271. return false
  10272. }
  10273. // It must have topic typeof string
  10274. if (!will.topic || typeof will.topic !== 'string') {
  10275. stream.emit('error', new Error('Invalid will topic'))
  10276. return false
  10277. } else {
  10278. length += Buffer.byteLength(will.topic) + 2
  10279. }
  10280. // Payload
  10281. length += 2 // payload length
  10282. if (will.payload) {
  10283. if (will.payload.length >= 0) {
  10284. if (typeof will.payload === 'string') {
  10285. length += Buffer.byteLength(will.payload)
  10286. } else {
  10287. length += will.payload.length
  10288. }
  10289. } else {
  10290. stream.emit('error', new Error('Invalid will payload'))
  10291. return false
  10292. }
  10293. }
  10294. // will properties
  10295. var willProperties = {}
  10296. if (protocolVersion === 5) {
  10297. willProperties = getProperties(stream, will.properties)
  10298. if (!willProperties) { return false }
  10299. length += willProperties.length
  10300. }
  10301. }
  10302. // Username
  10303. let providedUsername = false
  10304. if (username != null) {
  10305. if (isStringOrBuffer(username)) {
  10306. providedUsername = true
  10307. length += Buffer.byteLength(username) + 2
  10308. } else {
  10309. stream.emit('error', new Error('Invalid username'))
  10310. return false
  10311. }
  10312. }
  10313. // Password
  10314. if (password != null) {
  10315. if (!providedUsername) {
  10316. stream.emit('error', new Error('Username is required to use password'))
  10317. return false
  10318. }
  10319. if (isStringOrBuffer(password)) {
  10320. length += byteLength(password) + 2
  10321. } else {
  10322. stream.emit('error', new Error('Invalid password'))
  10323. return false
  10324. }
  10325. }
  10326. // Generate header
  10327. stream.write(protocol.CONNECT_HEADER)
  10328. // Generate length
  10329. writeVarByteInt(stream, length)
  10330. // Generate protocol ID
  10331. writeStringOrBuffer(stream, protocolId)
  10332. if (settings.bridgeMode) {
  10333. protocolVersion += 128
  10334. }
  10335. stream.write(
  10336. protocolVersion === 131
  10337. ? protocol.VERSION131
  10338. : protocolVersion === 132
  10339. ? protocol.VERSION132
  10340. : protocolVersion === 4
  10341. ? protocol.VERSION4
  10342. : protocolVersion === 5
  10343. ? protocol.VERSION5
  10344. : protocol.VERSION3
  10345. )
  10346. // Connect flags
  10347. let flags = 0
  10348. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  10349. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  10350. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  10351. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  10352. flags |= will ? protocol.WILL_FLAG_MASK : 0
  10353. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  10354. stream.write(Buffer.from([flags]))
  10355. // Keepalive
  10356. writeNumber(stream, keepalive)
  10357. // Properties
  10358. if (protocolVersion === 5) {
  10359. propertiesData.write()
  10360. }
  10361. // Client ID
  10362. writeStringOrBuffer(stream, clientId)
  10363. // Will
  10364. if (will) {
  10365. if (protocolVersion === 5) {
  10366. willProperties.write()
  10367. }
  10368. writeString(stream, will.topic)
  10369. writeStringOrBuffer(stream, will.payload)
  10370. }
  10371. // Username and password
  10372. if (username != null) {
  10373. writeStringOrBuffer(stream, username)
  10374. }
  10375. if (password != null) {
  10376. writeStringOrBuffer(stream, password)
  10377. }
  10378. // This is a small packet that happens only once on a stream
  10379. // We assume the stream is always free to receive more data after this
  10380. return true
  10381. }
  10382. function connack (packet, stream, opts) {
  10383. const version = opts ? opts.protocolVersion : 4
  10384. const settings = packet || {}
  10385. const rc = version === 5 ? settings.reasonCode : settings.returnCode
  10386. const properties = settings.properties
  10387. let length = 2 // length of rc and sessionHeader
  10388. // Check return code
  10389. if (typeof rc !== 'number') {
  10390. stream.emit('error', new Error('Invalid return code'))
  10391. return false
  10392. }
  10393. // mqtt5 properties
  10394. let propertiesData = null
  10395. if (version === 5) {
  10396. propertiesData = getProperties(stream, properties)
  10397. if (!propertiesData) { return false }
  10398. length += propertiesData.length
  10399. }
  10400. stream.write(protocol.CONNACK_HEADER)
  10401. // length
  10402. writeVarByteInt(stream, length)
  10403. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  10404. stream.write(Buffer.from([rc]))
  10405. if (propertiesData != null) {
  10406. propertiesData.write()
  10407. }
  10408. return true
  10409. }
  10410. function publish (packet, stream, opts) {
  10411. debug('publish: packet: %o', packet)
  10412. const version = opts ? opts.protocolVersion : 4
  10413. const settings = packet || {}
  10414. const qos = settings.qos || 0
  10415. const retain = settings.retain ? protocol.RETAIN_MASK : 0
  10416. const topic = settings.topic
  10417. const payload = settings.payload || empty
  10418. const id = settings.messageId
  10419. const properties = settings.properties
  10420. let length = 0
  10421. // Topic must be a non-empty string or Buffer
  10422. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  10423. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  10424. else {
  10425. stream.emit('error', new Error('Invalid topic'))
  10426. return false
  10427. }
  10428. // Get the payload length
  10429. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  10430. else length += payload.length
  10431. // Message ID must a number if qos > 0
  10432. if (qos && typeof id !== 'number') {
  10433. stream.emit('error', new Error('Invalid messageId'))
  10434. return false
  10435. } else if (qos) length += 2
  10436. // mqtt5 properties
  10437. let propertiesData = null
  10438. if (version === 5) {
  10439. propertiesData = getProperties(stream, properties)
  10440. if (!propertiesData) { return false }
  10441. length += propertiesData.length
  10442. }
  10443. // Header
  10444. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  10445. // Remaining length
  10446. writeVarByteInt(stream, length)
  10447. // Topic
  10448. writeNumber(stream, byteLength(topic))
  10449. stream.write(topic)
  10450. // Message ID
  10451. if (qos > 0) writeNumber(stream, id)
  10452. // Properties
  10453. if (propertiesData != null) {
  10454. propertiesData.write()
  10455. }
  10456. // Payload
  10457. debug('publish: payload: %o', payload)
  10458. return stream.write(payload)
  10459. }
  10460. /* Puback, pubrec, pubrel and pubcomp */
  10461. function confirmation (packet, stream, opts) {
  10462. const version = opts ? opts.protocolVersion : 4
  10463. const settings = packet || {}
  10464. const type = settings.cmd || 'puback'
  10465. const id = settings.messageId
  10466. const dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  10467. let qos = 0
  10468. const reasonCode = settings.reasonCode
  10469. const properties = settings.properties
  10470. let length = version === 5 ? 3 : 2
  10471. if (type === 'pubrel') qos = 1
  10472. // Check message ID
  10473. if (typeof id !== 'number') {
  10474. stream.emit('error', new Error('Invalid messageId'))
  10475. return false
  10476. }
  10477. // properies mqtt 5
  10478. let propertiesData = null
  10479. if (version === 5) {
  10480. // Confirm should not add empty property length with no properties (rfc 3.4.2.2.1)
  10481. if (typeof properties === 'object') {
  10482. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10483. if (!propertiesData) { return false }
  10484. length += propertiesData.length
  10485. }
  10486. }
  10487. // Header
  10488. stream.write(protocol.ACKS[type][qos][dup][0])
  10489. // Length
  10490. writeVarByteInt(stream, length)
  10491. // Message ID
  10492. writeNumber(stream, id)
  10493. // reason code in header
  10494. if (version === 5) {
  10495. stream.write(Buffer.from([reasonCode]))
  10496. }
  10497. // properies mqtt 5
  10498. if (propertiesData !== null) {
  10499. propertiesData.write()
  10500. }
  10501. return true
  10502. }
  10503. function subscribe (packet, stream, opts) {
  10504. debug('subscribe: packet: ')
  10505. const version = opts ? opts.protocolVersion : 4
  10506. const settings = packet || {}
  10507. const dup = settings.dup ? protocol.DUP_MASK : 0
  10508. const id = settings.messageId
  10509. const subs = settings.subscriptions
  10510. const properties = settings.properties
  10511. let length = 0
  10512. // Check message ID
  10513. if (typeof id !== 'number') {
  10514. stream.emit('error', new Error('Invalid messageId'))
  10515. return false
  10516. } else length += 2
  10517. // properies mqtt 5
  10518. let propertiesData = null
  10519. if (version === 5) {
  10520. propertiesData = getProperties(stream, properties)
  10521. if (!propertiesData) { return false }
  10522. length += propertiesData.length
  10523. }
  10524. // Check subscriptions
  10525. if (typeof subs === 'object' && subs.length) {
  10526. for (let i = 0; i < subs.length; i += 1) {
  10527. const itopic = subs[i].topic
  10528. const iqos = subs[i].qos
  10529. if (typeof itopic !== 'string') {
  10530. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  10531. return false
  10532. }
  10533. if (typeof iqos !== 'number') {
  10534. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  10535. return false
  10536. }
  10537. if (version === 5) {
  10538. const nl = subs[i].nl || false
  10539. if (typeof nl !== 'boolean') {
  10540. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  10541. return false
  10542. }
  10543. const rap = subs[i].rap || false
  10544. if (typeof rap !== 'boolean') {
  10545. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  10546. return false
  10547. }
  10548. const rh = subs[i].rh || 0
  10549. if (typeof rh !== 'number' || rh > 2) {
  10550. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  10551. return false
  10552. }
  10553. }
  10554. length += Buffer.byteLength(itopic) + 2 + 1
  10555. }
  10556. } else {
  10557. stream.emit('error', new Error('Invalid subscriptions'))
  10558. return false
  10559. }
  10560. // Generate header
  10561. debug('subscribe: writing to stream: %o', protocol.SUBSCRIBE_HEADER)
  10562. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  10563. // Generate length
  10564. writeVarByteInt(stream, length)
  10565. // Generate message ID
  10566. writeNumber(stream, id)
  10567. // properies mqtt 5
  10568. if (propertiesData !== null) {
  10569. propertiesData.write()
  10570. }
  10571. let result = true
  10572. // Generate subs
  10573. for (const sub of subs) {
  10574. const jtopic = sub.topic
  10575. const jqos = sub.qos
  10576. const jnl = +sub.nl
  10577. const jrap = +sub.rap
  10578. const jrh = sub.rh
  10579. let joptions
  10580. // Write topic string
  10581. writeString(stream, jtopic)
  10582. // options process
  10583. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  10584. if (version === 5) {
  10585. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  10586. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  10587. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  10588. }
  10589. // Write options
  10590. result = stream.write(Buffer.from([joptions]))
  10591. }
  10592. return result
  10593. }
  10594. function suback (packet, stream, opts) {
  10595. const version = opts ? opts.protocolVersion : 4
  10596. const settings = packet || {}
  10597. const id = settings.messageId
  10598. const granted = settings.granted
  10599. const properties = settings.properties
  10600. let length = 0
  10601. // Check message ID
  10602. if (typeof id !== 'number') {
  10603. stream.emit('error', new Error('Invalid messageId'))
  10604. return false
  10605. } else length += 2
  10606. // Check granted qos vector
  10607. if (typeof granted === 'object' && granted.length) {
  10608. for (let i = 0; i < granted.length; i += 1) {
  10609. if (typeof granted[i] !== 'number') {
  10610. stream.emit('error', new Error('Invalid qos vector'))
  10611. return false
  10612. }
  10613. length += 1
  10614. }
  10615. } else {
  10616. stream.emit('error', new Error('Invalid qos vector'))
  10617. return false
  10618. }
  10619. // properies mqtt 5
  10620. let propertiesData = null
  10621. if (version === 5) {
  10622. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10623. if (!propertiesData) { return false }
  10624. length += propertiesData.length
  10625. }
  10626. // header
  10627. stream.write(protocol.SUBACK_HEADER)
  10628. // Length
  10629. writeVarByteInt(stream, length)
  10630. // Message ID
  10631. writeNumber(stream, id)
  10632. // properies mqtt 5
  10633. if (propertiesData !== null) {
  10634. propertiesData.write()
  10635. }
  10636. return stream.write(Buffer.from(granted))
  10637. }
  10638. function unsubscribe (packet, stream, opts) {
  10639. const version = opts ? opts.protocolVersion : 4
  10640. const settings = packet || {}
  10641. const id = settings.messageId
  10642. const dup = settings.dup ? protocol.DUP_MASK : 0
  10643. const unsubs = settings.unsubscriptions
  10644. const properties = settings.properties
  10645. let length = 0
  10646. // Check message ID
  10647. if (typeof id !== 'number') {
  10648. stream.emit('error', new Error('Invalid messageId'))
  10649. return false
  10650. } else {
  10651. length += 2
  10652. }
  10653. // Check unsubs
  10654. if (typeof unsubs === 'object' && unsubs.length) {
  10655. for (let i = 0; i < unsubs.length; i += 1) {
  10656. if (typeof unsubs[i] !== 'string') {
  10657. stream.emit('error', new Error('Invalid unsubscriptions'))
  10658. return false
  10659. }
  10660. length += Buffer.byteLength(unsubs[i]) + 2
  10661. }
  10662. } else {
  10663. stream.emit('error', new Error('Invalid unsubscriptions'))
  10664. return false
  10665. }
  10666. // properies mqtt 5
  10667. let propertiesData = null
  10668. if (version === 5) {
  10669. propertiesData = getProperties(stream, properties)
  10670. if (!propertiesData) { return false }
  10671. length += propertiesData.length
  10672. }
  10673. // Header
  10674. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  10675. // Length
  10676. writeVarByteInt(stream, length)
  10677. // Message ID
  10678. writeNumber(stream, id)
  10679. // properies mqtt 5
  10680. if (propertiesData !== null) {
  10681. propertiesData.write()
  10682. }
  10683. // Unsubs
  10684. let result = true
  10685. for (let j = 0; j < unsubs.length; j++) {
  10686. result = writeString(stream, unsubs[j])
  10687. }
  10688. return result
  10689. }
  10690. function unsuback (packet, stream, opts) {
  10691. const version = opts ? opts.protocolVersion : 4
  10692. const settings = packet || {}
  10693. const id = settings.messageId
  10694. const dup = settings.dup ? protocol.DUP_MASK : 0
  10695. const granted = settings.granted
  10696. const properties = settings.properties
  10697. const type = settings.cmd
  10698. const qos = 0
  10699. let length = 2
  10700. // Check message ID
  10701. if (typeof id !== 'number') {
  10702. stream.emit('error', new Error('Invalid messageId'))
  10703. return false
  10704. }
  10705. // Check granted
  10706. if (version === 5) {
  10707. if (typeof granted === 'object' && granted.length) {
  10708. for (let i = 0; i < granted.length; i += 1) {
  10709. if (typeof granted[i] !== 'number') {
  10710. stream.emit('error', new Error('Invalid qos vector'))
  10711. return false
  10712. }
  10713. length += 1
  10714. }
  10715. } else {
  10716. stream.emit('error', new Error('Invalid qos vector'))
  10717. return false
  10718. }
  10719. }
  10720. // properies mqtt 5
  10721. let propertiesData = null
  10722. if (version === 5) {
  10723. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10724. if (!propertiesData) { return false }
  10725. length += propertiesData.length
  10726. }
  10727. // Header
  10728. stream.write(protocol.ACKS[type][qos][dup][0])
  10729. // Length
  10730. writeVarByteInt(stream, length)
  10731. // Message ID
  10732. writeNumber(stream, id)
  10733. // properies mqtt 5
  10734. if (propertiesData !== null) {
  10735. propertiesData.write()
  10736. }
  10737. // payload
  10738. if (version === 5) {
  10739. stream.write(Buffer.from(granted))
  10740. }
  10741. return true
  10742. }
  10743. function emptyPacket (packet, stream, opts) {
  10744. return stream.write(protocol.EMPTY[packet.cmd])
  10745. }
  10746. function disconnect (packet, stream, opts) {
  10747. const version = opts ? opts.protocolVersion : 4
  10748. const settings = packet || {}
  10749. const reasonCode = settings.reasonCode
  10750. const properties = settings.properties
  10751. let length = version === 5 ? 1 : 0
  10752. // properies mqtt 5
  10753. let propertiesData = null
  10754. if (version === 5) {
  10755. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10756. if (!propertiesData) { return false }
  10757. length += propertiesData.length
  10758. }
  10759. // Header
  10760. stream.write(Buffer.from([protocol.codes.disconnect << 4]))
  10761. // Length
  10762. writeVarByteInt(stream, length)
  10763. // reason code in header
  10764. if (version === 5) {
  10765. stream.write(Buffer.from([reasonCode]))
  10766. }
  10767. // properies mqtt 5
  10768. if (propertiesData !== null) {
  10769. propertiesData.write()
  10770. }
  10771. return true
  10772. }
  10773. function auth (packet, stream, opts) {
  10774. const version = opts ? opts.protocolVersion : 4
  10775. const settings = packet || {}
  10776. const reasonCode = settings.reasonCode
  10777. const properties = settings.properties
  10778. let length = version === 5 ? 1 : 0
  10779. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  10780. // properies mqtt 5
  10781. const propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10782. if (!propertiesData) { return false }
  10783. length += propertiesData.length
  10784. // Header
  10785. stream.write(Buffer.from([protocol.codes.auth << 4]))
  10786. // Length
  10787. writeVarByteInt(stream, length)
  10788. // reason code in header
  10789. stream.write(Buffer.from([reasonCode]))
  10790. // properies mqtt 5
  10791. if (propertiesData !== null) {
  10792. propertiesData.write()
  10793. }
  10794. return true
  10795. }
  10796. /**
  10797. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  10798. *
  10799. * @param <Buffer> buffer - destination
  10800. * @param <Number> pos - offset
  10801. * @param <Number> length - length (>0)
  10802. * @returns <Number> number of bytes written
  10803. *
  10804. * @api private
  10805. */
  10806. const varByteIntCache = {}
  10807. function writeVarByteInt (stream, num) {
  10808. if (num > protocol.VARBYTEINT_MAX) {
  10809. stream.emit('error', new Error(`Invalid variable byte integer: ${num}`))
  10810. return false
  10811. }
  10812. let buffer = varByteIntCache[num]
  10813. if (!buffer) {
  10814. buffer = genBufVariableByteInt(num)
  10815. if (num < 16384) varByteIntCache[num] = buffer
  10816. }
  10817. debug('writeVarByteInt: writing to stream: %o', buffer)
  10818. return stream.write(buffer)
  10819. }
  10820. /**
  10821. * writeString - write a utf8 string to the buffer
  10822. *
  10823. * @param <Buffer> buffer - destination
  10824. * @param <Number> pos - offset
  10825. * @param <String> string - string to write
  10826. * @return <Number> number of bytes written
  10827. *
  10828. * @api private
  10829. */
  10830. function writeString (stream, string) {
  10831. const strlen = Buffer.byteLength(string)
  10832. writeNumber(stream, strlen)
  10833. debug('writeString: %s', string)
  10834. return stream.write(string, 'utf8')
  10835. }
  10836. /**
  10837. * writeStringPair - write a utf8 string pairs to the buffer
  10838. *
  10839. * @param <Buffer> buffer - destination
  10840. * @param <String> name - string name to write
  10841. * @param <String> value - string value to write
  10842. * @return <Number> number of bytes written
  10843. *
  10844. * @api private
  10845. */
  10846. function writeStringPair (stream, name, value) {
  10847. writeString(stream, name)
  10848. writeString(stream, value)
  10849. }
  10850. /**
  10851. * writeNumber - write a two byte number to the buffer
  10852. *
  10853. * @param <Buffer> buffer - destination
  10854. * @param <Number> pos - offset
  10855. * @param <String> number - number to write
  10856. * @return <Number> number of bytes written
  10857. *
  10858. * @api private
  10859. */
  10860. function writeNumberCached (stream, number) {
  10861. debug('writeNumberCached: number: %d', number)
  10862. debug('writeNumberCached: %o', numCache[number])
  10863. return stream.write(numCache[number])
  10864. }
  10865. function writeNumberGenerated (stream, number) {
  10866. const generatedNumber = generateNumber(number)
  10867. debug('writeNumberGenerated: %o', generatedNumber)
  10868. return stream.write(generatedNumber)
  10869. }
  10870. function write4ByteNumber (stream, number) {
  10871. const generated4ByteBuffer = generate4ByteBuffer(number)
  10872. debug('write4ByteNumber: %o', generated4ByteBuffer)
  10873. return stream.write(generated4ByteBuffer)
  10874. }
  10875. /**
  10876. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  10877. *
  10878. * @param <Buffer> buffer - destination
  10879. * @param <Number> pos - offset
  10880. * @param <String> toWrite - String or Buffer
  10881. * @return <Number> number of bytes written
  10882. */
  10883. function writeStringOrBuffer (stream, toWrite) {
  10884. if (typeof toWrite === 'string') {
  10885. writeString(stream, toWrite)
  10886. } else if (toWrite) {
  10887. writeNumber(stream, toWrite.length)
  10888. stream.write(toWrite)
  10889. } else writeNumber(stream, 0)
  10890. }
  10891. function getProperties (stream, properties) {
  10892. /* connect properties */
  10893. if (typeof properties !== 'object' || properties.length != null) {
  10894. return {
  10895. length: 1,
  10896. write () {
  10897. writeProperties(stream, {}, 0)
  10898. }
  10899. }
  10900. }
  10901. let propertiesLength = 0
  10902. function getLengthProperty (name, value) {
  10903. const type = protocol.propertiesTypes[name]
  10904. let length = 0
  10905. switch (type) {
  10906. case 'byte': {
  10907. if (typeof value !== 'boolean') {
  10908. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10909. return false
  10910. }
  10911. length += 1 + 1
  10912. break
  10913. }
  10914. case 'int8': {
  10915. if (typeof value !== 'number' || value < 0 || value > 0xff) {
  10916. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10917. return false
  10918. }
  10919. length += 1 + 1
  10920. break
  10921. }
  10922. case 'binary': {
  10923. if (value && value === null) {
  10924. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10925. return false
  10926. }
  10927. length += 1 + Buffer.byteLength(value) + 2
  10928. break
  10929. }
  10930. case 'int16': {
  10931. if (typeof value !== 'number' || value < 0 || value > 0xffff) {
  10932. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10933. return false
  10934. }
  10935. length += 1 + 2
  10936. break
  10937. }
  10938. case 'int32': {
  10939. if (typeof value !== 'number' || value < 0 || value > 0xffffffff) {
  10940. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10941. return false
  10942. }
  10943. length += 1 + 4
  10944. break
  10945. }
  10946. case 'var': {
  10947. // var byte integer is max 24 bits packed in 32 bits
  10948. if (typeof value !== 'number' || value < 0 || value > 0x0fffffff) {
  10949. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10950. return false
  10951. }
  10952. length += 1 + Buffer.byteLength(genBufVariableByteInt(value))
  10953. break
  10954. }
  10955. case 'string': {
  10956. if (typeof value !== 'string') {
  10957. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10958. return false
  10959. }
  10960. length += 1 + 2 + Buffer.byteLength(value.toString())
  10961. break
  10962. }
  10963. case 'pair': {
  10964. if (typeof value !== 'object') {
  10965. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10966. return false
  10967. }
  10968. length += Object.getOwnPropertyNames(value).reduce((result, name) => {
  10969. const currentValue = value[name]
  10970. if (Array.isArray(currentValue)) {
  10971. result += currentValue.reduce((currentLength, value) => {
  10972. currentLength += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value.toString())
  10973. return currentLength
  10974. }, 0)
  10975. } else {
  10976. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  10977. }
  10978. return result
  10979. }, 0)
  10980. break
  10981. }
  10982. default: {
  10983. stream.emit('error', new Error(`Invalid property ${name}: ${value}`))
  10984. return false
  10985. }
  10986. }
  10987. return length
  10988. }
  10989. if (properties) {
  10990. for (const propName in properties) {
  10991. let propLength = 0
  10992. let propValueLength = 0
  10993. const propValue = properties[propName]
  10994. if (Array.isArray(propValue)) {
  10995. for (let valueIndex = 0; valueIndex < propValue.length; valueIndex++) {
  10996. propValueLength = getLengthProperty(propName, propValue[valueIndex])
  10997. if (!propValueLength) { return false }
  10998. propLength += propValueLength
  10999. }
  11000. } else {
  11001. propValueLength = getLengthProperty(propName, propValue)
  11002. if (!propValueLength) { return false }
  11003. propLength = propValueLength
  11004. }
  11005. if (!propLength) return false
  11006. propertiesLength += propLength
  11007. }
  11008. }
  11009. const propertiesLengthLength = Buffer.byteLength(genBufVariableByteInt(propertiesLength))
  11010. return {
  11011. length: propertiesLengthLength + propertiesLength,
  11012. write () {
  11013. writeProperties(stream, properties, propertiesLength)
  11014. }
  11015. }
  11016. }
  11017. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  11018. const mayEmptyProps = ['reasonString', 'userProperties']
  11019. const maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  11020. let propertiesData = getProperties(stream, properties)
  11021. if (maximumPacketSize) {
  11022. while (length + propertiesData.length > maximumPacketSize) {
  11023. const currentMayEmptyProp = mayEmptyProps.shift()
  11024. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  11025. delete properties[currentMayEmptyProp]
  11026. propertiesData = getProperties(stream, properties)
  11027. } else {
  11028. return false
  11029. }
  11030. }
  11031. }
  11032. return propertiesData
  11033. }
  11034. function writeProperty (stream, propName, value) {
  11035. const type = protocol.propertiesTypes[propName]
  11036. switch (type) {
  11037. case 'byte': {
  11038. stream.write(Buffer.from([protocol.properties[propName]]))
  11039. stream.write(Buffer.from([+value]))
  11040. break
  11041. }
  11042. case 'int8': {
  11043. stream.write(Buffer.from([protocol.properties[propName]]))
  11044. stream.write(Buffer.from([value]))
  11045. break
  11046. }
  11047. case 'binary': {
  11048. stream.write(Buffer.from([protocol.properties[propName]]))
  11049. writeStringOrBuffer(stream, value)
  11050. break
  11051. }
  11052. case 'int16': {
  11053. stream.write(Buffer.from([protocol.properties[propName]]))
  11054. writeNumber(stream, value)
  11055. break
  11056. }
  11057. case 'int32': {
  11058. stream.write(Buffer.from([protocol.properties[propName]]))
  11059. write4ByteNumber(stream, value)
  11060. break
  11061. }
  11062. case 'var': {
  11063. stream.write(Buffer.from([protocol.properties[propName]]))
  11064. writeVarByteInt(stream, value)
  11065. break
  11066. }
  11067. case 'string': {
  11068. stream.write(Buffer.from([protocol.properties[propName]]))
  11069. writeString(stream, value)
  11070. break
  11071. }
  11072. case 'pair': {
  11073. Object.getOwnPropertyNames(value).forEach(name => {
  11074. const currentValue = value[name]
  11075. if (Array.isArray(currentValue)) {
  11076. currentValue.forEach(value => {
  11077. stream.write(Buffer.from([protocol.properties[propName]]))
  11078. writeStringPair(stream, name.toString(), value.toString())
  11079. })
  11080. } else {
  11081. stream.write(Buffer.from([protocol.properties[propName]]))
  11082. writeStringPair(stream, name.toString(), currentValue.toString())
  11083. }
  11084. })
  11085. break
  11086. }
  11087. default: {
  11088. stream.emit('error', new Error(`Invalid property ${propName} value: ${value}`))
  11089. return false
  11090. }
  11091. }
  11092. }
  11093. function writeProperties (stream, properties, propertiesLength) {
  11094. /* write properties to stream */
  11095. writeVarByteInt(stream, propertiesLength)
  11096. for (const propName in properties) {
  11097. if (Object.prototype.hasOwnProperty.call(properties, propName) && properties[propName] !== null) {
  11098. const value = properties[propName]
  11099. if (Array.isArray(value)) {
  11100. for (let valueIndex = 0; valueIndex < value.length; valueIndex++) {
  11101. writeProperty(stream, propName, value[valueIndex])
  11102. }
  11103. } else {
  11104. writeProperty(stream, propName, value)
  11105. }
  11106. }
  11107. }
  11108. }
  11109. function byteLength (bufOrString) {
  11110. if (!bufOrString) return 0
  11111. else if (bufOrString instanceof Buffer) return bufOrString.length
  11112. else return Buffer.byteLength(bufOrString)
  11113. }
  11114. function isStringOrBuffer (field) {
  11115. return typeof field === 'string' || field instanceof Buffer
  11116. }
  11117. module.exports = generate
  11118. }).call(this)}).call(this,require("buffer").Buffer)
  11119. },{"./constants":38,"./numbers":41,"buffer":17,"debug":18,"process-nextick-args":49}],45:[function(require,module,exports){
  11120. /**
  11121. * Helpers.
  11122. */
  11123. var s = 1000;
  11124. var m = s * 60;
  11125. var h = m * 60;
  11126. var d = h * 24;
  11127. var w = d * 7;
  11128. var y = d * 365.25;
  11129. /**
  11130. * Parse or format the given `val`.
  11131. *
  11132. * Options:
  11133. *
  11134. * - `long` verbose formatting [false]
  11135. *
  11136. * @param {String|Number} val
  11137. * @param {Object} [options]
  11138. * @throws {Error} throw an error if val is not a non-empty string or a number
  11139. * @return {String|Number}
  11140. * @api public
  11141. */
  11142. module.exports = function(val, options) {
  11143. options = options || {};
  11144. var type = typeof val;
  11145. if (type === 'string' && val.length > 0) {
  11146. return parse(val);
  11147. } else if (type === 'number' && isFinite(val)) {
  11148. return options.long ? fmtLong(val) : fmtShort(val);
  11149. }
  11150. throw new Error(
  11151. 'val is not a non-empty string or a valid number. val=' +
  11152. JSON.stringify(val)
  11153. );
  11154. };
  11155. /**
  11156. * Parse the given `str` and return milliseconds.
  11157. *
  11158. * @param {String} str
  11159. * @return {Number}
  11160. * @api private
  11161. */
  11162. function parse(str) {
  11163. str = String(str);
  11164. if (str.length > 100) {
  11165. return;
  11166. }
  11167. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  11168. str
  11169. );
  11170. if (!match) {
  11171. return;
  11172. }
  11173. var n = parseFloat(match[1]);
  11174. var type = (match[2] || 'ms').toLowerCase();
  11175. switch (type) {
  11176. case 'years':
  11177. case 'year':
  11178. case 'yrs':
  11179. case 'yr':
  11180. case 'y':
  11181. return n * y;
  11182. case 'weeks':
  11183. case 'week':
  11184. case 'w':
  11185. return n * w;
  11186. case 'days':
  11187. case 'day':
  11188. case 'd':
  11189. return n * d;
  11190. case 'hours':
  11191. case 'hour':
  11192. case 'hrs':
  11193. case 'hr':
  11194. case 'h':
  11195. return n * h;
  11196. case 'minutes':
  11197. case 'minute':
  11198. case 'mins':
  11199. case 'min':
  11200. case 'm':
  11201. return n * m;
  11202. case 'seconds':
  11203. case 'second':
  11204. case 'secs':
  11205. case 'sec':
  11206. case 's':
  11207. return n * s;
  11208. case 'milliseconds':
  11209. case 'millisecond':
  11210. case 'msecs':
  11211. case 'msec':
  11212. case 'ms':
  11213. return n;
  11214. default:
  11215. return undefined;
  11216. }
  11217. }
  11218. /**
  11219. * Short format for `ms`.
  11220. *
  11221. * @param {Number} ms
  11222. * @return {String}
  11223. * @api private
  11224. */
  11225. function fmtShort(ms) {
  11226. var msAbs = Math.abs(ms);
  11227. if (msAbs >= d) {
  11228. return Math.round(ms / d) + 'd';
  11229. }
  11230. if (msAbs >= h) {
  11231. return Math.round(ms / h) + 'h';
  11232. }
  11233. if (msAbs >= m) {
  11234. return Math.round(ms / m) + 'm';
  11235. }
  11236. if (msAbs >= s) {
  11237. return Math.round(ms / s) + 's';
  11238. }
  11239. return ms + 'ms';
  11240. }
  11241. /**
  11242. * Long format for `ms`.
  11243. *
  11244. * @param {Number} ms
  11245. * @return {String}
  11246. * @api private
  11247. */
  11248. function fmtLong(ms) {
  11249. var msAbs = Math.abs(ms);
  11250. if (msAbs >= d) {
  11251. return plural(ms, msAbs, d, 'day');
  11252. }
  11253. if (msAbs >= h) {
  11254. return plural(ms, msAbs, h, 'hour');
  11255. }
  11256. if (msAbs >= m) {
  11257. return plural(ms, msAbs, m, 'minute');
  11258. }
  11259. if (msAbs >= s) {
  11260. return plural(ms, msAbs, s, 'second');
  11261. }
  11262. return ms + ' ms';
  11263. }
  11264. /**
  11265. * Pluralization helper.
  11266. */
  11267. function plural(ms, msAbs, n, name) {
  11268. var isPlural = msAbs >= n * 1.5;
  11269. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  11270. }
  11271. },{}],46:[function(require,module,exports){
  11272. // Copyright Takatoshi Kondo 2021
  11273. //
  11274. // Distributed under the MIT License
  11275. const NumberAllocator = require('./lib/number-allocator.js')
  11276. module.exports.NumberAllocator = NumberAllocator
  11277. },{"./lib/number-allocator.js":47}],47:[function(require,module,exports){
  11278. // Copyright Takatoshi Kondo 2021
  11279. //
  11280. // Distributed under the MIT License
  11281. 'use strict'
  11282. const SortedSet = require('js-sdsl').Set
  11283. const debugTrace = require('debug')('number-allocator:trace')
  11284. const debugError = require('debug')('number-allocator:error')
  11285. /**
  11286. * Interval constructor
  11287. * @constructor
  11288. * @param {Number} low - The lowest value of the interval
  11289. * @param {Number} high - The highest value of the interval
  11290. */
  11291. function Interval (low, high) {
  11292. this.low = low
  11293. this.high = high
  11294. }
  11295. Interval.prototype.equals = function (other) {
  11296. return this.low === other.low && this.high === other.high
  11297. }
  11298. Interval.prototype.compare = function (other) {
  11299. if (this.low < other.low && this.high < other.low) return -1
  11300. if (other.low < this.low && other.high < this.low) return 1
  11301. return 0
  11302. }
  11303. /**
  11304. * NumberAllocator constructor.
  11305. * The all numbers are set to vacant status.
  11306. * Time Complexity O(1)
  11307. * @constructor
  11308. * @param {Number} min - The maximum number of allocatable. The number must be integer.
  11309. * @param {Number} maxh - The minimum number of allocatable. The number must be integer.
  11310. */
  11311. function NumberAllocator (min, max) {
  11312. if (!(this instanceof NumberAllocator)) {
  11313. return new NumberAllocator(min, max)
  11314. }
  11315. this.min = min
  11316. this.max = max
  11317. this.ss = new SortedSet(
  11318. [],
  11319. (lhs, rhs) => {
  11320. return lhs.compare(rhs)
  11321. }
  11322. )
  11323. debugTrace('Create')
  11324. this.clear()
  11325. }
  11326. /**
  11327. * Get the first vacant number. The status of the number is not updated.
  11328. * Time Complexity O(1)
  11329. * @return {Number} - The first vacant number. If all numbers are occupied, return null.
  11330. * When alloc() is called then the same value will be allocated.
  11331. */
  11332. NumberAllocator.prototype.firstVacant = function () {
  11333. if (this.ss.size() === 0) return null
  11334. return this.ss.front().low
  11335. }
  11336. /**
  11337. * Allocate the first vacant number. The number become occupied status.
  11338. * Time Complexity O(1)
  11339. * @return {Number} - The first vacant number. If all numbers are occupied, return null.
  11340. */
  11341. NumberAllocator.prototype.alloc = function () {
  11342. if (this.ss.size() === 0) {
  11343. debugTrace('alloc():empty')
  11344. return null
  11345. }
  11346. const it = this.ss.front()
  11347. const num = it.low
  11348. if (num + 1 <= it.high) {
  11349. // Overwrite the interval in the ss but it is safe,
  11350. // because no order violation is happened.
  11351. // x|----|
  11352. ++it.low
  11353. } else {
  11354. this.ss.eraseElementByPos(0)
  11355. }
  11356. debugTrace('alloc():' + num)
  11357. return num
  11358. }
  11359. /**
  11360. * Use the number. The number become occupied status.
  11361. * If the number has already been occupied, then return false.
  11362. * Time Complexity O(logN) : N is the number of intervals (not numbers)
  11363. * @param {Number} num - The number to request use.
  11364. * @return {Boolean} - If `num` was not occupied, then return true, otherwise return false.
  11365. */
  11366. NumberAllocator.prototype.use = function (num) {
  11367. const key = new Interval(num, num)
  11368. const it = this.ss.lowerBound(key)
  11369. if (it) {
  11370. if (it.equals(key)) {
  11371. // |x|
  11372. this.ss.eraseElementByValue(it)
  11373. debugTrace('use():' + num)
  11374. return true
  11375. }
  11376. // x |-----|
  11377. if (it.low > num) return false
  11378. // |x----|
  11379. if (it.low === num) {
  11380. // Overwrite the interval in the ss but it is safe,
  11381. // because no order violation is happened.
  11382. // x|----|
  11383. ++it.low
  11384. debugTrace('use():' + num)
  11385. return true
  11386. }
  11387. // |----x|
  11388. if (it.high === num) {
  11389. // Overwrite the interval in the ss but it is safe,
  11390. // because no order violation is happened.
  11391. // |----|x
  11392. --it.high
  11393. debugTrace('use():' + num)
  11394. return true
  11395. }
  11396. const low = it.low
  11397. // |--x--|
  11398. // Overwrite the interval in the ss but it is safe,
  11399. // because no order violation is happened.
  11400. // x|--|
  11401. it.low = num + 1
  11402. // |--|x|--|
  11403. this.ss.insert(new Interval(low, num - 1))
  11404. debugTrace('use():' + num)
  11405. return true
  11406. }
  11407. debugTrace('use():failed')
  11408. return false
  11409. }
  11410. /**
  11411. * Deallocate the number. The number become vacant status.
  11412. * Time Complexity O(logN) : N is the number of intervals (not numbers)
  11413. * @param {Number} num - The number to deallocate. The number must be occupied status.
  11414. * In other words, the number must be allocated by alloc() or occupied be use().
  11415. */
  11416. NumberAllocator.prototype.free = function (num) {
  11417. if (num < this.min || num > this.max) {
  11418. debugError('free():' + num + ' is out of range')
  11419. return
  11420. }
  11421. const key = new Interval(num, num)
  11422. const it = this.ss.lowerBound(key)
  11423. if (it) {
  11424. if (it.low <= num && num <= it.high) {
  11425. debugError('free():' + num + ' has already been vacant')
  11426. return
  11427. }
  11428. if (it === this.ss.front()) {
  11429. // v....
  11430. if (num + 1 === it.low) {
  11431. // Concat to right
  11432. // Overwrite the interval in the ss but it is safe,
  11433. // because no order violation is happened.
  11434. --it.low
  11435. } else {
  11436. // Insert new interval
  11437. this.ss.insert(key)
  11438. }
  11439. } else {
  11440. // ..v..
  11441. const itl = this.ss.reverseLowerBound(key)
  11442. if (itl.high + 1 === num) {
  11443. if (num + 1 === it.low) {
  11444. // Concat to left and right
  11445. this.ss.eraseElementByValue(itl)
  11446. // Overwrite the interval in the ss but it is safe,
  11447. // because no order violation is happened.
  11448. it.low = itl.low
  11449. } else {
  11450. // Concat to left
  11451. // Overwrite the interval in the ss but it is safe,
  11452. // because no order violation is happened.
  11453. itl.high = num
  11454. }
  11455. } else {
  11456. if (num + 1 === it.low) {
  11457. // Concat to right
  11458. // Overwrite the interval in the ss but it is safe,
  11459. // because no order violation is happened.
  11460. it.low = num
  11461. } else {
  11462. // Insert new interval
  11463. this.ss.insert(key)
  11464. }
  11465. }
  11466. }
  11467. } else {
  11468. // ....v
  11469. if (it === this.ss.front()) {
  11470. // Insert new interval
  11471. this.ss.insert(key)
  11472. return
  11473. }
  11474. const itl = this.ss.reverseLowerBound(key)
  11475. if (itl.high + 1 === num) {
  11476. // Concat to left
  11477. // Overwrite the interval in the ss but it is safe,
  11478. // because no order violation is happened.
  11479. itl.high = num
  11480. } else {
  11481. // Insert new interval
  11482. this.ss.insert(key)
  11483. }
  11484. }
  11485. debugTrace('free():' + num)
  11486. }
  11487. /**
  11488. * Clear all occupied numbers.
  11489. * The all numbers are set to vacant status.
  11490. * Time Complexity O(1)
  11491. */
  11492. NumberAllocator.prototype.clear = function () {
  11493. debugTrace('clear()')
  11494. this.ss.clear()
  11495. this.ss.insert(new Interval(this.min, this.max))
  11496. }
  11497. /**
  11498. * Get the number of intervals. Interval is internal structure of this library.
  11499. * This function is for debugging.
  11500. * Time Complexity O(1)
  11501. * @return {Number} - The number of intervals.
  11502. */
  11503. NumberAllocator.prototype.intervalCount = function () {
  11504. return this.ss.size()
  11505. }
  11506. /**
  11507. * Dump the internal structor of the library.
  11508. * This function is for debugging.
  11509. * Time Complexity O(N) : N is the number of intervals (not numbers)
  11510. */
  11511. NumberAllocator.prototype.dump = function () {
  11512. console.log('length:' + this.ss.size())
  11513. for (const element of this.ss) {
  11514. console.log(element)
  11515. }
  11516. }
  11517. module.exports = NumberAllocator
  11518. },{"debug":18,"js-sdsl":36}],48:[function(require,module,exports){
  11519. var wrappy = require('wrappy')
  11520. module.exports = wrappy(once)
  11521. module.exports.strict = wrappy(onceStrict)
  11522. once.proto = once(function () {
  11523. Object.defineProperty(Function.prototype, 'once', {
  11524. value: function () {
  11525. return once(this)
  11526. },
  11527. configurable: true
  11528. })
  11529. Object.defineProperty(Function.prototype, 'onceStrict', {
  11530. value: function () {
  11531. return onceStrict(this)
  11532. },
  11533. configurable: true
  11534. })
  11535. })
  11536. function once (fn) {
  11537. var f = function () {
  11538. if (f.called) return f.value
  11539. f.called = true
  11540. return f.value = fn.apply(this, arguments)
  11541. }
  11542. f.called = false
  11543. return f
  11544. }
  11545. function onceStrict (fn) {
  11546. var f = function () {
  11547. if (f.called)
  11548. throw new Error(f.onceError)
  11549. f.called = true
  11550. return f.value = fn.apply(this, arguments)
  11551. }
  11552. var name = fn.name || 'Function wrapped with `once`'
  11553. f.onceError = name + " shouldn't be called more than once"
  11554. f.called = false
  11555. return f
  11556. }
  11557. },{"wrappy":79}],49:[function(require,module,exports){
  11558. (function (process){(function (){
  11559. 'use strict';
  11560. if (typeof process === 'undefined' ||
  11561. !process.version ||
  11562. process.version.indexOf('v0.') === 0 ||
  11563. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  11564. module.exports = { nextTick: nextTick };
  11565. } else {
  11566. module.exports = process
  11567. }
  11568. function nextTick(fn, arg1, arg2, arg3) {
  11569. if (typeof fn !== 'function') {
  11570. throw new TypeError('"callback" argument must be a function');
  11571. }
  11572. var len = arguments.length;
  11573. var args, i;
  11574. switch (len) {
  11575. case 0:
  11576. case 1:
  11577. return process.nextTick(fn);
  11578. case 2:
  11579. return process.nextTick(function afterTickOne() {
  11580. fn.call(null, arg1);
  11581. });
  11582. case 3:
  11583. return process.nextTick(function afterTickTwo() {
  11584. fn.call(null, arg1, arg2);
  11585. });
  11586. case 4:
  11587. return process.nextTick(function afterTickThree() {
  11588. fn.call(null, arg1, arg2, arg3);
  11589. });
  11590. default:
  11591. args = new Array(len - 1);
  11592. i = 0;
  11593. while (i < args.length) {
  11594. args[i++] = arguments[i];
  11595. }
  11596. return process.nextTick(function afterTick() {
  11597. fn.apply(null, args);
  11598. });
  11599. }
  11600. }
  11601. }).call(this)}).call(this,require('_process'))
  11602. },{"_process":50}],50:[function(require,module,exports){
  11603. // shim for using process in browser
  11604. var process = module.exports = {};
  11605. // cached from whatever global is present so that test runners that stub it
  11606. // don't break things. But we need to wrap it in a try catch in case it is
  11607. // wrapped in strict mode code which doesn't define any globals. It's inside a
  11608. // function because try/catches deoptimize in certain engines.
  11609. var cachedSetTimeout;
  11610. var cachedClearTimeout;
  11611. function defaultSetTimout() {
  11612. throw new Error('setTimeout has not been defined');
  11613. }
  11614. function defaultClearTimeout () {
  11615. throw new Error('clearTimeout has not been defined');
  11616. }
  11617. (function () {
  11618. try {
  11619. if (typeof setTimeout === 'function') {
  11620. cachedSetTimeout = setTimeout;
  11621. } else {
  11622. cachedSetTimeout = defaultSetTimout;
  11623. }
  11624. } catch (e) {
  11625. cachedSetTimeout = defaultSetTimout;
  11626. }
  11627. try {
  11628. if (typeof clearTimeout === 'function') {
  11629. cachedClearTimeout = clearTimeout;
  11630. } else {
  11631. cachedClearTimeout = defaultClearTimeout;
  11632. }
  11633. } catch (e) {
  11634. cachedClearTimeout = defaultClearTimeout;
  11635. }
  11636. } ())
  11637. function runTimeout(fun) {
  11638. if (cachedSetTimeout === setTimeout) {
  11639. //normal enviroments in sane situations
  11640. return setTimeout(fun, 0);
  11641. }
  11642. // if setTimeout wasn't available but was latter defined
  11643. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11644. cachedSetTimeout = setTimeout;
  11645. return setTimeout(fun, 0);
  11646. }
  11647. try {
  11648. // when when somebody has screwed with setTimeout but no I.E. maddness
  11649. return cachedSetTimeout(fun, 0);
  11650. } catch(e){
  11651. try {
  11652. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  11653. return cachedSetTimeout.call(null, fun, 0);
  11654. } catch(e){
  11655. // 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
  11656. return cachedSetTimeout.call(this, fun, 0);
  11657. }
  11658. }
  11659. }
  11660. function runClearTimeout(marker) {
  11661. if (cachedClearTimeout === clearTimeout) {
  11662. //normal enviroments in sane situations
  11663. return clearTimeout(marker);
  11664. }
  11665. // if clearTimeout wasn't available but was latter defined
  11666. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11667. cachedClearTimeout = clearTimeout;
  11668. return clearTimeout(marker);
  11669. }
  11670. try {
  11671. // when when somebody has screwed with setTimeout but no I.E. maddness
  11672. return cachedClearTimeout(marker);
  11673. } catch (e){
  11674. try {
  11675. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  11676. return cachedClearTimeout.call(null, marker);
  11677. } catch (e){
  11678. // 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.
  11679. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  11680. return cachedClearTimeout.call(this, marker);
  11681. }
  11682. }
  11683. }
  11684. var queue = [];
  11685. var draining = false;
  11686. var currentQueue;
  11687. var queueIndex = -1;
  11688. function cleanUpNextTick() {
  11689. if (!draining || !currentQueue) {
  11690. return;
  11691. }
  11692. draining = false;
  11693. if (currentQueue.length) {
  11694. queue = currentQueue.concat(queue);
  11695. } else {
  11696. queueIndex = -1;
  11697. }
  11698. if (queue.length) {
  11699. drainQueue();
  11700. }
  11701. }
  11702. function drainQueue() {
  11703. if (draining) {
  11704. return;
  11705. }
  11706. var timeout = runTimeout(cleanUpNextTick);
  11707. draining = true;
  11708. var len = queue.length;
  11709. while(len) {
  11710. currentQueue = queue;
  11711. queue = [];
  11712. while (++queueIndex < len) {
  11713. if (currentQueue) {
  11714. currentQueue[queueIndex].run();
  11715. }
  11716. }
  11717. queueIndex = -1;
  11718. len = queue.length;
  11719. }
  11720. currentQueue = null;
  11721. draining = false;
  11722. runClearTimeout(timeout);
  11723. }
  11724. process.nextTick = function (fun) {
  11725. var args = new Array(arguments.length - 1);
  11726. if (arguments.length > 1) {
  11727. for (var i = 1; i < arguments.length; i++) {
  11728. args[i - 1] = arguments[i];
  11729. }
  11730. }
  11731. queue.push(new Item(fun, args));
  11732. if (queue.length === 1 && !draining) {
  11733. runTimeout(drainQueue);
  11734. }
  11735. };
  11736. // v8 likes predictible objects
  11737. function Item(fun, array) {
  11738. this.fun = fun;
  11739. this.array = array;
  11740. }
  11741. Item.prototype.run = function () {
  11742. this.fun.apply(null, this.array);
  11743. };
  11744. process.title = 'browser';
  11745. process.browser = true;
  11746. process.env = {};
  11747. process.argv = [];
  11748. process.version = ''; // empty string to avoid regexp issues
  11749. process.versions = {};
  11750. function noop() {}
  11751. process.on = noop;
  11752. process.addListener = noop;
  11753. process.once = noop;
  11754. process.off = noop;
  11755. process.removeListener = noop;
  11756. process.removeAllListeners = noop;
  11757. process.emit = noop;
  11758. process.prependListener = noop;
  11759. process.prependOnceListener = noop;
  11760. process.listeners = function (name) { return [] }
  11761. process.binding = function (name) {
  11762. throw new Error('process.binding is not supported');
  11763. };
  11764. process.cwd = function () { return '/' };
  11765. process.chdir = function (dir) {
  11766. throw new Error('process.chdir is not supported');
  11767. };
  11768. process.umask = function() { return 0; };
  11769. },{}],51:[function(require,module,exports){
  11770. (function (global){(function (){
  11771. /*! https://mths.be/punycode v1.4.1 by @mathias */
  11772. ;(function(root) {
  11773. /** Detect free variables */
  11774. var freeExports = typeof exports == 'object' && exports &&
  11775. !exports.nodeType && exports;
  11776. var freeModule = typeof module == 'object' && module &&
  11777. !module.nodeType && module;
  11778. var freeGlobal = typeof global == 'object' && global;
  11779. if (
  11780. freeGlobal.global === freeGlobal ||
  11781. freeGlobal.window === freeGlobal ||
  11782. freeGlobal.self === freeGlobal
  11783. ) {
  11784. root = freeGlobal;
  11785. }
  11786. /**
  11787. * The `punycode` object.
  11788. * @name punycode
  11789. * @type Object
  11790. */
  11791. var punycode,
  11792. /** Highest positive signed 32-bit float value */
  11793. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  11794. /** Bootstring parameters */
  11795. base = 36,
  11796. tMin = 1,
  11797. tMax = 26,
  11798. skew = 38,
  11799. damp = 700,
  11800. initialBias = 72,
  11801. initialN = 128, // 0x80
  11802. delimiter = '-', // '\x2D'
  11803. /** Regular expressions */
  11804. regexPunycode = /^xn--/,
  11805. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  11806. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  11807. /** Error messages */
  11808. errors = {
  11809. 'overflow': 'Overflow: input needs wider integers to process',
  11810. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  11811. 'invalid-input': 'Invalid input'
  11812. },
  11813. /** Convenience shortcuts */
  11814. baseMinusTMin = base - tMin,
  11815. floor = Math.floor,
  11816. stringFromCharCode = String.fromCharCode,
  11817. /** Temporary variable */
  11818. key;
  11819. /*--------------------------------------------------------------------------*/
  11820. /**
  11821. * A generic error utility function.
  11822. * @private
  11823. * @param {String} type The error type.
  11824. * @returns {Error} Throws a `RangeError` with the applicable error message.
  11825. */
  11826. function error(type) {
  11827. throw new RangeError(errors[type]);
  11828. }
  11829. /**
  11830. * A generic `Array#map` utility function.
  11831. * @private
  11832. * @param {Array} array The array to iterate over.
  11833. * @param {Function} callback The function that gets called for every array
  11834. * item.
  11835. * @returns {Array} A new array of values returned by the callback function.
  11836. */
  11837. function map(array, fn) {
  11838. var length = array.length;
  11839. var result = [];
  11840. while (length--) {
  11841. result[length] = fn(array[length]);
  11842. }
  11843. return result;
  11844. }
  11845. /**
  11846. * A simple `Array#map`-like wrapper to work with domain name strings or email
  11847. * addresses.
  11848. * @private
  11849. * @param {String} domain The domain name or email address.
  11850. * @param {Function} callback The function that gets called for every
  11851. * character.
  11852. * @returns {Array} A new string of characters returned by the callback
  11853. * function.
  11854. */
  11855. function mapDomain(string, fn) {
  11856. var parts = string.split('@');
  11857. var result = '';
  11858. if (parts.length > 1) {
  11859. // In email addresses, only the domain name should be punycoded. Leave
  11860. // the local part (i.e. everything up to `@`) intact.
  11861. result = parts[0] + '@';
  11862. string = parts[1];
  11863. }
  11864. // Avoid `split(regex)` for IE8 compatibility. See #17.
  11865. string = string.replace(regexSeparators, '\x2E');
  11866. var labels = string.split('.');
  11867. var encoded = map(labels, fn).join('.');
  11868. return result + encoded;
  11869. }
  11870. /**
  11871. * Creates an array containing the numeric code points of each Unicode
  11872. * character in the string. While JavaScript uses UCS-2 internally,
  11873. * this function will convert a pair of surrogate halves (each of which
  11874. * UCS-2 exposes as separate characters) into a single code point,
  11875. * matching UTF-16.
  11876. * @see `punycode.ucs2.encode`
  11877. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  11878. * @memberOf punycode.ucs2
  11879. * @name decode
  11880. * @param {String} string The Unicode input string (UCS-2).
  11881. * @returns {Array} The new array of code points.
  11882. */
  11883. function ucs2decode(string) {
  11884. var output = [],
  11885. counter = 0,
  11886. length = string.length,
  11887. value,
  11888. extra;
  11889. while (counter < length) {
  11890. value = string.charCodeAt(counter++);
  11891. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11892. // high surrogate, and there is a next character
  11893. extra = string.charCodeAt(counter++);
  11894. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11895. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11896. } else {
  11897. // unmatched surrogate; only append this code unit, in case the next
  11898. // code unit is the high surrogate of a surrogate pair
  11899. output.push(value);
  11900. counter--;
  11901. }
  11902. } else {
  11903. output.push(value);
  11904. }
  11905. }
  11906. return output;
  11907. }
  11908. /**
  11909. * Creates a string based on an array of numeric code points.
  11910. * @see `punycode.ucs2.decode`
  11911. * @memberOf punycode.ucs2
  11912. * @name encode
  11913. * @param {Array} codePoints The array of numeric code points.
  11914. * @returns {String} The new Unicode string (UCS-2).
  11915. */
  11916. function ucs2encode(array) {
  11917. return map(array, function(value) {
  11918. var output = '';
  11919. if (value > 0xFFFF) {
  11920. value -= 0x10000;
  11921. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11922. value = 0xDC00 | value & 0x3FF;
  11923. }
  11924. output += stringFromCharCode(value);
  11925. return output;
  11926. }).join('');
  11927. }
  11928. /**
  11929. * Converts a basic code point into a digit/integer.
  11930. * @see `digitToBasic()`
  11931. * @private
  11932. * @param {Number} codePoint The basic numeric code point value.
  11933. * @returns {Number} The numeric value of a basic code point (for use in
  11934. * representing integers) in the range `0` to `base - 1`, or `base` if
  11935. * the code point does not represent a value.
  11936. */
  11937. function basicToDigit(codePoint) {
  11938. if (codePoint - 48 < 10) {
  11939. return codePoint - 22;
  11940. }
  11941. if (codePoint - 65 < 26) {
  11942. return codePoint - 65;
  11943. }
  11944. if (codePoint - 97 < 26) {
  11945. return codePoint - 97;
  11946. }
  11947. return base;
  11948. }
  11949. /**
  11950. * Converts a digit/integer into a basic code point.
  11951. * @see `basicToDigit()`
  11952. * @private
  11953. * @param {Number} digit The numeric value of a basic code point.
  11954. * @returns {Number} The basic code point whose value (when used for
  11955. * representing integers) is `digit`, which needs to be in the range
  11956. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  11957. * used; else, the lowercase form is used. The behavior is undefined
  11958. * if `flag` is non-zero and `digit` has no uppercase form.
  11959. */
  11960. function digitToBasic(digit, flag) {
  11961. // 0..25 map to ASCII a..z or A..Z
  11962. // 26..35 map to ASCII 0..9
  11963. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  11964. }
  11965. /**
  11966. * Bias adaptation function as per section 3.4 of RFC 3492.
  11967. * https://tools.ietf.org/html/rfc3492#section-3.4
  11968. * @private
  11969. */
  11970. function adapt(delta, numPoints, firstTime) {
  11971. var k = 0;
  11972. delta = firstTime ? floor(delta / damp) : delta >> 1;
  11973. delta += floor(delta / numPoints);
  11974. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  11975. delta = floor(delta / baseMinusTMin);
  11976. }
  11977. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  11978. }
  11979. /**
  11980. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  11981. * symbols.
  11982. * @memberOf punycode
  11983. * @param {String} input The Punycode string of ASCII-only symbols.
  11984. * @returns {String} The resulting string of Unicode symbols.
  11985. */
  11986. function decode(input) {
  11987. // Don't use UCS-2
  11988. var output = [],
  11989. inputLength = input.length,
  11990. out,
  11991. i = 0,
  11992. n = initialN,
  11993. bias = initialBias,
  11994. basic,
  11995. j,
  11996. index,
  11997. oldi,
  11998. w,
  11999. k,
  12000. digit,
  12001. t,
  12002. /** Cached calculation results */
  12003. baseMinusT;
  12004. // Handle the basic code points: let `basic` be the number of input code
  12005. // points before the last delimiter, or `0` if there is none, then copy
  12006. // the first basic code points to the output.
  12007. basic = input.lastIndexOf(delimiter);
  12008. if (basic < 0) {
  12009. basic = 0;
  12010. }
  12011. for (j = 0; j < basic; ++j) {
  12012. // if it's not a basic code point
  12013. if (input.charCodeAt(j) >= 0x80) {
  12014. error('not-basic');
  12015. }
  12016. output.push(input.charCodeAt(j));
  12017. }
  12018. // Main decoding loop: start just after the last delimiter if any basic code
  12019. // points were copied; start at the beginning otherwise.
  12020. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  12021. // `index` is the index of the next character to be consumed.
  12022. // Decode a generalized variable-length integer into `delta`,
  12023. // which gets added to `i`. The overflow checking is easier
  12024. // if we increase `i` as we go, then subtract off its starting
  12025. // value at the end to obtain `delta`.
  12026. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  12027. if (index >= inputLength) {
  12028. error('invalid-input');
  12029. }
  12030. digit = basicToDigit(input.charCodeAt(index++));
  12031. if (digit >= base || digit > floor((maxInt - i) / w)) {
  12032. error('overflow');
  12033. }
  12034. i += digit * w;
  12035. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  12036. if (digit < t) {
  12037. break;
  12038. }
  12039. baseMinusT = base - t;
  12040. if (w > floor(maxInt / baseMinusT)) {
  12041. error('overflow');
  12042. }
  12043. w *= baseMinusT;
  12044. }
  12045. out = output.length + 1;
  12046. bias = adapt(i - oldi, out, oldi == 0);
  12047. // `i` was supposed to wrap around from `out` to `0`,
  12048. // incrementing `n` each time, so we'll fix that now:
  12049. if (floor(i / out) > maxInt - n) {
  12050. error('overflow');
  12051. }
  12052. n += floor(i / out);
  12053. i %= out;
  12054. // Insert `n` at position `i` of the output
  12055. output.splice(i++, 0, n);
  12056. }
  12057. return ucs2encode(output);
  12058. }
  12059. /**
  12060. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  12061. * Punycode string of ASCII-only symbols.
  12062. * @memberOf punycode
  12063. * @param {String} input The string of Unicode symbols.
  12064. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  12065. */
  12066. function encode(input) {
  12067. var n,
  12068. delta,
  12069. handledCPCount,
  12070. basicLength,
  12071. bias,
  12072. j,
  12073. m,
  12074. q,
  12075. k,
  12076. t,
  12077. currentValue,
  12078. output = [],
  12079. /** `inputLength` will hold the number of code points in `input`. */
  12080. inputLength,
  12081. /** Cached calculation results */
  12082. handledCPCountPlusOne,
  12083. baseMinusT,
  12084. qMinusT;
  12085. // Convert the input in UCS-2 to Unicode
  12086. input = ucs2decode(input);
  12087. // Cache the length
  12088. inputLength = input.length;
  12089. // Initialize the state
  12090. n = initialN;
  12091. delta = 0;
  12092. bias = initialBias;
  12093. // Handle the basic code points
  12094. for (j = 0; j < inputLength; ++j) {
  12095. currentValue = input[j];
  12096. if (currentValue < 0x80) {
  12097. output.push(stringFromCharCode(currentValue));
  12098. }
  12099. }
  12100. handledCPCount = basicLength = output.length;
  12101. // `handledCPCount` is the number of code points that have been handled;
  12102. // `basicLength` is the number of basic code points.
  12103. // Finish the basic string - if it is not empty - with a delimiter
  12104. if (basicLength) {
  12105. output.push(delimiter);
  12106. }
  12107. // Main encoding loop:
  12108. while (handledCPCount < inputLength) {
  12109. // All non-basic code points < n have been handled already. Find the next
  12110. // larger one:
  12111. for (m = maxInt, j = 0; j < inputLength; ++j) {
  12112. currentValue = input[j];
  12113. if (currentValue >= n && currentValue < m) {
  12114. m = currentValue;
  12115. }
  12116. }
  12117. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  12118. // but guard against overflow
  12119. handledCPCountPlusOne = handledCPCount + 1;
  12120. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  12121. error('overflow');
  12122. }
  12123. delta += (m - n) * handledCPCountPlusOne;
  12124. n = m;
  12125. for (j = 0; j < inputLength; ++j) {
  12126. currentValue = input[j];
  12127. if (currentValue < n && ++delta > maxInt) {
  12128. error('overflow');
  12129. }
  12130. if (currentValue == n) {
  12131. // Represent delta as a generalized variable-length integer
  12132. for (q = delta, k = base; /* no condition */; k += base) {
  12133. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  12134. if (q < t) {
  12135. break;
  12136. }
  12137. qMinusT = q - t;
  12138. baseMinusT = base - t;
  12139. output.push(
  12140. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  12141. );
  12142. q = floor(qMinusT / baseMinusT);
  12143. }
  12144. output.push(stringFromCharCode(digitToBasic(q, 0)));
  12145. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  12146. delta = 0;
  12147. ++handledCPCount;
  12148. }
  12149. }
  12150. ++delta;
  12151. ++n;
  12152. }
  12153. return output.join('');
  12154. }
  12155. /**
  12156. * Converts a Punycode string representing a domain name or an email address
  12157. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  12158. * it doesn't matter if you call it on a string that has already been
  12159. * converted to Unicode.
  12160. * @memberOf punycode
  12161. * @param {String} input The Punycoded domain name or email address to
  12162. * convert to Unicode.
  12163. * @returns {String} The Unicode representation of the given Punycode
  12164. * string.
  12165. */
  12166. function toUnicode(input) {
  12167. return mapDomain(input, function(string) {
  12168. return regexPunycode.test(string)
  12169. ? decode(string.slice(4).toLowerCase())
  12170. : string;
  12171. });
  12172. }
  12173. /**
  12174. * Converts a Unicode string representing a domain name or an email address to
  12175. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  12176. * i.e. it doesn't matter if you call it with a domain that's already in
  12177. * ASCII.
  12178. * @memberOf punycode
  12179. * @param {String} input The domain name or email address to convert, as a
  12180. * Unicode string.
  12181. * @returns {String} The Punycode representation of the given domain name or
  12182. * email address.
  12183. */
  12184. function toASCII(input) {
  12185. return mapDomain(input, function(string) {
  12186. return regexNonASCII.test(string)
  12187. ? 'xn--' + encode(string)
  12188. : string;
  12189. });
  12190. }
  12191. /*--------------------------------------------------------------------------*/
  12192. /** Define the public API */
  12193. punycode = {
  12194. /**
  12195. * A string representing the current Punycode.js version number.
  12196. * @memberOf punycode
  12197. * @type String
  12198. */
  12199. 'version': '1.4.1',
  12200. /**
  12201. * An object of methods to convert from JavaScript's internal character
  12202. * representation (UCS-2) to Unicode code points, and back.
  12203. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  12204. * @memberOf punycode
  12205. * @type Object
  12206. */
  12207. 'ucs2': {
  12208. 'decode': ucs2decode,
  12209. 'encode': ucs2encode
  12210. },
  12211. 'decode': decode,
  12212. 'encode': encode,
  12213. 'toASCII': toASCII,
  12214. 'toUnicode': toUnicode
  12215. };
  12216. /** Expose `punycode` */
  12217. // Some AMD build optimizers, like r.js, check for specific condition patterns
  12218. // like the following:
  12219. if (
  12220. typeof define == 'function' &&
  12221. typeof define.amd == 'object' &&
  12222. define.amd
  12223. ) {
  12224. define('punycode', function() {
  12225. return punycode;
  12226. });
  12227. } else if (freeExports && freeModule) {
  12228. if (module.exports == freeExports) {
  12229. // in Node.js, io.js, or RingoJS v0.8.0+
  12230. freeModule.exports = punycode;
  12231. } else {
  12232. // in Narwhal or RingoJS v0.7.0-
  12233. for (key in punycode) {
  12234. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  12235. }
  12236. }
  12237. } else {
  12238. // in Rhino or a web browser
  12239. root.punycode = punycode;
  12240. }
  12241. }(this));
  12242. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12243. },{}],52:[function(require,module,exports){
  12244. // Copyright Joyent, Inc. and other Node contributors.
  12245. //
  12246. // Permission is hereby granted, free of charge, to any person obtaining a
  12247. // copy of this software and associated documentation files (the
  12248. // "Software"), to deal in the Software without restriction, including
  12249. // without limitation the rights to use, copy, modify, merge, publish,
  12250. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12251. // persons to whom the Software is furnished to do so, subject to the
  12252. // following conditions:
  12253. //
  12254. // The above copyright notice and this permission notice shall be included
  12255. // in all copies or substantial portions of the Software.
  12256. //
  12257. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12258. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12259. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12260. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12261. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12262. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12263. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12264. 'use strict';
  12265. // If obj.hasOwnProperty has been overridden, then calling
  12266. // obj.hasOwnProperty(prop) will break.
  12267. // See: https://github.com/joyent/node/issues/1707
  12268. function hasOwnProperty(obj, prop) {
  12269. return Object.prototype.hasOwnProperty.call(obj, prop);
  12270. }
  12271. module.exports = function(qs, sep, eq, options) {
  12272. sep = sep || '&';
  12273. eq = eq || '=';
  12274. var obj = {};
  12275. if (typeof qs !== 'string' || qs.length === 0) {
  12276. return obj;
  12277. }
  12278. var regexp = /\+/g;
  12279. qs = qs.split(sep);
  12280. var maxKeys = 1000;
  12281. if (options && typeof options.maxKeys === 'number') {
  12282. maxKeys = options.maxKeys;
  12283. }
  12284. var len = qs.length;
  12285. // maxKeys <= 0 means that we should not limit keys count
  12286. if (maxKeys > 0 && len > maxKeys) {
  12287. len = maxKeys;
  12288. }
  12289. for (var i = 0; i < len; ++i) {
  12290. var x = qs[i].replace(regexp, '%20'),
  12291. idx = x.indexOf(eq),
  12292. kstr, vstr, k, v;
  12293. if (idx >= 0) {
  12294. kstr = x.substr(0, idx);
  12295. vstr = x.substr(idx + 1);
  12296. } else {
  12297. kstr = x;
  12298. vstr = '';
  12299. }
  12300. k = decodeURIComponent(kstr);
  12301. v = decodeURIComponent(vstr);
  12302. if (!hasOwnProperty(obj, k)) {
  12303. obj[k] = v;
  12304. } else if (isArray(obj[k])) {
  12305. obj[k].push(v);
  12306. } else {
  12307. obj[k] = [obj[k], v];
  12308. }
  12309. }
  12310. return obj;
  12311. };
  12312. var isArray = Array.isArray || function (xs) {
  12313. return Object.prototype.toString.call(xs) === '[object Array]';
  12314. };
  12315. },{}],53:[function(require,module,exports){
  12316. // Copyright Joyent, Inc. and other Node contributors.
  12317. //
  12318. // Permission is hereby granted, free of charge, to any person obtaining a
  12319. // copy of this software and associated documentation files (the
  12320. // "Software"), to deal in the Software without restriction, including
  12321. // without limitation the rights to use, copy, modify, merge, publish,
  12322. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12323. // persons to whom the Software is furnished to do so, subject to the
  12324. // following conditions:
  12325. //
  12326. // The above copyright notice and this permission notice shall be included
  12327. // in all copies or substantial portions of the Software.
  12328. //
  12329. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12330. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12331. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12332. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12333. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12334. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12335. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12336. 'use strict';
  12337. var stringifyPrimitive = function(v) {
  12338. switch (typeof v) {
  12339. case 'string':
  12340. return v;
  12341. case 'boolean':
  12342. return v ? 'true' : 'false';
  12343. case 'number':
  12344. return isFinite(v) ? v : '';
  12345. default:
  12346. return '';
  12347. }
  12348. };
  12349. module.exports = function(obj, sep, eq, name) {
  12350. sep = sep || '&';
  12351. eq = eq || '=';
  12352. if (obj === null) {
  12353. obj = undefined;
  12354. }
  12355. if (typeof obj === 'object') {
  12356. return map(objectKeys(obj), function(k) {
  12357. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  12358. if (isArray(obj[k])) {
  12359. return map(obj[k], function(v) {
  12360. return ks + encodeURIComponent(stringifyPrimitive(v));
  12361. }).join(sep);
  12362. } else {
  12363. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  12364. }
  12365. }).join(sep);
  12366. }
  12367. if (!name) return '';
  12368. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  12369. encodeURIComponent(stringifyPrimitive(obj));
  12370. };
  12371. var isArray = Array.isArray || function (xs) {
  12372. return Object.prototype.toString.call(xs) === '[object Array]';
  12373. };
  12374. function map (xs, f) {
  12375. if (xs.map) return xs.map(f);
  12376. var res = [];
  12377. for (var i = 0; i < xs.length; i++) {
  12378. res.push(f(xs[i], i));
  12379. }
  12380. return res;
  12381. }
  12382. var objectKeys = Object.keys || function (obj) {
  12383. var res = [];
  12384. for (var key in obj) {
  12385. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  12386. }
  12387. return res;
  12388. };
  12389. },{}],54:[function(require,module,exports){
  12390. 'use strict';
  12391. exports.decode = exports.parse = require('./decode');
  12392. exports.encode = exports.stringify = require('./encode');
  12393. },{"./decode":52,"./encode":53}],55:[function(require,module,exports){
  12394. 'use strict';
  12395. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  12396. var codes = {};
  12397. function createErrorType(code, message, Base) {
  12398. if (!Base) {
  12399. Base = Error;
  12400. }
  12401. function getMessage(arg1, arg2, arg3) {
  12402. if (typeof message === 'string') {
  12403. return message;
  12404. } else {
  12405. return message(arg1, arg2, arg3);
  12406. }
  12407. }
  12408. var NodeError =
  12409. /*#__PURE__*/
  12410. function (_Base) {
  12411. _inheritsLoose(NodeError, _Base);
  12412. function NodeError(arg1, arg2, arg3) {
  12413. return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
  12414. }
  12415. return NodeError;
  12416. }(Base);
  12417. NodeError.prototype.name = Base.name;
  12418. NodeError.prototype.code = code;
  12419. codes[code] = NodeError;
  12420. } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  12421. function oneOf(expected, thing) {
  12422. if (Array.isArray(expected)) {
  12423. var len = expected.length;
  12424. expected = expected.map(function (i) {
  12425. return String(i);
  12426. });
  12427. if (len > 2) {
  12428. return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
  12429. } else if (len === 2) {
  12430. return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
  12431. } else {
  12432. return "of ".concat(thing, " ").concat(expected[0]);
  12433. }
  12434. } else {
  12435. return "of ".concat(thing, " ").concat(String(expected));
  12436. }
  12437. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  12438. function startsWith(str, search, pos) {
  12439. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  12440. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  12441. function endsWith(str, search, this_len) {
  12442. if (this_len === undefined || this_len > str.length) {
  12443. this_len = str.length;
  12444. }
  12445. return str.substring(this_len - search.length, this_len) === search;
  12446. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  12447. function includes(str, search, start) {
  12448. if (typeof start !== 'number') {
  12449. start = 0;
  12450. }
  12451. if (start + search.length > str.length) {
  12452. return false;
  12453. } else {
  12454. return str.indexOf(search, start) !== -1;
  12455. }
  12456. }
  12457. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  12458. return 'The value "' + value + '" is invalid for option "' + name + '"';
  12459. }, TypeError);
  12460. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  12461. // determiner: 'must be' or 'must not be'
  12462. var determiner;
  12463. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  12464. determiner = 'must not be';
  12465. expected = expected.replace(/^not /, '');
  12466. } else {
  12467. determiner = 'must be';
  12468. }
  12469. var msg;
  12470. if (endsWith(name, ' argument')) {
  12471. // For cases like 'first argument'
  12472. msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  12473. } else {
  12474. var type = includes(name, '.') ? 'property' : 'argument';
  12475. msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  12476. }
  12477. msg += ". Received type ".concat(typeof actual);
  12478. return msg;
  12479. }, TypeError);
  12480. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  12481. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  12482. return 'The ' + name + ' method is not implemented';
  12483. });
  12484. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  12485. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  12486. return 'Cannot call ' + name + ' after a stream was destroyed';
  12487. });
  12488. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  12489. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  12490. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  12491. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  12492. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  12493. return 'Unknown encoding: ' + arg;
  12494. }, TypeError);
  12495. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  12496. module.exports.codes = codes;
  12497. },{}],56:[function(require,module,exports){
  12498. (function (process){(function (){
  12499. // Copyright Joyent, Inc. and other Node contributors.
  12500. //
  12501. // Permission is hereby granted, free of charge, to any person obtaining a
  12502. // copy of this software and associated documentation files (the
  12503. // "Software"), to deal in the Software without restriction, including
  12504. // without limitation the rights to use, copy, modify, merge, publish,
  12505. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12506. // persons to whom the Software is furnished to do so, subject to the
  12507. // following conditions:
  12508. //
  12509. // The above copyright notice and this permission notice shall be included
  12510. // in all copies or substantial portions of the Software.
  12511. //
  12512. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12513. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12514. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12515. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12516. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12517. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12518. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12519. // a duplex stream is just a stream that is both readable and writable.
  12520. // Since JS doesn't have multiple prototypal inheritance, this class
  12521. // prototypally inherits from Readable, and then parasitically from
  12522. // Writable.
  12523. 'use strict';
  12524. /*<replacement>*/
  12525. var objectKeys = Object.keys || function (obj) {
  12526. var keys = [];
  12527. for (var key in obj) {
  12528. keys.push(key);
  12529. }
  12530. return keys;
  12531. };
  12532. /*</replacement>*/
  12533. module.exports = Duplex;
  12534. var Readable = require('./_stream_readable');
  12535. var Writable = require('./_stream_writable');
  12536. require('inherits')(Duplex, Readable);
  12537. {
  12538. // Allow the keys array to be GC'ed.
  12539. var keys = objectKeys(Writable.prototype);
  12540. for (var v = 0; v < keys.length; v++) {
  12541. var method = keys[v];
  12542. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  12543. }
  12544. }
  12545. function Duplex(options) {
  12546. if (!(this instanceof Duplex)) return new Duplex(options);
  12547. Readable.call(this, options);
  12548. Writable.call(this, options);
  12549. this.allowHalfOpen = true;
  12550. if (options) {
  12551. if (options.readable === false) this.readable = false;
  12552. if (options.writable === false) this.writable = false;
  12553. if (options.allowHalfOpen === false) {
  12554. this.allowHalfOpen = false;
  12555. this.once('end', onend);
  12556. }
  12557. }
  12558. }
  12559. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  12560. // making it explicit this property is not enumerable
  12561. // because otherwise some prototype manipulation in
  12562. // userland will fail
  12563. enumerable: false,
  12564. get: function get() {
  12565. return this._writableState.highWaterMark;
  12566. }
  12567. });
  12568. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  12569. // making it explicit this property is not enumerable
  12570. // because otherwise some prototype manipulation in
  12571. // userland will fail
  12572. enumerable: false,
  12573. get: function get() {
  12574. return this._writableState && this._writableState.getBuffer();
  12575. }
  12576. });
  12577. Object.defineProperty(Duplex.prototype, 'writableLength', {
  12578. // making it explicit this property is not enumerable
  12579. // because otherwise some prototype manipulation in
  12580. // userland will fail
  12581. enumerable: false,
  12582. get: function get() {
  12583. return this._writableState.length;
  12584. }
  12585. }); // the no-half-open enforcer
  12586. function onend() {
  12587. // If the writable side ended, then we're ok.
  12588. if (this._writableState.ended) return; // no more data can be written.
  12589. // But allow more writes to happen in this tick.
  12590. process.nextTick(onEndNT, this);
  12591. }
  12592. function onEndNT(self) {
  12593. self.end();
  12594. }
  12595. Object.defineProperty(Duplex.prototype, 'destroyed', {
  12596. // making it explicit this property is not enumerable
  12597. // because otherwise some prototype manipulation in
  12598. // userland will fail
  12599. enumerable: false,
  12600. get: function get() {
  12601. if (this._readableState === undefined || this._writableState === undefined) {
  12602. return false;
  12603. }
  12604. return this._readableState.destroyed && this._writableState.destroyed;
  12605. },
  12606. set: function set(value) {
  12607. // we ignore the value if the stream
  12608. // has not been initialized yet
  12609. if (this._readableState === undefined || this._writableState === undefined) {
  12610. return;
  12611. } // backward compatibility, the user is explicitly
  12612. // managing destroyed
  12613. this._readableState.destroyed = value;
  12614. this._writableState.destroyed = value;
  12615. }
  12616. });
  12617. }).call(this)}).call(this,require('_process'))
  12618. },{"./_stream_readable":58,"./_stream_writable":60,"_process":50,"inherits":24}],57:[function(require,module,exports){
  12619. // Copyright Joyent, Inc. and other Node contributors.
  12620. //
  12621. // Permission is hereby granted, free of charge, to any person obtaining a
  12622. // copy of this software and associated documentation files (the
  12623. // "Software"), to deal in the Software without restriction, including
  12624. // without limitation the rights to use, copy, modify, merge, publish,
  12625. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12626. // persons to whom the Software is furnished to do so, subject to the
  12627. // following conditions:
  12628. //
  12629. // The above copyright notice and this permission notice shall be included
  12630. // in all copies or substantial portions of the Software.
  12631. //
  12632. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12633. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12634. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12635. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12636. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12637. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12638. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12639. // a passthrough stream.
  12640. // basically just the most minimal sort of Transform stream.
  12641. // Every written chunk gets output as-is.
  12642. 'use strict';
  12643. module.exports = PassThrough;
  12644. var Transform = require('./_stream_transform');
  12645. require('inherits')(PassThrough, Transform);
  12646. function PassThrough(options) {
  12647. if (!(this instanceof PassThrough)) return new PassThrough(options);
  12648. Transform.call(this, options);
  12649. }
  12650. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  12651. cb(null, chunk);
  12652. };
  12653. },{"./_stream_transform":59,"inherits":24}],58:[function(require,module,exports){
  12654. (function (process,global){(function (){
  12655. // Copyright Joyent, Inc. and other Node contributors.
  12656. //
  12657. // Permission is hereby granted, free of charge, to any person obtaining a
  12658. // copy of this software and associated documentation files (the
  12659. // "Software"), to deal in the Software without restriction, including
  12660. // without limitation the rights to use, copy, modify, merge, publish,
  12661. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12662. // persons to whom the Software is furnished to do so, subject to the
  12663. // following conditions:
  12664. //
  12665. // The above copyright notice and this permission notice shall be included
  12666. // in all copies or substantial portions of the Software.
  12667. //
  12668. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12669. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12670. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12671. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12672. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12673. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12674. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12675. 'use strict';
  12676. module.exports = Readable;
  12677. /*<replacement>*/
  12678. var Duplex;
  12679. /*</replacement>*/
  12680. Readable.ReadableState = ReadableState;
  12681. /*<replacement>*/
  12682. var EE = require('events').EventEmitter;
  12683. var EElistenerCount = function EElistenerCount(emitter, type) {
  12684. return emitter.listeners(type).length;
  12685. };
  12686. /*</replacement>*/
  12687. /*<replacement>*/
  12688. var Stream = require('./internal/streams/stream');
  12689. /*</replacement>*/
  12690. var Buffer = require('buffer').Buffer;
  12691. var OurUint8Array = global.Uint8Array || function () {};
  12692. function _uint8ArrayToBuffer(chunk) {
  12693. return Buffer.from(chunk);
  12694. }
  12695. function _isUint8Array(obj) {
  12696. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  12697. }
  12698. /*<replacement>*/
  12699. var debugUtil = require('util');
  12700. var debug;
  12701. if (debugUtil && debugUtil.debuglog) {
  12702. debug = debugUtil.debuglog('stream');
  12703. } else {
  12704. debug = function debug() {};
  12705. }
  12706. /*</replacement>*/
  12707. var BufferList = require('./internal/streams/buffer_list');
  12708. var destroyImpl = require('./internal/streams/destroy');
  12709. var _require = require('./internal/streams/state'),
  12710. getHighWaterMark = _require.getHighWaterMark;
  12711. var _require$codes = require('../errors').codes,
  12712. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  12713. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  12714. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  12715. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
  12716. var StringDecoder;
  12717. var createReadableStreamAsyncIterator;
  12718. var from;
  12719. require('inherits')(Readable, Stream);
  12720. var errorOrDestroy = destroyImpl.errorOrDestroy;
  12721. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  12722. function prependListener(emitter, event, fn) {
  12723. // Sadly this is not cacheable as some libraries bundle their own
  12724. // event emitter implementation with them.
  12725. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
  12726. // userland ones. NEVER DO THIS. This is here only because this code needs
  12727. // to continue to work with older versions of Node.js that do not include
  12728. // the prependListener() method. The goal is to eventually remove this hack.
  12729. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  12730. }
  12731. function ReadableState(options, stream, isDuplex) {
  12732. Duplex = Duplex || require('./_stream_duplex');
  12733. options = options || {}; // Duplex streams are both readable and writable, but share
  12734. // the same options object.
  12735. // However, some cases require setting options to different
  12736. // values for the readable and the writable sides of the duplex stream.
  12737. // These options can be provided separately as readableXXX and writableXXX.
  12738. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
  12739. // make all the buffer merging and length checks go away
  12740. this.objectMode = !!options.objectMode;
  12741. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
  12742. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  12743. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
  12744. // linked list can remove elements from the beginning faster than
  12745. // array.shift()
  12746. this.buffer = new BufferList();
  12747. this.length = 0;
  12748. this.pipes = null;
  12749. this.pipesCount = 0;
  12750. this.flowing = null;
  12751. this.ended = false;
  12752. this.endEmitted = false;
  12753. this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
  12754. // immediately, or on a later tick. We set this to true at first, because
  12755. // any actions that shouldn't happen until "later" should generally also
  12756. // not happen before the first read call.
  12757. this.sync = true; // whenever we return null, then we set a flag to say
  12758. // that we're awaiting a 'readable' event emission.
  12759. this.needReadable = false;
  12760. this.emittedReadable = false;
  12761. this.readableListening = false;
  12762. this.resumeScheduled = false;
  12763. this.paused = true; // Should close be emitted on destroy. Defaults to true.
  12764. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
  12765. this.autoDestroy = !!options.autoDestroy; // has it been destroyed
  12766. this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
  12767. // encoding is 'binary' so we have to make this configurable.
  12768. // Everything else in the universe uses 'utf8', though.
  12769. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
  12770. this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
  12771. this.readingMore = false;
  12772. this.decoder = null;
  12773. this.encoding = null;
  12774. if (options.encoding) {
  12775. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12776. this.decoder = new StringDecoder(options.encoding);
  12777. this.encoding = options.encoding;
  12778. }
  12779. }
  12780. function Readable(options) {
  12781. Duplex = Duplex || require('./_stream_duplex');
  12782. if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
  12783. // the ReadableState constructor, at least with V8 6.5
  12784. var isDuplex = this instanceof Duplex;
  12785. this._readableState = new ReadableState(options, this, isDuplex); // legacy
  12786. this.readable = true;
  12787. if (options) {
  12788. if (typeof options.read === 'function') this._read = options.read;
  12789. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  12790. }
  12791. Stream.call(this);
  12792. }
  12793. Object.defineProperty(Readable.prototype, 'destroyed', {
  12794. // making it explicit this property is not enumerable
  12795. // because otherwise some prototype manipulation in
  12796. // userland will fail
  12797. enumerable: false,
  12798. get: function get() {
  12799. if (this._readableState === undefined) {
  12800. return false;
  12801. }
  12802. return this._readableState.destroyed;
  12803. },
  12804. set: function set(value) {
  12805. // we ignore the value if the stream
  12806. // has not been initialized yet
  12807. if (!this._readableState) {
  12808. return;
  12809. } // backward compatibility, the user is explicitly
  12810. // managing destroyed
  12811. this._readableState.destroyed = value;
  12812. }
  12813. });
  12814. Readable.prototype.destroy = destroyImpl.destroy;
  12815. Readable.prototype._undestroy = destroyImpl.undestroy;
  12816. Readable.prototype._destroy = function (err, cb) {
  12817. cb(err);
  12818. }; // Manually shove something into the read() buffer.
  12819. // This returns true if the highWaterMark has not been hit yet,
  12820. // similar to how Writable.write() returns true if you should
  12821. // write() some more.
  12822. Readable.prototype.push = function (chunk, encoding) {
  12823. var state = this._readableState;
  12824. var skipChunkCheck;
  12825. if (!state.objectMode) {
  12826. if (typeof chunk === 'string') {
  12827. encoding = encoding || state.defaultEncoding;
  12828. if (encoding !== state.encoding) {
  12829. chunk = Buffer.from(chunk, encoding);
  12830. encoding = '';
  12831. }
  12832. skipChunkCheck = true;
  12833. }
  12834. } else {
  12835. skipChunkCheck = true;
  12836. }
  12837. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  12838. }; // Unshift should *always* be something directly out of read()
  12839. Readable.prototype.unshift = function (chunk) {
  12840. return readableAddChunk(this, chunk, null, true, false);
  12841. };
  12842. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  12843. debug('readableAddChunk', chunk);
  12844. var state = stream._readableState;
  12845. if (chunk === null) {
  12846. state.reading = false;
  12847. onEofChunk(stream, state);
  12848. } else {
  12849. var er;
  12850. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  12851. if (er) {
  12852. errorOrDestroy(stream, er);
  12853. } else if (state.objectMode || chunk && chunk.length > 0) {
  12854. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  12855. chunk = _uint8ArrayToBuffer(chunk);
  12856. }
  12857. if (addToFront) {
  12858. if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  12859. } else if (state.ended) {
  12860. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  12861. } else if (state.destroyed) {
  12862. return false;
  12863. } else {
  12864. state.reading = false;
  12865. if (state.decoder && !encoding) {
  12866. chunk = state.decoder.write(chunk);
  12867. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  12868. } else {
  12869. addChunk(stream, state, chunk, false);
  12870. }
  12871. }
  12872. } else if (!addToFront) {
  12873. state.reading = false;
  12874. maybeReadMore(stream, state);
  12875. }
  12876. } // We can push more data if we are below the highWaterMark.
  12877. // Also, if we have no data yet, we can stand some more bytes.
  12878. // This is to work around cases where hwm=0, such as the repl.
  12879. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  12880. }
  12881. function addChunk(stream, state, chunk, addToFront) {
  12882. if (state.flowing && state.length === 0 && !state.sync) {
  12883. state.awaitDrain = 0;
  12884. stream.emit('data', chunk);
  12885. } else {
  12886. // update the buffer info.
  12887. state.length += state.objectMode ? 1 : chunk.length;
  12888. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  12889. if (state.needReadable) emitReadable(stream);
  12890. }
  12891. maybeReadMore(stream, state);
  12892. }
  12893. function chunkInvalid(state, chunk) {
  12894. var er;
  12895. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  12896. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  12897. }
  12898. return er;
  12899. }
  12900. Readable.prototype.isPaused = function () {
  12901. return this._readableState.flowing === false;
  12902. }; // backwards compatibility.
  12903. Readable.prototype.setEncoding = function (enc) {
  12904. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12905. var decoder = new StringDecoder(enc);
  12906. this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
  12907. this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
  12908. var p = this._readableState.buffer.head;
  12909. var content = '';
  12910. while (p !== null) {
  12911. content += decoder.write(p.data);
  12912. p = p.next;
  12913. }
  12914. this._readableState.buffer.clear();
  12915. if (content !== '') this._readableState.buffer.push(content);
  12916. this._readableState.length = content.length;
  12917. return this;
  12918. }; // Don't raise the hwm > 1GB
  12919. var MAX_HWM = 0x40000000;
  12920. function computeNewHighWaterMark(n) {
  12921. if (n >= MAX_HWM) {
  12922. // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
  12923. n = MAX_HWM;
  12924. } else {
  12925. // Get the next highest power of 2 to prevent increasing hwm excessively in
  12926. // tiny amounts
  12927. n--;
  12928. n |= n >>> 1;
  12929. n |= n >>> 2;
  12930. n |= n >>> 4;
  12931. n |= n >>> 8;
  12932. n |= n >>> 16;
  12933. n++;
  12934. }
  12935. return n;
  12936. } // This function is designed to be inlinable, so please take care when making
  12937. // changes to the function body.
  12938. function howMuchToRead(n, state) {
  12939. if (n <= 0 || state.length === 0 && state.ended) return 0;
  12940. if (state.objectMode) return 1;
  12941. if (n !== n) {
  12942. // Only flow one buffer at a time
  12943. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  12944. } // If we're asking for more than the current hwm, then raise the hwm.
  12945. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  12946. if (n <= state.length) return n; // Don't have enough
  12947. if (!state.ended) {
  12948. state.needReadable = true;
  12949. return 0;
  12950. }
  12951. return state.length;
  12952. } // you can override either this method, or the async _read(n) below.
  12953. Readable.prototype.read = function (n) {
  12954. debug('read', n);
  12955. n = parseInt(n, 10);
  12956. var state = this._readableState;
  12957. var nOrig = n;
  12958. if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
  12959. // already have a bunch of data in the buffer, then just trigger
  12960. // the 'readable' event and move on.
  12961. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  12962. debug('read: emitReadable', state.length, state.ended);
  12963. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  12964. return null;
  12965. }
  12966. n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
  12967. if (n === 0 && state.ended) {
  12968. if (state.length === 0) endReadable(this);
  12969. return null;
  12970. } // All the actual chunk generation logic needs to be
  12971. // *below* the call to _read. The reason is that in certain
  12972. // synthetic stream cases, such as passthrough streams, _read
  12973. // may be a completely synchronous operation which may change
  12974. // the state of the read buffer, providing enough data when
  12975. // before there was *not* enough.
  12976. //
  12977. // So, the steps are:
  12978. // 1. Figure out what the state of things will be after we do
  12979. // a read from the buffer.
  12980. //
  12981. // 2. If that resulting state will trigger a _read, then call _read.
  12982. // Note that this may be asynchronous, or synchronous. Yes, it is
  12983. // deeply ugly to write APIs this way, but that still doesn't mean
  12984. // that the Readable class should behave improperly, as streams are
  12985. // designed to be sync/async agnostic.
  12986. // Take note if the _read call is sync or async (ie, if the read call
  12987. // has returned yet), so that we know whether or not it's safe to emit
  12988. // 'readable' etc.
  12989. //
  12990. // 3. Actually pull the requested chunks out of the buffer and return.
  12991. // if we need a readable event, then we need to do some reading.
  12992. var doRead = state.needReadable;
  12993. debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
  12994. if (state.length === 0 || state.length - n < state.highWaterMark) {
  12995. doRead = true;
  12996. debug('length less than watermark', doRead);
  12997. } // however, if we've ended, then there's no point, and if we're already
  12998. // reading, then it's unnecessary.
  12999. if (state.ended || state.reading) {
  13000. doRead = false;
  13001. debug('reading or ended', doRead);
  13002. } else if (doRead) {
  13003. debug('do read');
  13004. state.reading = true;
  13005. state.sync = true; // if the length is currently zero, then we *need* a readable event.
  13006. if (state.length === 0) state.needReadable = true; // call internal read method
  13007. this._read(state.highWaterMark);
  13008. state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
  13009. // and we need to re-evaluate how much data we can return to the user.
  13010. if (!state.reading) n = howMuchToRead(nOrig, state);
  13011. }
  13012. var ret;
  13013. if (n > 0) ret = fromList(n, state);else ret = null;
  13014. if (ret === null) {
  13015. state.needReadable = state.length <= state.highWaterMark;
  13016. n = 0;
  13017. } else {
  13018. state.length -= n;
  13019. state.awaitDrain = 0;
  13020. }
  13021. if (state.length === 0) {
  13022. // If we have nothing in the buffer, then we want to know
  13023. // as soon as we *do* get something into the buffer.
  13024. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
  13025. if (nOrig !== n && state.ended) endReadable(this);
  13026. }
  13027. if (ret !== null) this.emit('data', ret);
  13028. return ret;
  13029. };
  13030. function onEofChunk(stream, state) {
  13031. debug('onEofChunk');
  13032. if (state.ended) return;
  13033. if (state.decoder) {
  13034. var chunk = state.decoder.end();
  13035. if (chunk && chunk.length) {
  13036. state.buffer.push(chunk);
  13037. state.length += state.objectMode ? 1 : chunk.length;
  13038. }
  13039. }
  13040. state.ended = true;
  13041. if (state.sync) {
  13042. // if we are sync, wait until next tick to emit the data.
  13043. // Otherwise we risk emitting data in the flow()
  13044. // the readable code triggers during a read() call
  13045. emitReadable(stream);
  13046. } else {
  13047. // emit 'readable' now to make sure it gets picked up.
  13048. state.needReadable = false;
  13049. if (!state.emittedReadable) {
  13050. state.emittedReadable = true;
  13051. emitReadable_(stream);
  13052. }
  13053. }
  13054. } // Don't emit readable right away in sync mode, because this can trigger
  13055. // another read() call => stack overflow. This way, it might trigger
  13056. // a nextTick recursion warning, but that's not so bad.
  13057. function emitReadable(stream) {
  13058. var state = stream._readableState;
  13059. debug('emitReadable', state.needReadable, state.emittedReadable);
  13060. state.needReadable = false;
  13061. if (!state.emittedReadable) {
  13062. debug('emitReadable', state.flowing);
  13063. state.emittedReadable = true;
  13064. process.nextTick(emitReadable_, stream);
  13065. }
  13066. }
  13067. function emitReadable_(stream) {
  13068. var state = stream._readableState;
  13069. debug('emitReadable_', state.destroyed, state.length, state.ended);
  13070. if (!state.destroyed && (state.length || state.ended)) {
  13071. stream.emit('readable');
  13072. state.emittedReadable = false;
  13073. } // The stream needs another readable event if
  13074. // 1. It is not flowing, as the flow mechanism will take
  13075. // care of it.
  13076. // 2. It is not ended.
  13077. // 3. It is below the highWaterMark, so we can schedule
  13078. // another readable later.
  13079. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  13080. flow(stream);
  13081. } // at this point, the user has presumably seen the 'readable' event,
  13082. // and called read() to consume some data. that may have triggered
  13083. // in turn another _read(n) call, in which case reading = true if
  13084. // it's in progress.
  13085. // However, if we're not ended, or reading, and the length < hwm,
  13086. // then go ahead and try to read some more preemptively.
  13087. function maybeReadMore(stream, state) {
  13088. if (!state.readingMore) {
  13089. state.readingMore = true;
  13090. process.nextTick(maybeReadMore_, stream, state);
  13091. }
  13092. }
  13093. function maybeReadMore_(stream, state) {
  13094. // Attempt to read more data if we should.
  13095. //
  13096. // The conditions for reading more data are (one of):
  13097. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  13098. // is responsible for filling the buffer with enough data if such data
  13099. // is available. If highWaterMark is 0 and we are not in the flowing mode
  13100. // we should _not_ attempt to buffer any extra data. We'll get more data
  13101. // when the stream consumer calls read() instead.
  13102. // - No data in the buffer, and the stream is in flowing mode. In this mode
  13103. // the loop below is responsible for ensuring read() is called. Failing to
  13104. // call read here would abort the flow and there's no other mechanism for
  13105. // continuing the flow if the stream consumer has just subscribed to the
  13106. // 'data' event.
  13107. //
  13108. // In addition to the above conditions to keep reading data, the following
  13109. // conditions prevent the data from being read:
  13110. // - The stream has ended (state.ended).
  13111. // - There is already a pending 'read' operation (state.reading). This is a
  13112. // case where the the stream has called the implementation defined _read()
  13113. // method, but they are processing the call asynchronously and have _not_
  13114. // called push() with new data. In this case we skip performing more
  13115. // read()s. The execution ends in this method again after the _read() ends
  13116. // up calling push() with more data.
  13117. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  13118. var len = state.length;
  13119. debug('maybeReadMore read 0');
  13120. stream.read(0);
  13121. if (len === state.length) // didn't get any data, stop spinning.
  13122. break;
  13123. }
  13124. state.readingMore = false;
  13125. } // abstract method. to be overridden in specific implementation classes.
  13126. // call cb(er, data) where data is <= n in length.
  13127. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  13128. // arbitrary, and perhaps not very meaningful.
  13129. Readable.prototype._read = function (n) {
  13130. errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  13131. };
  13132. Readable.prototype.pipe = function (dest, pipeOpts) {
  13133. var src = this;
  13134. var state = this._readableState;
  13135. switch (state.pipesCount) {
  13136. case 0:
  13137. state.pipes = dest;
  13138. break;
  13139. case 1:
  13140. state.pipes = [state.pipes, dest];
  13141. break;
  13142. default:
  13143. state.pipes.push(dest);
  13144. break;
  13145. }
  13146. state.pipesCount += 1;
  13147. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  13148. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  13149. var endFn = doEnd ? onend : unpipe;
  13150. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  13151. dest.on('unpipe', onunpipe);
  13152. function onunpipe(readable, unpipeInfo) {
  13153. debug('onunpipe');
  13154. if (readable === src) {
  13155. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  13156. unpipeInfo.hasUnpiped = true;
  13157. cleanup();
  13158. }
  13159. }
  13160. }
  13161. function onend() {
  13162. debug('onend');
  13163. dest.end();
  13164. } // when the dest drains, it reduces the awaitDrain counter
  13165. // on the source. This would be more elegant with a .once()
  13166. // handler in flow(), but adding and removing repeatedly is
  13167. // too slow.
  13168. var ondrain = pipeOnDrain(src);
  13169. dest.on('drain', ondrain);
  13170. var cleanedUp = false;
  13171. function cleanup() {
  13172. debug('cleanup'); // cleanup event handlers once the pipe is broken
  13173. dest.removeListener('close', onclose);
  13174. dest.removeListener('finish', onfinish);
  13175. dest.removeListener('drain', ondrain);
  13176. dest.removeListener('error', onerror);
  13177. dest.removeListener('unpipe', onunpipe);
  13178. src.removeListener('end', onend);
  13179. src.removeListener('end', unpipe);
  13180. src.removeListener('data', ondata);
  13181. cleanedUp = true; // if the reader is waiting for a drain event from this
  13182. // specific writer, then it would cause it to never start
  13183. // flowing again.
  13184. // So, if this is awaiting a drain, then we just call it now.
  13185. // If we don't know, then assume that we are waiting for one.
  13186. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  13187. }
  13188. src.on('data', ondata);
  13189. function ondata(chunk) {
  13190. debug('ondata');
  13191. var ret = dest.write(chunk);
  13192. debug('dest.write', ret);
  13193. if (ret === false) {
  13194. // If the user unpiped during `dest.write()`, it is possible
  13195. // to get stuck in a permanently paused state if that write
  13196. // also returned false.
  13197. // => Check whether `dest` is still a piping destination.
  13198. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  13199. debug('false write response, pause', state.awaitDrain);
  13200. state.awaitDrain++;
  13201. }
  13202. src.pause();
  13203. }
  13204. } // if the dest has an error, then stop piping into it.
  13205. // however, don't suppress the throwing behavior for this.
  13206. function onerror(er) {
  13207. debug('onerror', er);
  13208. unpipe();
  13209. dest.removeListener('error', onerror);
  13210. if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  13211. } // Make sure our error handler is attached before userland ones.
  13212. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
  13213. function onclose() {
  13214. dest.removeListener('finish', onfinish);
  13215. unpipe();
  13216. }
  13217. dest.once('close', onclose);
  13218. function onfinish() {
  13219. debug('onfinish');
  13220. dest.removeListener('close', onclose);
  13221. unpipe();
  13222. }
  13223. dest.once('finish', onfinish);
  13224. function unpipe() {
  13225. debug('unpipe');
  13226. src.unpipe(dest);
  13227. } // tell the dest that it's being piped to
  13228. dest.emit('pipe', src); // start the flow if it hasn't been started already.
  13229. if (!state.flowing) {
  13230. debug('pipe resume');
  13231. src.resume();
  13232. }
  13233. return dest;
  13234. };
  13235. function pipeOnDrain(src) {
  13236. return function pipeOnDrainFunctionResult() {
  13237. var state = src._readableState;
  13238. debug('pipeOnDrain', state.awaitDrain);
  13239. if (state.awaitDrain) state.awaitDrain--;
  13240. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  13241. state.flowing = true;
  13242. flow(src);
  13243. }
  13244. };
  13245. }
  13246. Readable.prototype.unpipe = function (dest) {
  13247. var state = this._readableState;
  13248. var unpipeInfo = {
  13249. hasUnpiped: false
  13250. }; // if we're not piping anywhere, then do nothing.
  13251. if (state.pipesCount === 0) return this; // just one destination. most common case.
  13252. if (state.pipesCount === 1) {
  13253. // passed in one, but it's not the right one.
  13254. if (dest && dest !== state.pipes) return this;
  13255. if (!dest) dest = state.pipes; // got a match.
  13256. state.pipes = null;
  13257. state.pipesCount = 0;
  13258. state.flowing = false;
  13259. if (dest) dest.emit('unpipe', this, unpipeInfo);
  13260. return this;
  13261. } // slow case. multiple pipe destinations.
  13262. if (!dest) {
  13263. // remove all.
  13264. var dests = state.pipes;
  13265. var len = state.pipesCount;
  13266. state.pipes = null;
  13267. state.pipesCount = 0;
  13268. state.flowing = false;
  13269. for (var i = 0; i < len; i++) {
  13270. dests[i].emit('unpipe', this, {
  13271. hasUnpiped: false
  13272. });
  13273. }
  13274. return this;
  13275. } // try to find the right one.
  13276. var index = indexOf(state.pipes, dest);
  13277. if (index === -1) return this;
  13278. state.pipes.splice(index, 1);
  13279. state.pipesCount -= 1;
  13280. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  13281. dest.emit('unpipe', this, unpipeInfo);
  13282. return this;
  13283. }; // set up data events if they are asked for
  13284. // Ensure readable listeners eventually get something
  13285. Readable.prototype.on = function (ev, fn) {
  13286. var res = Stream.prototype.on.call(this, ev, fn);
  13287. var state = this._readableState;
  13288. if (ev === 'data') {
  13289. // update readableListening so that resume() may be a no-op
  13290. // a few lines down. This is needed to support once('readable').
  13291. state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
  13292. if (state.flowing !== false) this.resume();
  13293. } else if (ev === 'readable') {
  13294. if (!state.endEmitted && !state.readableListening) {
  13295. state.readableListening = state.needReadable = true;
  13296. state.flowing = false;
  13297. state.emittedReadable = false;
  13298. debug('on readable', state.length, state.reading);
  13299. if (state.length) {
  13300. emitReadable(this);
  13301. } else if (!state.reading) {
  13302. process.nextTick(nReadingNextTick, this);
  13303. }
  13304. }
  13305. }
  13306. return res;
  13307. };
  13308. Readable.prototype.addListener = Readable.prototype.on;
  13309. Readable.prototype.removeListener = function (ev, fn) {
  13310. var res = Stream.prototype.removeListener.call(this, ev, fn);
  13311. if (ev === 'readable') {
  13312. // We need to check if there is someone still listening to
  13313. // readable and reset the state. However this needs to happen
  13314. // after readable has been emitted but before I/O (nextTick) to
  13315. // support once('readable', fn) cycles. This means that calling
  13316. // resume within the same tick will have no
  13317. // effect.
  13318. process.nextTick(updateReadableListening, this);
  13319. }
  13320. return res;
  13321. };
  13322. Readable.prototype.removeAllListeners = function (ev) {
  13323. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  13324. if (ev === 'readable' || ev === undefined) {
  13325. // We need to check if there is someone still listening to
  13326. // readable and reset the state. However this needs to happen
  13327. // after readable has been emitted but before I/O (nextTick) to
  13328. // support once('readable', fn) cycles. This means that calling
  13329. // resume within the same tick will have no
  13330. // effect.
  13331. process.nextTick(updateReadableListening, this);
  13332. }
  13333. return res;
  13334. };
  13335. function updateReadableListening(self) {
  13336. var state = self._readableState;
  13337. state.readableListening = self.listenerCount('readable') > 0;
  13338. if (state.resumeScheduled && !state.paused) {
  13339. // flowing needs to be set to true now, otherwise
  13340. // the upcoming resume will not flow.
  13341. state.flowing = true; // crude way to check if we should resume
  13342. } else if (self.listenerCount('data') > 0) {
  13343. self.resume();
  13344. }
  13345. }
  13346. function nReadingNextTick(self) {
  13347. debug('readable nexttick read 0');
  13348. self.read(0);
  13349. } // pause() and resume() are remnants of the legacy readable stream API
  13350. // If the user uses them, then switch into old mode.
  13351. Readable.prototype.resume = function () {
  13352. var state = this._readableState;
  13353. if (!state.flowing) {
  13354. debug('resume'); // we flow only if there is no one listening
  13355. // for readable, but we still have to call
  13356. // resume()
  13357. state.flowing = !state.readableListening;
  13358. resume(this, state);
  13359. }
  13360. state.paused = false;
  13361. return this;
  13362. };
  13363. function resume(stream, state) {
  13364. if (!state.resumeScheduled) {
  13365. state.resumeScheduled = true;
  13366. process.nextTick(resume_, stream, state);
  13367. }
  13368. }
  13369. function resume_(stream, state) {
  13370. debug('resume', state.reading);
  13371. if (!state.reading) {
  13372. stream.read(0);
  13373. }
  13374. state.resumeScheduled = false;
  13375. stream.emit('resume');
  13376. flow(stream);
  13377. if (state.flowing && !state.reading) stream.read(0);
  13378. }
  13379. Readable.prototype.pause = function () {
  13380. debug('call pause flowing=%j', this._readableState.flowing);
  13381. if (this._readableState.flowing !== false) {
  13382. debug('pause');
  13383. this._readableState.flowing = false;
  13384. this.emit('pause');
  13385. }
  13386. this._readableState.paused = true;
  13387. return this;
  13388. };
  13389. function flow(stream) {
  13390. var state = stream._readableState;
  13391. debug('flow', state.flowing);
  13392. while (state.flowing && stream.read() !== null) {
  13393. ;
  13394. }
  13395. } // wrap an old-style stream as the async data source.
  13396. // This is *not* part of the readable stream interface.
  13397. // It is an ugly unfortunate mess of history.
  13398. Readable.prototype.wrap = function (stream) {
  13399. var _this = this;
  13400. var state = this._readableState;
  13401. var paused = false;
  13402. stream.on('end', function () {
  13403. debug('wrapped end');
  13404. if (state.decoder && !state.ended) {
  13405. var chunk = state.decoder.end();
  13406. if (chunk && chunk.length) _this.push(chunk);
  13407. }
  13408. _this.push(null);
  13409. });
  13410. stream.on('data', function (chunk) {
  13411. debug('wrapped data');
  13412. if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
  13413. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  13414. var ret = _this.push(chunk);
  13415. if (!ret) {
  13416. paused = true;
  13417. stream.pause();
  13418. }
  13419. }); // proxy all the other methods.
  13420. // important when wrapping filters and duplexes.
  13421. for (var i in stream) {
  13422. if (this[i] === undefined && typeof stream[i] === 'function') {
  13423. this[i] = function methodWrap(method) {
  13424. return function methodWrapReturnFunction() {
  13425. return stream[method].apply(stream, arguments);
  13426. };
  13427. }(i);
  13428. }
  13429. } // proxy certain important events.
  13430. for (var n = 0; n < kProxyEvents.length; n++) {
  13431. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  13432. } // when we try to consume some more bytes, simply unpause the
  13433. // underlying stream.
  13434. this._read = function (n) {
  13435. debug('wrapped _read', n);
  13436. if (paused) {
  13437. paused = false;
  13438. stream.resume();
  13439. }
  13440. };
  13441. return this;
  13442. };
  13443. if (typeof Symbol === 'function') {
  13444. Readable.prototype[Symbol.asyncIterator] = function () {
  13445. if (createReadableStreamAsyncIterator === undefined) {
  13446. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  13447. }
  13448. return createReadableStreamAsyncIterator(this);
  13449. };
  13450. }
  13451. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  13452. // making it explicit this property is not enumerable
  13453. // because otherwise some prototype manipulation in
  13454. // userland will fail
  13455. enumerable: false,
  13456. get: function get() {
  13457. return this._readableState.highWaterMark;
  13458. }
  13459. });
  13460. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  13461. // making it explicit this property is not enumerable
  13462. // because otherwise some prototype manipulation in
  13463. // userland will fail
  13464. enumerable: false,
  13465. get: function get() {
  13466. return this._readableState && this._readableState.buffer;
  13467. }
  13468. });
  13469. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  13470. // making it explicit this property is not enumerable
  13471. // because otherwise some prototype manipulation in
  13472. // userland will fail
  13473. enumerable: false,
  13474. get: function get() {
  13475. return this._readableState.flowing;
  13476. },
  13477. set: function set(state) {
  13478. if (this._readableState) {
  13479. this._readableState.flowing = state;
  13480. }
  13481. }
  13482. }); // exposed for testing purposes only.
  13483. Readable._fromList = fromList;
  13484. Object.defineProperty(Readable.prototype, 'readableLength', {
  13485. // making it explicit this property is not enumerable
  13486. // because otherwise some prototype manipulation in
  13487. // userland will fail
  13488. enumerable: false,
  13489. get: function get() {
  13490. return this._readableState.length;
  13491. }
  13492. }); // Pluck off n bytes from an array of buffers.
  13493. // Length is the combined lengths of all the buffers in the list.
  13494. // This function is designed to be inlinable, so please take care when making
  13495. // changes to the function body.
  13496. function fromList(n, state) {
  13497. // nothing buffered
  13498. if (state.length === 0) return null;
  13499. var ret;
  13500. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  13501. // read it all, truncate the list
  13502. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  13503. state.buffer.clear();
  13504. } else {
  13505. // read part of list
  13506. ret = state.buffer.consume(n, state.decoder);
  13507. }
  13508. return ret;
  13509. }
  13510. function endReadable(stream) {
  13511. var state = stream._readableState;
  13512. debug('endReadable', state.endEmitted);
  13513. if (!state.endEmitted) {
  13514. state.ended = true;
  13515. process.nextTick(endReadableNT, state, stream);
  13516. }
  13517. }
  13518. function endReadableNT(state, stream) {
  13519. debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
  13520. if (!state.endEmitted && state.length === 0) {
  13521. state.endEmitted = true;
  13522. stream.readable = false;
  13523. stream.emit('end');
  13524. if (state.autoDestroy) {
  13525. // In case of duplex streams we need a way to detect
  13526. // if the writable side is ready for autoDestroy as well
  13527. var wState = stream._writableState;
  13528. if (!wState || wState.autoDestroy && wState.finished) {
  13529. stream.destroy();
  13530. }
  13531. }
  13532. }
  13533. }
  13534. if (typeof Symbol === 'function') {
  13535. Readable.from = function (iterable, opts) {
  13536. if (from === undefined) {
  13537. from = require('./internal/streams/from');
  13538. }
  13539. return from(Readable, iterable, opts);
  13540. };
  13541. }
  13542. function indexOf(xs, x) {
  13543. for (var i = 0, l = xs.length; i < l; i++) {
  13544. if (xs[i] === x) return i;
  13545. }
  13546. return -1;
  13547. }
  13548. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13549. },{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,"_process":50,"buffer":17,"events":22,"inherits":24,"string_decoder/":75,"util":16}],59:[function(require,module,exports){
  13550. // Copyright Joyent, Inc. and other Node contributors.
  13551. //
  13552. // Permission is hereby granted, free of charge, to any person obtaining a
  13553. // copy of this software and associated documentation files (the
  13554. // "Software"), to deal in the Software without restriction, including
  13555. // without limitation the rights to use, copy, modify, merge, publish,
  13556. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13557. // persons to whom the Software is furnished to do so, subject to the
  13558. // following conditions:
  13559. //
  13560. // The above copyright notice and this permission notice shall be included
  13561. // in all copies or substantial portions of the Software.
  13562. //
  13563. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13564. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13565. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13566. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13567. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13568. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13569. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13570. // a transform stream is a readable/writable stream where you do
  13571. // something with the data. Sometimes it's called a "filter",
  13572. // but that's not a great name for it, since that implies a thing where
  13573. // some bits pass through, and others are simply ignored. (That would
  13574. // be a valid example of a transform, of course.)
  13575. //
  13576. // While the output is causally related to the input, it's not a
  13577. // necessarily symmetric or synchronous transformation. For example,
  13578. // a zlib stream might take multiple plain-text writes(), and then
  13579. // emit a single compressed chunk some time in the future.
  13580. //
  13581. // Here's how this works:
  13582. //
  13583. // The Transform stream has all the aspects of the readable and writable
  13584. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  13585. // internally, and returns false if there's a lot of pending writes
  13586. // buffered up. When you call read(), that calls _read(n) until
  13587. // there's enough pending readable data buffered up.
  13588. //
  13589. // In a transform stream, the written data is placed in a buffer. When
  13590. // _read(n) is called, it transforms the queued up data, calling the
  13591. // buffered _write cb's as it consumes chunks. If consuming a single
  13592. // written chunk would result in multiple output chunks, then the first
  13593. // outputted bit calls the readcb, and subsequent chunks just go into
  13594. // the read buffer, and will cause it to emit 'readable' if necessary.
  13595. //
  13596. // This way, back-pressure is actually determined by the reading side,
  13597. // since _read has to be called to start processing a new chunk. However,
  13598. // a pathological inflate type of transform can cause excessive buffering
  13599. // here. For example, imagine a stream where every byte of input is
  13600. // interpreted as an integer from 0-255, and then results in that many
  13601. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  13602. // 1kb of data being output. In this case, you could write a very small
  13603. // amount of input, and end up with a very large amount of output. In
  13604. // such a pathological inflating mechanism, there'd be no way to tell
  13605. // the system to stop doing the transform. A single 4MB write could
  13606. // cause the system to run out of memory.
  13607. //
  13608. // However, even in such a pathological case, only a single written chunk
  13609. // would be consumed, and then the rest would wait (un-transformed) until
  13610. // the results of the previous transformed chunk were consumed.
  13611. 'use strict';
  13612. module.exports = Transform;
  13613. var _require$codes = require('../errors').codes,
  13614. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  13615. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  13616. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  13617. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  13618. var Duplex = require('./_stream_duplex');
  13619. require('inherits')(Transform, Duplex);
  13620. function afterTransform(er, data) {
  13621. var ts = this._transformState;
  13622. ts.transforming = false;
  13623. var cb = ts.writecb;
  13624. if (cb === null) {
  13625. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  13626. }
  13627. ts.writechunk = null;
  13628. ts.writecb = null;
  13629. if (data != null) // single equals check for both `null` and `undefined`
  13630. this.push(data);
  13631. cb(er);
  13632. var rs = this._readableState;
  13633. rs.reading = false;
  13634. if (rs.needReadable || rs.length < rs.highWaterMark) {
  13635. this._read(rs.highWaterMark);
  13636. }
  13637. }
  13638. function Transform(options) {
  13639. if (!(this instanceof Transform)) return new Transform(options);
  13640. Duplex.call(this, options);
  13641. this._transformState = {
  13642. afterTransform: afterTransform.bind(this),
  13643. needTransform: false,
  13644. transforming: false,
  13645. writecb: null,
  13646. writechunk: null,
  13647. writeencoding: null
  13648. }; // start out asking for a readable event once data is transformed.
  13649. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
  13650. // that Readable wants before the first _read call, so unset the
  13651. // sync guard flag.
  13652. this._readableState.sync = false;
  13653. if (options) {
  13654. if (typeof options.transform === 'function') this._transform = options.transform;
  13655. if (typeof options.flush === 'function') this._flush = options.flush;
  13656. } // When the writable side finishes, then flush out anything remaining.
  13657. this.on('prefinish', prefinish);
  13658. }
  13659. function prefinish() {
  13660. var _this = this;
  13661. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  13662. this._flush(function (er, data) {
  13663. done(_this, er, data);
  13664. });
  13665. } else {
  13666. done(this, null, null);
  13667. }
  13668. }
  13669. Transform.prototype.push = function (chunk, encoding) {
  13670. this._transformState.needTransform = false;
  13671. return Duplex.prototype.push.call(this, chunk, encoding);
  13672. }; // This is the part where you do stuff!
  13673. // override this function in implementation classes.
  13674. // 'chunk' is an input chunk.
  13675. //
  13676. // Call `push(newChunk)` to pass along transformed output
  13677. // to the readable side. You may call 'push' zero or more times.
  13678. //
  13679. // Call `cb(err)` when you are done with this chunk. If you pass
  13680. // an error, then that'll put the hurt on the whole operation. If you
  13681. // never call cb(), then you'll never get another chunk.
  13682. Transform.prototype._transform = function (chunk, encoding, cb) {
  13683. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  13684. };
  13685. Transform.prototype._write = function (chunk, encoding, cb) {
  13686. var ts = this._transformState;
  13687. ts.writecb = cb;
  13688. ts.writechunk = chunk;
  13689. ts.writeencoding = encoding;
  13690. if (!ts.transforming) {
  13691. var rs = this._readableState;
  13692. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  13693. }
  13694. }; // Doesn't matter what the args are here.
  13695. // _transform does all the work.
  13696. // That we got here means that the readable side wants more data.
  13697. Transform.prototype._read = function (n) {
  13698. var ts = this._transformState;
  13699. if (ts.writechunk !== null && !ts.transforming) {
  13700. ts.transforming = true;
  13701. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  13702. } else {
  13703. // mark that we need a transform, so that any data that comes in
  13704. // will get processed, now that we've asked for it.
  13705. ts.needTransform = true;
  13706. }
  13707. };
  13708. Transform.prototype._destroy = function (err, cb) {
  13709. Duplex.prototype._destroy.call(this, err, function (err2) {
  13710. cb(err2);
  13711. });
  13712. };
  13713. function done(stream, er, data) {
  13714. if (er) return stream.emit('error', er);
  13715. if (data != null) // single equals check for both `null` and `undefined`
  13716. stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
  13717. // if there's nothing in the write buffer, then that means
  13718. // that nothing more will ever be provided
  13719. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  13720. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  13721. return stream.push(null);
  13722. }
  13723. },{"../errors":55,"./_stream_duplex":56,"inherits":24}],60:[function(require,module,exports){
  13724. (function (process,global){(function (){
  13725. // Copyright Joyent, Inc. and other Node contributors.
  13726. //
  13727. // Permission is hereby granted, free of charge, to any person obtaining a
  13728. // copy of this software and associated documentation files (the
  13729. // "Software"), to deal in the Software without restriction, including
  13730. // without limitation the rights to use, copy, modify, merge, publish,
  13731. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13732. // persons to whom the Software is furnished to do so, subject to the
  13733. // following conditions:
  13734. //
  13735. // The above copyright notice and this permission notice shall be included
  13736. // in all copies or substantial portions of the Software.
  13737. //
  13738. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13739. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13740. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13741. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13742. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13743. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13744. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13745. // A bit simpler than readable streams.
  13746. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  13747. // the drain event emission and buffering.
  13748. 'use strict';
  13749. module.exports = Writable;
  13750. /* <replacement> */
  13751. function WriteReq(chunk, encoding, cb) {
  13752. this.chunk = chunk;
  13753. this.encoding = encoding;
  13754. this.callback = cb;
  13755. this.next = null;
  13756. } // It seems a linked list but it is not
  13757. // there will be only 2 of these for each stream
  13758. function CorkedRequest(state) {
  13759. var _this = this;
  13760. this.next = null;
  13761. this.entry = null;
  13762. this.finish = function () {
  13763. onCorkedFinish(_this, state);
  13764. };
  13765. }
  13766. /* </replacement> */
  13767. /*<replacement>*/
  13768. var Duplex;
  13769. /*</replacement>*/
  13770. Writable.WritableState = WritableState;
  13771. /*<replacement>*/
  13772. var internalUtil = {
  13773. deprecate: require('util-deprecate')
  13774. };
  13775. /*</replacement>*/
  13776. /*<replacement>*/
  13777. var Stream = require('./internal/streams/stream');
  13778. /*</replacement>*/
  13779. var Buffer = require('buffer').Buffer;
  13780. var OurUint8Array = global.Uint8Array || function () {};
  13781. function _uint8ArrayToBuffer(chunk) {
  13782. return Buffer.from(chunk);
  13783. }
  13784. function _isUint8Array(obj) {
  13785. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  13786. }
  13787. var destroyImpl = require('./internal/streams/destroy');
  13788. var _require = require('./internal/streams/state'),
  13789. getHighWaterMark = _require.getHighWaterMark;
  13790. var _require$codes = require('../errors').codes,
  13791. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  13792. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  13793. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  13794. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  13795. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  13796. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  13797. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  13798. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  13799. var errorOrDestroy = destroyImpl.errorOrDestroy;
  13800. require('inherits')(Writable, Stream);
  13801. function nop() {}
  13802. function WritableState(options, stream, isDuplex) {
  13803. Duplex = Duplex || require('./_stream_duplex');
  13804. options = options || {}; // Duplex streams are both readable and writable, but share
  13805. // the same options object.
  13806. // However, some cases require setting options to different
  13807. // values for the readable and the writable sides of the duplex stream,
  13808. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  13809. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
  13810. // contains buffers or objects.
  13811. this.objectMode = !!options.objectMode;
  13812. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
  13813. // Note: 0 is a valid value, means that we always return false if
  13814. // the entire buffer is not flushed immediately on write()
  13815. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
  13816. this.finalCalled = false; // drain event flag.
  13817. this.needDrain = false; // at the start of calling end()
  13818. this.ending = false; // when end() has been called, and returned
  13819. this.ended = false; // when 'finish' is emitted
  13820. this.finished = false; // has it been destroyed
  13821. this.destroyed = false; // should we decode strings into buffers before passing to _write?
  13822. // this is here so that some node-core streams can optimize string
  13823. // handling at a lower level.
  13824. var noDecode = options.decodeStrings === false;
  13825. this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
  13826. // encoding is 'binary' so we have to make this configurable.
  13827. // Everything else in the universe uses 'utf8', though.
  13828. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
  13829. // of how much we're waiting to get pushed to some underlying
  13830. // socket or file.
  13831. this.length = 0; // a flag to see when we're in the middle of a write.
  13832. this.writing = false; // when true all writes will be buffered until .uncork() call
  13833. this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
  13834. // or on a later tick. We set this to true at first, because any
  13835. // actions that shouldn't happen until "later" should generally also
  13836. // not happen before the first write call.
  13837. this.sync = true; // a flag to know if we're processing previously buffered items, which
  13838. // may call the _write() callback in the same tick, so that we don't
  13839. // end up in an overlapped onwrite situation.
  13840. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
  13841. this.onwrite = function (er) {
  13842. onwrite(stream, er);
  13843. }; // the callback that the user supplies to write(chunk,encoding,cb)
  13844. this.writecb = null; // the amount that is being written when _write is called.
  13845. this.writelen = 0;
  13846. this.bufferedRequest = null;
  13847. this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
  13848. // this must be 0 before 'finish' can be emitted
  13849. this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
  13850. // This is relevant for synchronous Transform streams
  13851. this.prefinished = false; // True if the error was already emitted and should not be thrown again
  13852. this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
  13853. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
  13854. this.autoDestroy = !!options.autoDestroy; // count buffered requests
  13855. this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
  13856. // one allocated and free to use, and we maintain at most two
  13857. this.corkedRequestsFree = new CorkedRequest(this);
  13858. }
  13859. WritableState.prototype.getBuffer = function getBuffer() {
  13860. var current = this.bufferedRequest;
  13861. var out = [];
  13862. while (current) {
  13863. out.push(current);
  13864. current = current.next;
  13865. }
  13866. return out;
  13867. };
  13868. (function () {
  13869. try {
  13870. Object.defineProperty(WritableState.prototype, 'buffer', {
  13871. get: internalUtil.deprecate(function writableStateBufferGetter() {
  13872. return this.getBuffer();
  13873. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  13874. });
  13875. } catch (_) {}
  13876. })(); // Test _writableState for inheritance to account for Duplex streams,
  13877. // whose prototype chain only points to Readable.
  13878. var realHasInstance;
  13879. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  13880. realHasInstance = Function.prototype[Symbol.hasInstance];
  13881. Object.defineProperty(Writable, Symbol.hasInstance, {
  13882. value: function value(object) {
  13883. if (realHasInstance.call(this, object)) return true;
  13884. if (this !== Writable) return false;
  13885. return object && object._writableState instanceof WritableState;
  13886. }
  13887. });
  13888. } else {
  13889. realHasInstance = function realHasInstance(object) {
  13890. return object instanceof this;
  13891. };
  13892. }
  13893. function Writable(options) {
  13894. Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
  13895. // `realHasInstance` is necessary because using plain `instanceof`
  13896. // would return false, as no `_writableState` property is attached.
  13897. // Trying to use the custom `instanceof` for Writable here will also break the
  13898. // Node.js LazyTransform implementation, which has a non-trivial getter for
  13899. // `_writableState` that would lead to infinite recursion.
  13900. // Checking for a Stream.Duplex instance is faster here instead of inside
  13901. // the WritableState constructor, at least with V8 6.5
  13902. var isDuplex = this instanceof Duplex;
  13903. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  13904. this._writableState = new WritableState(options, this, isDuplex); // legacy.
  13905. this.writable = true;
  13906. if (options) {
  13907. if (typeof options.write === 'function') this._write = options.write;
  13908. if (typeof options.writev === 'function') this._writev = options.writev;
  13909. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  13910. if (typeof options.final === 'function') this._final = options.final;
  13911. }
  13912. Stream.call(this);
  13913. } // Otherwise people can pipe Writable streams, which is just wrong.
  13914. Writable.prototype.pipe = function () {
  13915. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  13916. };
  13917. function writeAfterEnd(stream, cb) {
  13918. var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
  13919. errorOrDestroy(stream, er);
  13920. process.nextTick(cb, er);
  13921. } // Checks that a user-supplied chunk is valid, especially for the particular
  13922. // mode the stream is in. Currently this means that `null` is never accepted
  13923. // and undefined/non-string values are only allowed in object mode.
  13924. function validChunk(stream, state, chunk, cb) {
  13925. var er;
  13926. if (chunk === null) {
  13927. er = new ERR_STREAM_NULL_VALUES();
  13928. } else if (typeof chunk !== 'string' && !state.objectMode) {
  13929. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  13930. }
  13931. if (er) {
  13932. errorOrDestroy(stream, er);
  13933. process.nextTick(cb, er);
  13934. return false;
  13935. }
  13936. return true;
  13937. }
  13938. Writable.prototype.write = function (chunk, encoding, cb) {
  13939. var state = this._writableState;
  13940. var ret = false;
  13941. var isBuf = !state.objectMode && _isUint8Array(chunk);
  13942. if (isBuf && !Buffer.isBuffer(chunk)) {
  13943. chunk = _uint8ArrayToBuffer(chunk);
  13944. }
  13945. if (typeof encoding === 'function') {
  13946. cb = encoding;
  13947. encoding = null;
  13948. }
  13949. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  13950. if (typeof cb !== 'function') cb = nop;
  13951. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  13952. state.pendingcb++;
  13953. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  13954. }
  13955. return ret;
  13956. };
  13957. Writable.prototype.cork = function () {
  13958. this._writableState.corked++;
  13959. };
  13960. Writable.prototype.uncork = function () {
  13961. var state = this._writableState;
  13962. if (state.corked) {
  13963. state.corked--;
  13964. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  13965. }
  13966. };
  13967. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  13968. // node::ParseEncoding() requires lower case.
  13969. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  13970. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  13971. this._writableState.defaultEncoding = encoding;
  13972. return this;
  13973. };
  13974. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  13975. // making it explicit this property is not enumerable
  13976. // because otherwise some prototype manipulation in
  13977. // userland will fail
  13978. enumerable: false,
  13979. get: function get() {
  13980. return this._writableState && this._writableState.getBuffer();
  13981. }
  13982. });
  13983. function decodeChunk(state, chunk, encoding) {
  13984. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  13985. chunk = Buffer.from(chunk, encoding);
  13986. }
  13987. return chunk;
  13988. }
  13989. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  13990. // making it explicit this property is not enumerable
  13991. // because otherwise some prototype manipulation in
  13992. // userland will fail
  13993. enumerable: false,
  13994. get: function get() {
  13995. return this._writableState.highWaterMark;
  13996. }
  13997. }); // if we're already writing something, then just put this
  13998. // in the queue, and wait our turn. Otherwise, call _write
  13999. // If we return false, then we need a drain event, so set that flag.
  14000. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  14001. if (!isBuf) {
  14002. var newChunk = decodeChunk(state, chunk, encoding);
  14003. if (chunk !== newChunk) {
  14004. isBuf = true;
  14005. encoding = 'buffer';
  14006. chunk = newChunk;
  14007. }
  14008. }
  14009. var len = state.objectMode ? 1 : chunk.length;
  14010. state.length += len;
  14011. var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
  14012. if (!ret) state.needDrain = true;
  14013. if (state.writing || state.corked) {
  14014. var last = state.lastBufferedRequest;
  14015. state.lastBufferedRequest = {
  14016. chunk: chunk,
  14017. encoding: encoding,
  14018. isBuf: isBuf,
  14019. callback: cb,
  14020. next: null
  14021. };
  14022. if (last) {
  14023. last.next = state.lastBufferedRequest;
  14024. } else {
  14025. state.bufferedRequest = state.lastBufferedRequest;
  14026. }
  14027. state.bufferedRequestCount += 1;
  14028. } else {
  14029. doWrite(stream, state, false, len, chunk, encoding, cb);
  14030. }
  14031. return ret;
  14032. }
  14033. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  14034. state.writelen = len;
  14035. state.writecb = cb;
  14036. state.writing = true;
  14037. state.sync = true;
  14038. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  14039. state.sync = false;
  14040. }
  14041. function onwriteError(stream, state, sync, er, cb) {
  14042. --state.pendingcb;
  14043. if (sync) {
  14044. // defer the callback if we are being called synchronously
  14045. // to avoid piling up things on the stack
  14046. process.nextTick(cb, er); // this can emit finish, and it will always happen
  14047. // after error
  14048. process.nextTick(finishMaybe, stream, state);
  14049. stream._writableState.errorEmitted = true;
  14050. errorOrDestroy(stream, er);
  14051. } else {
  14052. // the caller expect this to happen before if
  14053. // it is async
  14054. cb(er);
  14055. stream._writableState.errorEmitted = true;
  14056. errorOrDestroy(stream, er); // this can emit finish, but finish must
  14057. // always follow error
  14058. finishMaybe(stream, state);
  14059. }
  14060. }
  14061. function onwriteStateUpdate(state) {
  14062. state.writing = false;
  14063. state.writecb = null;
  14064. state.length -= state.writelen;
  14065. state.writelen = 0;
  14066. }
  14067. function onwrite(stream, er) {
  14068. var state = stream._writableState;
  14069. var sync = state.sync;
  14070. var cb = state.writecb;
  14071. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  14072. onwriteStateUpdate(state);
  14073. if (er) onwriteError(stream, state, sync, er, cb);else {
  14074. // Check if we're actually ready to finish, but don't emit yet
  14075. var finished = needFinish(state) || stream.destroyed;
  14076. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  14077. clearBuffer(stream, state);
  14078. }
  14079. if (sync) {
  14080. process.nextTick(afterWrite, stream, state, finished, cb);
  14081. } else {
  14082. afterWrite(stream, state, finished, cb);
  14083. }
  14084. }
  14085. }
  14086. function afterWrite(stream, state, finished, cb) {
  14087. if (!finished) onwriteDrain(stream, state);
  14088. state.pendingcb--;
  14089. cb();
  14090. finishMaybe(stream, state);
  14091. } // Must force callback to be called on nextTick, so that we don't
  14092. // emit 'drain' before the write() consumer gets the 'false' return
  14093. // value, and has a chance to attach a 'drain' listener.
  14094. function onwriteDrain(stream, state) {
  14095. if (state.length === 0 && state.needDrain) {
  14096. state.needDrain = false;
  14097. stream.emit('drain');
  14098. }
  14099. } // if there's something in the buffer waiting, then process it
  14100. function clearBuffer(stream, state) {
  14101. state.bufferProcessing = true;
  14102. var entry = state.bufferedRequest;
  14103. if (stream._writev && entry && entry.next) {
  14104. // Fast case, write everything using _writev()
  14105. var l = state.bufferedRequestCount;
  14106. var buffer = new Array(l);
  14107. var holder = state.corkedRequestsFree;
  14108. holder.entry = entry;
  14109. var count = 0;
  14110. var allBuffers = true;
  14111. while (entry) {
  14112. buffer[count] = entry;
  14113. if (!entry.isBuf) allBuffers = false;
  14114. entry = entry.next;
  14115. count += 1;
  14116. }
  14117. buffer.allBuffers = allBuffers;
  14118. doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
  14119. // as the hot path ends with doWrite
  14120. state.pendingcb++;
  14121. state.lastBufferedRequest = null;
  14122. if (holder.next) {
  14123. state.corkedRequestsFree = holder.next;
  14124. holder.next = null;
  14125. } else {
  14126. state.corkedRequestsFree = new CorkedRequest(state);
  14127. }
  14128. state.bufferedRequestCount = 0;
  14129. } else {
  14130. // Slow case, write chunks one-by-one
  14131. while (entry) {
  14132. var chunk = entry.chunk;
  14133. var encoding = entry.encoding;
  14134. var cb = entry.callback;
  14135. var len = state.objectMode ? 1 : chunk.length;
  14136. doWrite(stream, state, false, len, chunk, encoding, cb);
  14137. entry = entry.next;
  14138. state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
  14139. // it means that we need to wait until it does.
  14140. // also, that means that the chunk and cb are currently
  14141. // being processed, so move the buffer counter past them.
  14142. if (state.writing) {
  14143. break;
  14144. }
  14145. }
  14146. if (entry === null) state.lastBufferedRequest = null;
  14147. }
  14148. state.bufferedRequest = entry;
  14149. state.bufferProcessing = false;
  14150. }
  14151. Writable.prototype._write = function (chunk, encoding, cb) {
  14152. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  14153. };
  14154. Writable.prototype._writev = null;
  14155. Writable.prototype.end = function (chunk, encoding, cb) {
  14156. var state = this._writableState;
  14157. if (typeof chunk === 'function') {
  14158. cb = chunk;
  14159. chunk = null;
  14160. encoding = null;
  14161. } else if (typeof encoding === 'function') {
  14162. cb = encoding;
  14163. encoding = null;
  14164. }
  14165. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
  14166. if (state.corked) {
  14167. state.corked = 1;
  14168. this.uncork();
  14169. } // ignore unnecessary end() calls.
  14170. if (!state.ending) endWritable(this, state, cb);
  14171. return this;
  14172. };
  14173. Object.defineProperty(Writable.prototype, 'writableLength', {
  14174. // making it explicit this property is not enumerable
  14175. // because otherwise some prototype manipulation in
  14176. // userland will fail
  14177. enumerable: false,
  14178. get: function get() {
  14179. return this._writableState.length;
  14180. }
  14181. });
  14182. function needFinish(state) {
  14183. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  14184. }
  14185. function callFinal(stream, state) {
  14186. stream._final(function (err) {
  14187. state.pendingcb--;
  14188. if (err) {
  14189. errorOrDestroy(stream, err);
  14190. }
  14191. state.prefinished = true;
  14192. stream.emit('prefinish');
  14193. finishMaybe(stream, state);
  14194. });
  14195. }
  14196. function prefinish(stream, state) {
  14197. if (!state.prefinished && !state.finalCalled) {
  14198. if (typeof stream._final === 'function' && !state.destroyed) {
  14199. state.pendingcb++;
  14200. state.finalCalled = true;
  14201. process.nextTick(callFinal, stream, state);
  14202. } else {
  14203. state.prefinished = true;
  14204. stream.emit('prefinish');
  14205. }
  14206. }
  14207. }
  14208. function finishMaybe(stream, state) {
  14209. var need = needFinish(state);
  14210. if (need) {
  14211. prefinish(stream, state);
  14212. if (state.pendingcb === 0) {
  14213. state.finished = true;
  14214. stream.emit('finish');
  14215. if (state.autoDestroy) {
  14216. // In case of duplex streams we need a way to detect
  14217. // if the readable side is ready for autoDestroy as well
  14218. var rState = stream._readableState;
  14219. if (!rState || rState.autoDestroy && rState.endEmitted) {
  14220. stream.destroy();
  14221. }
  14222. }
  14223. }
  14224. }
  14225. return need;
  14226. }
  14227. function endWritable(stream, state, cb) {
  14228. state.ending = true;
  14229. finishMaybe(stream, state);
  14230. if (cb) {
  14231. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  14232. }
  14233. state.ended = true;
  14234. stream.writable = false;
  14235. }
  14236. function onCorkedFinish(corkReq, state, err) {
  14237. var entry = corkReq.entry;
  14238. corkReq.entry = null;
  14239. while (entry) {
  14240. var cb = entry.callback;
  14241. state.pendingcb--;
  14242. cb(err);
  14243. entry = entry.next;
  14244. } // reuse the free corkReq.
  14245. state.corkedRequestsFree.next = corkReq;
  14246. }
  14247. Object.defineProperty(Writable.prototype, 'destroyed', {
  14248. // making it explicit this property is not enumerable
  14249. // because otherwise some prototype manipulation in
  14250. // userland will fail
  14251. enumerable: false,
  14252. get: function get() {
  14253. if (this._writableState === undefined) {
  14254. return false;
  14255. }
  14256. return this._writableState.destroyed;
  14257. },
  14258. set: function set(value) {
  14259. // we ignore the value if the stream
  14260. // has not been initialized yet
  14261. if (!this._writableState) {
  14262. return;
  14263. } // backward compatibility, the user is explicitly
  14264. // managing destroyed
  14265. this._writableState.destroyed = value;
  14266. }
  14267. });
  14268. Writable.prototype.destroy = destroyImpl.destroy;
  14269. Writable.prototype._undestroy = destroyImpl.undestroy;
  14270. Writable.prototype._destroy = function (err, cb) {
  14271. cb(err);
  14272. };
  14273. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14274. },{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,"_process":50,"buffer":17,"inherits":24,"util-deprecate":78}],61:[function(require,module,exports){
  14275. (function (process){(function (){
  14276. 'use strict';
  14277. var _Object$setPrototypeO;
  14278. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  14279. var finished = require('./end-of-stream');
  14280. var kLastResolve = Symbol('lastResolve');
  14281. var kLastReject = Symbol('lastReject');
  14282. var kError = Symbol('error');
  14283. var kEnded = Symbol('ended');
  14284. var kLastPromise = Symbol('lastPromise');
  14285. var kHandlePromise = Symbol('handlePromise');
  14286. var kStream = Symbol('stream');
  14287. function createIterResult(value, done) {
  14288. return {
  14289. value: value,
  14290. done: done
  14291. };
  14292. }
  14293. function readAndResolve(iter) {
  14294. var resolve = iter[kLastResolve];
  14295. if (resolve !== null) {
  14296. var data = iter[kStream].read(); // we defer if data is null
  14297. // we can be expecting either 'end' or
  14298. // 'error'
  14299. if (data !== null) {
  14300. iter[kLastPromise] = null;
  14301. iter[kLastResolve] = null;
  14302. iter[kLastReject] = null;
  14303. resolve(createIterResult(data, false));
  14304. }
  14305. }
  14306. }
  14307. function onReadable(iter) {
  14308. // we wait for the next tick, because it might
  14309. // emit an error with process.nextTick
  14310. process.nextTick(readAndResolve, iter);
  14311. }
  14312. function wrapForNext(lastPromise, iter) {
  14313. return function (resolve, reject) {
  14314. lastPromise.then(function () {
  14315. if (iter[kEnded]) {
  14316. resolve(createIterResult(undefined, true));
  14317. return;
  14318. }
  14319. iter[kHandlePromise](resolve, reject);
  14320. }, reject);
  14321. };
  14322. }
  14323. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  14324. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  14325. get stream() {
  14326. return this[kStream];
  14327. },
  14328. next: function next() {
  14329. var _this = this;
  14330. // if we have detected an error in the meanwhile
  14331. // reject straight away
  14332. var error = this[kError];
  14333. if (error !== null) {
  14334. return Promise.reject(error);
  14335. }
  14336. if (this[kEnded]) {
  14337. return Promise.resolve(createIterResult(undefined, true));
  14338. }
  14339. if (this[kStream].destroyed) {
  14340. // We need to defer via nextTick because if .destroy(err) is
  14341. // called, the error will be emitted via nextTick, and
  14342. // we cannot guarantee that there is no error lingering around
  14343. // waiting to be emitted.
  14344. return new Promise(function (resolve, reject) {
  14345. process.nextTick(function () {
  14346. if (_this[kError]) {
  14347. reject(_this[kError]);
  14348. } else {
  14349. resolve(createIterResult(undefined, true));
  14350. }
  14351. });
  14352. });
  14353. } // if we have multiple next() calls
  14354. // we will wait for the previous Promise to finish
  14355. // this logic is optimized to support for await loops,
  14356. // where next() is only called once at a time
  14357. var lastPromise = this[kLastPromise];
  14358. var promise;
  14359. if (lastPromise) {
  14360. promise = new Promise(wrapForNext(lastPromise, this));
  14361. } else {
  14362. // fast path needed to support multiple this.push()
  14363. // without triggering the next() queue
  14364. var data = this[kStream].read();
  14365. if (data !== null) {
  14366. return Promise.resolve(createIterResult(data, false));
  14367. }
  14368. promise = new Promise(this[kHandlePromise]);
  14369. }
  14370. this[kLastPromise] = promise;
  14371. return promise;
  14372. }
  14373. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  14374. return this;
  14375. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  14376. var _this2 = this;
  14377. // destroy(err, cb) is a private API
  14378. // we can guarantee we have that here, because we control the
  14379. // Readable class this is attached to
  14380. return new Promise(function (resolve, reject) {
  14381. _this2[kStream].destroy(null, function (err) {
  14382. if (err) {
  14383. reject(err);
  14384. return;
  14385. }
  14386. resolve(createIterResult(undefined, true));
  14387. });
  14388. });
  14389. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  14390. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  14391. var _Object$create;
  14392. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  14393. value: stream,
  14394. writable: true
  14395. }), _defineProperty(_Object$create, kLastResolve, {
  14396. value: null,
  14397. writable: true
  14398. }), _defineProperty(_Object$create, kLastReject, {
  14399. value: null,
  14400. writable: true
  14401. }), _defineProperty(_Object$create, kError, {
  14402. value: null,
  14403. writable: true
  14404. }), _defineProperty(_Object$create, kEnded, {
  14405. value: stream._readableState.endEmitted,
  14406. writable: true
  14407. }), _defineProperty(_Object$create, kHandlePromise, {
  14408. value: function value(resolve, reject) {
  14409. var data = iterator[kStream].read();
  14410. if (data) {
  14411. iterator[kLastPromise] = null;
  14412. iterator[kLastResolve] = null;
  14413. iterator[kLastReject] = null;
  14414. resolve(createIterResult(data, false));
  14415. } else {
  14416. iterator[kLastResolve] = resolve;
  14417. iterator[kLastReject] = reject;
  14418. }
  14419. },
  14420. writable: true
  14421. }), _Object$create));
  14422. iterator[kLastPromise] = null;
  14423. finished(stream, function (err) {
  14424. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  14425. var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
  14426. // returned by next() and store the error
  14427. if (reject !== null) {
  14428. iterator[kLastPromise] = null;
  14429. iterator[kLastResolve] = null;
  14430. iterator[kLastReject] = null;
  14431. reject(err);
  14432. }
  14433. iterator[kError] = err;
  14434. return;
  14435. }
  14436. var resolve = iterator[kLastResolve];
  14437. if (resolve !== null) {
  14438. iterator[kLastPromise] = null;
  14439. iterator[kLastResolve] = null;
  14440. iterator[kLastReject] = null;
  14441. resolve(createIterResult(undefined, true));
  14442. }
  14443. iterator[kEnded] = true;
  14444. });
  14445. stream.on('readable', onReadable.bind(null, iterator));
  14446. return iterator;
  14447. };
  14448. module.exports = createReadableStreamAsyncIterator;
  14449. }).call(this)}).call(this,require('_process'))
  14450. },{"./end-of-stream":64,"_process":50}],62:[function(require,module,exports){
  14451. 'use strict';
  14452. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  14453. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  14454. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  14455. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14456. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  14457. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  14458. var _require = require('buffer'),
  14459. Buffer = _require.Buffer;
  14460. var _require2 = require('util'),
  14461. inspect = _require2.inspect;
  14462. var custom = inspect && inspect.custom || 'inspect';
  14463. function copyBuffer(src, target, offset) {
  14464. Buffer.prototype.copy.call(src, target, offset);
  14465. }
  14466. module.exports =
  14467. /*#__PURE__*/
  14468. function () {
  14469. function BufferList() {
  14470. _classCallCheck(this, BufferList);
  14471. this.head = null;
  14472. this.tail = null;
  14473. this.length = 0;
  14474. }
  14475. _createClass(BufferList, [{
  14476. key: "push",
  14477. value: function push(v) {
  14478. var entry = {
  14479. data: v,
  14480. next: null
  14481. };
  14482. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  14483. this.tail = entry;
  14484. ++this.length;
  14485. }
  14486. }, {
  14487. key: "unshift",
  14488. value: function unshift(v) {
  14489. var entry = {
  14490. data: v,
  14491. next: this.head
  14492. };
  14493. if (this.length === 0) this.tail = entry;
  14494. this.head = entry;
  14495. ++this.length;
  14496. }
  14497. }, {
  14498. key: "shift",
  14499. value: function shift() {
  14500. if (this.length === 0) return;
  14501. var ret = this.head.data;
  14502. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  14503. --this.length;
  14504. return ret;
  14505. }
  14506. }, {
  14507. key: "clear",
  14508. value: function clear() {
  14509. this.head = this.tail = null;
  14510. this.length = 0;
  14511. }
  14512. }, {
  14513. key: "join",
  14514. value: function join(s) {
  14515. if (this.length === 0) return '';
  14516. var p = this.head;
  14517. var ret = '' + p.data;
  14518. while (p = p.next) {
  14519. ret += s + p.data;
  14520. }
  14521. return ret;
  14522. }
  14523. }, {
  14524. key: "concat",
  14525. value: function concat(n) {
  14526. if (this.length === 0) return Buffer.alloc(0);
  14527. var ret = Buffer.allocUnsafe(n >>> 0);
  14528. var p = this.head;
  14529. var i = 0;
  14530. while (p) {
  14531. copyBuffer(p.data, ret, i);
  14532. i += p.data.length;
  14533. p = p.next;
  14534. }
  14535. return ret;
  14536. } // Consumes a specified amount of bytes or characters from the buffered data.
  14537. }, {
  14538. key: "consume",
  14539. value: function consume(n, hasStrings) {
  14540. var ret;
  14541. if (n < this.head.data.length) {
  14542. // `slice` is the same for buffers and strings.
  14543. ret = this.head.data.slice(0, n);
  14544. this.head.data = this.head.data.slice(n);
  14545. } else if (n === this.head.data.length) {
  14546. // First chunk is a perfect match.
  14547. ret = this.shift();
  14548. } else {
  14549. // Result spans more than one buffer.
  14550. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  14551. }
  14552. return ret;
  14553. }
  14554. }, {
  14555. key: "first",
  14556. value: function first() {
  14557. return this.head.data;
  14558. } // Consumes a specified amount of characters from the buffered data.
  14559. }, {
  14560. key: "_getString",
  14561. value: function _getString(n) {
  14562. var p = this.head;
  14563. var c = 1;
  14564. var ret = p.data;
  14565. n -= ret.length;
  14566. while (p = p.next) {
  14567. var str = p.data;
  14568. var nb = n > str.length ? str.length : n;
  14569. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  14570. n -= nb;
  14571. if (n === 0) {
  14572. if (nb === str.length) {
  14573. ++c;
  14574. if (p.next) this.head = p.next;else this.head = this.tail = null;
  14575. } else {
  14576. this.head = p;
  14577. p.data = str.slice(nb);
  14578. }
  14579. break;
  14580. }
  14581. ++c;
  14582. }
  14583. this.length -= c;
  14584. return ret;
  14585. } // Consumes a specified amount of bytes from the buffered data.
  14586. }, {
  14587. key: "_getBuffer",
  14588. value: function _getBuffer(n) {
  14589. var ret = Buffer.allocUnsafe(n);
  14590. var p = this.head;
  14591. var c = 1;
  14592. p.data.copy(ret);
  14593. n -= p.data.length;
  14594. while (p = p.next) {
  14595. var buf = p.data;
  14596. var nb = n > buf.length ? buf.length : n;
  14597. buf.copy(ret, ret.length - n, 0, nb);
  14598. n -= nb;
  14599. if (n === 0) {
  14600. if (nb === buf.length) {
  14601. ++c;
  14602. if (p.next) this.head = p.next;else this.head = this.tail = null;
  14603. } else {
  14604. this.head = p;
  14605. p.data = buf.slice(nb);
  14606. }
  14607. break;
  14608. }
  14609. ++c;
  14610. }
  14611. this.length -= c;
  14612. return ret;
  14613. } // Make sure the linked list only shows the minimal necessary information.
  14614. }, {
  14615. key: custom,
  14616. value: function value(_, options) {
  14617. return inspect(this, _objectSpread({}, options, {
  14618. // Only inspect one level.
  14619. depth: 0,
  14620. // It should not recurse.
  14621. customInspect: false
  14622. }));
  14623. }
  14624. }]);
  14625. return BufferList;
  14626. }();
  14627. },{"buffer":17,"util":16}],63:[function(require,module,exports){
  14628. (function (process){(function (){
  14629. 'use strict'; // undocumented cb() API, needed for core, not for public API
  14630. function destroy(err, cb) {
  14631. var _this = this;
  14632. var readableDestroyed = this._readableState && this._readableState.destroyed;
  14633. var writableDestroyed = this._writableState && this._writableState.destroyed;
  14634. if (readableDestroyed || writableDestroyed) {
  14635. if (cb) {
  14636. cb(err);
  14637. } else if (err) {
  14638. if (!this._writableState) {
  14639. process.nextTick(emitErrorNT, this, err);
  14640. } else if (!this._writableState.errorEmitted) {
  14641. this._writableState.errorEmitted = true;
  14642. process.nextTick(emitErrorNT, this, err);
  14643. }
  14644. }
  14645. return this;
  14646. } // we set destroyed to true before firing error callbacks in order
  14647. // to make it re-entrance safe in case destroy() is called within callbacks
  14648. if (this._readableState) {
  14649. this._readableState.destroyed = true;
  14650. } // if this is a duplex stream mark the writable part as destroyed as well
  14651. if (this._writableState) {
  14652. this._writableState.destroyed = true;
  14653. }
  14654. this._destroy(err || null, function (err) {
  14655. if (!cb && err) {
  14656. if (!_this._writableState) {
  14657. process.nextTick(emitErrorAndCloseNT, _this, err);
  14658. } else if (!_this._writableState.errorEmitted) {
  14659. _this._writableState.errorEmitted = true;
  14660. process.nextTick(emitErrorAndCloseNT, _this, err);
  14661. } else {
  14662. process.nextTick(emitCloseNT, _this);
  14663. }
  14664. } else if (cb) {
  14665. process.nextTick(emitCloseNT, _this);
  14666. cb(err);
  14667. } else {
  14668. process.nextTick(emitCloseNT, _this);
  14669. }
  14670. });
  14671. return this;
  14672. }
  14673. function emitErrorAndCloseNT(self, err) {
  14674. emitErrorNT(self, err);
  14675. emitCloseNT(self);
  14676. }
  14677. function emitCloseNT(self) {
  14678. if (self._writableState && !self._writableState.emitClose) return;
  14679. if (self._readableState && !self._readableState.emitClose) return;
  14680. self.emit('close');
  14681. }
  14682. function undestroy() {
  14683. if (this._readableState) {
  14684. this._readableState.destroyed = false;
  14685. this._readableState.reading = false;
  14686. this._readableState.ended = false;
  14687. this._readableState.endEmitted = false;
  14688. }
  14689. if (this._writableState) {
  14690. this._writableState.destroyed = false;
  14691. this._writableState.ended = false;
  14692. this._writableState.ending = false;
  14693. this._writableState.finalCalled = false;
  14694. this._writableState.prefinished = false;
  14695. this._writableState.finished = false;
  14696. this._writableState.errorEmitted = false;
  14697. }
  14698. }
  14699. function emitErrorNT(self, err) {
  14700. self.emit('error', err);
  14701. }
  14702. function errorOrDestroy(stream, err) {
  14703. // We have tests that rely on errors being emitted
  14704. // in the same tick, so changing this is semver major.
  14705. // For now when you opt-in to autoDestroy we allow
  14706. // the error to be emitted nextTick. In a future
  14707. // semver major update we should change the default to this.
  14708. var rState = stream._readableState;
  14709. var wState = stream._writableState;
  14710. if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
  14711. }
  14712. module.exports = {
  14713. destroy: destroy,
  14714. undestroy: undestroy,
  14715. errorOrDestroy: errorOrDestroy
  14716. };
  14717. }).call(this)}).call(this,require('_process'))
  14718. },{"_process":50}],64:[function(require,module,exports){
  14719. // Ported from https://github.com/mafintosh/end-of-stream with
  14720. // permission from the author, Mathias Buus (@mafintosh).
  14721. 'use strict';
  14722. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  14723. function once(callback) {
  14724. var called = false;
  14725. return function () {
  14726. if (called) return;
  14727. called = true;
  14728. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  14729. args[_key] = arguments[_key];
  14730. }
  14731. callback.apply(this, args);
  14732. };
  14733. }
  14734. function noop() {}
  14735. function isRequest(stream) {
  14736. return stream.setHeader && typeof stream.abort === 'function';
  14737. }
  14738. function eos(stream, opts, callback) {
  14739. if (typeof opts === 'function') return eos(stream, null, opts);
  14740. if (!opts) opts = {};
  14741. callback = once(callback || noop);
  14742. var readable = opts.readable || opts.readable !== false && stream.readable;
  14743. var writable = opts.writable || opts.writable !== false && stream.writable;
  14744. var onlegacyfinish = function onlegacyfinish() {
  14745. if (!stream.writable) onfinish();
  14746. };
  14747. var writableEnded = stream._writableState && stream._writableState.finished;
  14748. var onfinish = function onfinish() {
  14749. writable = false;
  14750. writableEnded = true;
  14751. if (!readable) callback.call(stream);
  14752. };
  14753. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  14754. var onend = function onend() {
  14755. readable = false;
  14756. readableEnded = true;
  14757. if (!writable) callback.call(stream);
  14758. };
  14759. var onerror = function onerror(err) {
  14760. callback.call(stream, err);
  14761. };
  14762. var onclose = function onclose() {
  14763. var err;
  14764. if (readable && !readableEnded) {
  14765. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  14766. return callback.call(stream, err);
  14767. }
  14768. if (writable && !writableEnded) {
  14769. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  14770. return callback.call(stream, err);
  14771. }
  14772. };
  14773. var onrequest = function onrequest() {
  14774. stream.req.on('finish', onfinish);
  14775. };
  14776. if (isRequest(stream)) {
  14777. stream.on('complete', onfinish);
  14778. stream.on('abort', onclose);
  14779. if (stream.req) onrequest();else stream.on('request', onrequest);
  14780. } else if (writable && !stream._writableState) {
  14781. // legacy streams
  14782. stream.on('end', onlegacyfinish);
  14783. stream.on('close', onlegacyfinish);
  14784. }
  14785. stream.on('end', onend);
  14786. stream.on('finish', onfinish);
  14787. if (opts.error !== false) stream.on('error', onerror);
  14788. stream.on('close', onclose);
  14789. return function () {
  14790. stream.removeListener('complete', onfinish);
  14791. stream.removeListener('abort', onclose);
  14792. stream.removeListener('request', onrequest);
  14793. if (stream.req) stream.req.removeListener('finish', onfinish);
  14794. stream.removeListener('end', onlegacyfinish);
  14795. stream.removeListener('close', onlegacyfinish);
  14796. stream.removeListener('finish', onfinish);
  14797. stream.removeListener('end', onend);
  14798. stream.removeListener('error', onerror);
  14799. stream.removeListener('close', onclose);
  14800. };
  14801. }
  14802. module.exports = eos;
  14803. },{"../../../errors":55}],65:[function(require,module,exports){
  14804. module.exports = function () {
  14805. throw new Error('Readable.from is not available in the browser')
  14806. };
  14807. },{}],66:[function(require,module,exports){
  14808. // Ported from https://github.com/mafintosh/pump with
  14809. // permission from the author, Mathias Buus (@mafintosh).
  14810. 'use strict';
  14811. var eos;
  14812. function once(callback) {
  14813. var called = false;
  14814. return function () {
  14815. if (called) return;
  14816. called = true;
  14817. callback.apply(void 0, arguments);
  14818. };
  14819. }
  14820. var _require$codes = require('../../../errors').codes,
  14821. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  14822. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  14823. function noop(err) {
  14824. // Rethrow the error if it exists to avoid swallowing it
  14825. if (err) throw err;
  14826. }
  14827. function isRequest(stream) {
  14828. return stream.setHeader && typeof stream.abort === 'function';
  14829. }
  14830. function destroyer(stream, reading, writing, callback) {
  14831. callback = once(callback);
  14832. var closed = false;
  14833. stream.on('close', function () {
  14834. closed = true;
  14835. });
  14836. if (eos === undefined) eos = require('./end-of-stream');
  14837. eos(stream, {
  14838. readable: reading,
  14839. writable: writing
  14840. }, function (err) {
  14841. if (err) return callback(err);
  14842. closed = true;
  14843. callback();
  14844. });
  14845. var destroyed = false;
  14846. return function (err) {
  14847. if (closed) return;
  14848. if (destroyed) return;
  14849. destroyed = true; // request.destroy just do .end - .abort is what we want
  14850. if (isRequest(stream)) return stream.abort();
  14851. if (typeof stream.destroy === 'function') return stream.destroy();
  14852. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  14853. };
  14854. }
  14855. function call(fn) {
  14856. fn();
  14857. }
  14858. function pipe(from, to) {
  14859. return from.pipe(to);
  14860. }
  14861. function popCallback(streams) {
  14862. if (!streams.length) return noop;
  14863. if (typeof streams[streams.length - 1] !== 'function') return noop;
  14864. return streams.pop();
  14865. }
  14866. function pipeline() {
  14867. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  14868. streams[_key] = arguments[_key];
  14869. }
  14870. var callback = popCallback(streams);
  14871. if (Array.isArray(streams[0])) streams = streams[0];
  14872. if (streams.length < 2) {
  14873. throw new ERR_MISSING_ARGS('streams');
  14874. }
  14875. var error;
  14876. var destroys = streams.map(function (stream, i) {
  14877. var reading = i < streams.length - 1;
  14878. var writing = i > 0;
  14879. return destroyer(stream, reading, writing, function (err) {
  14880. if (!error) error = err;
  14881. if (err) destroys.forEach(call);
  14882. if (reading) return;
  14883. destroys.forEach(call);
  14884. callback(error);
  14885. });
  14886. });
  14887. return streams.reduce(pipe);
  14888. }
  14889. module.exports = pipeline;
  14890. },{"../../../errors":55,"./end-of-stream":64}],67:[function(require,module,exports){
  14891. 'use strict';
  14892. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  14893. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  14894. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  14895. }
  14896. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  14897. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  14898. if (hwm != null) {
  14899. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  14900. var name = isDuplex ? duplexKey : 'highWaterMark';
  14901. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  14902. }
  14903. return Math.floor(hwm);
  14904. } // Default value
  14905. return state.objectMode ? 16 : 16 * 1024;
  14906. }
  14907. module.exports = {
  14908. getHighWaterMark: getHighWaterMark
  14909. };
  14910. },{"../../../errors":55}],68:[function(require,module,exports){
  14911. module.exports = require('events').EventEmitter;
  14912. },{"events":22}],69:[function(require,module,exports){
  14913. exports = module.exports = require('./lib/_stream_readable.js');
  14914. exports.Stream = exports;
  14915. exports.Readable = exports;
  14916. exports.Writable = require('./lib/_stream_writable.js');
  14917. exports.Duplex = require('./lib/_stream_duplex.js');
  14918. exports.Transform = require('./lib/_stream_transform.js');
  14919. exports.PassThrough = require('./lib/_stream_passthrough.js');
  14920. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  14921. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  14922. },{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(require,module,exports){
  14923. 'use strict'
  14924. function ReInterval (callback, interval, args) {
  14925. var self = this;
  14926. this._callback = callback;
  14927. this._args = args;
  14928. this._interval = setInterval(callback, interval, this._args);
  14929. this.reschedule = function (interval) {
  14930. // if no interval entered, use the interval passed in on creation
  14931. if (!interval)
  14932. interval = self._interval;
  14933. if (self._interval)
  14934. clearInterval(self._interval);
  14935. self._interval = setInterval(self._callback, interval, self._args);
  14936. };
  14937. this.clear = function () {
  14938. if (self._interval) {
  14939. clearInterval(self._interval);
  14940. self._interval = undefined;
  14941. }
  14942. };
  14943. this.destroy = function () {
  14944. if (self._interval) {
  14945. clearInterval(self._interval);
  14946. }
  14947. self._callback = undefined;
  14948. self._interval = undefined;
  14949. self._args = undefined;
  14950. };
  14951. }
  14952. function reInterval () {
  14953. if (typeof arguments[0] !== 'function')
  14954. throw new Error('callback needed');
  14955. if (typeof arguments[1] !== 'number')
  14956. throw new Error('interval needed');
  14957. var args;
  14958. if (arguments.length > 0) {
  14959. args = new Array(arguments.length - 2);
  14960. for (var i = 0; i < args.length; i++) {
  14961. args[i] = arguments[i + 2];
  14962. }
  14963. }
  14964. return new ReInterval(arguments[0], arguments[1], args);
  14965. }
  14966. module.exports = reInterval;
  14967. },{}],71:[function(require,module,exports){
  14968. 'use strict'
  14969. module.exports = require('./index.js')()
  14970. },{"./index.js":72}],72:[function(require,module,exports){
  14971. (function (Buffer){(function (){
  14972. 'use strict'
  14973. module.exports = rfdc
  14974. function copyBuffer (cur) {
  14975. if (cur instanceof Buffer) {
  14976. return Buffer.from(cur)
  14977. }
  14978. return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length)
  14979. }
  14980. function rfdc (opts) {
  14981. opts = opts || {}
  14982. if (opts.circles) return rfdcCircles(opts)
  14983. return opts.proto ? cloneProto : clone
  14984. function cloneArray (a, fn) {
  14985. var keys = Object.keys(a)
  14986. var a2 = new Array(keys.length)
  14987. for (var i = 0; i < keys.length; i++) {
  14988. var k = keys[i]
  14989. var cur = a[k]
  14990. if (typeof cur !== 'object' || cur === null) {
  14991. a2[k] = cur
  14992. } else if (cur instanceof Date) {
  14993. a2[k] = new Date(cur)
  14994. } else if (ArrayBuffer.isView(cur)) {
  14995. a2[k] = copyBuffer(cur)
  14996. } else {
  14997. a2[k] = fn(cur)
  14998. }
  14999. }
  15000. return a2
  15001. }
  15002. function clone (o) {
  15003. if (typeof o !== 'object' || o === null) return o
  15004. if (o instanceof Date) return new Date(o)
  15005. if (Array.isArray(o)) return cloneArray(o, clone)
  15006. if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone))
  15007. if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone))
  15008. var o2 = {}
  15009. for (var k in o) {
  15010. if (Object.hasOwnProperty.call(o, k) === false) continue
  15011. var cur = o[k]
  15012. if (typeof cur !== 'object' || cur === null) {
  15013. o2[k] = cur
  15014. } else if (cur instanceof Date) {
  15015. o2[k] = new Date(cur)
  15016. } else if (cur instanceof Map) {
  15017. o2[k] = new Map(cloneArray(Array.from(cur), clone))
  15018. } else if (cur instanceof Set) {
  15019. o2[k] = new Set(cloneArray(Array.from(cur), clone))
  15020. } else if (ArrayBuffer.isView(cur)) {
  15021. o2[k] = copyBuffer(cur)
  15022. } else {
  15023. o2[k] = clone(cur)
  15024. }
  15025. }
  15026. return o2
  15027. }
  15028. function cloneProto (o) {
  15029. if (typeof o !== 'object' || o === null) return o
  15030. if (o instanceof Date) return new Date(o)
  15031. if (Array.isArray(o)) return cloneArray(o, cloneProto)
  15032. if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto))
  15033. if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto))
  15034. var o2 = {}
  15035. for (var k in o) {
  15036. var cur = o[k]
  15037. if (typeof cur !== 'object' || cur === null) {
  15038. o2[k] = cur
  15039. } else if (cur instanceof Date) {
  15040. o2[k] = new Date(cur)
  15041. } else if (cur instanceof Map) {
  15042. o2[k] = new Map(cloneArray(Array.from(cur), cloneProto))
  15043. } else if (cur instanceof Set) {
  15044. o2[k] = new Set(cloneArray(Array.from(cur), cloneProto))
  15045. } else if (ArrayBuffer.isView(cur)) {
  15046. o2[k] = copyBuffer(cur)
  15047. } else {
  15048. o2[k] = cloneProto(cur)
  15049. }
  15050. }
  15051. return o2
  15052. }
  15053. }
  15054. function rfdcCircles (opts) {
  15055. var refs = []
  15056. var refsNew = []
  15057. return opts.proto ? cloneProto : clone
  15058. function cloneArray (a, fn) {
  15059. var keys = Object.keys(a)
  15060. var a2 = new Array(keys.length)
  15061. for (var i = 0; i < keys.length; i++) {
  15062. var k = keys[i]
  15063. var cur = a[k]
  15064. if (typeof cur !== 'object' || cur === null) {
  15065. a2[k] = cur
  15066. } else if (cur instanceof Date) {
  15067. a2[k] = new Date(cur)
  15068. } else if (ArrayBuffer.isView(cur)) {
  15069. a2[k] = copyBuffer(cur)
  15070. } else {
  15071. var index = refs.indexOf(cur)
  15072. if (index !== -1) {
  15073. a2[k] = refsNew[index]
  15074. } else {
  15075. a2[k] = fn(cur)
  15076. }
  15077. }
  15078. }
  15079. return a2
  15080. }
  15081. function clone (o) {
  15082. if (typeof o !== 'object' || o === null) return o
  15083. if (o instanceof Date) return new Date(o)
  15084. if (Array.isArray(o)) return cloneArray(o, clone)
  15085. if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone))
  15086. if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone))
  15087. var o2 = {}
  15088. refs.push(o)
  15089. refsNew.push(o2)
  15090. for (var k in o) {
  15091. if (Object.hasOwnProperty.call(o, k) === false) continue
  15092. var cur = o[k]
  15093. if (typeof cur !== 'object' || cur === null) {
  15094. o2[k] = cur
  15095. } else if (cur instanceof Date) {
  15096. o2[k] = new Date(cur)
  15097. } else if (cur instanceof Map) {
  15098. o2[k] = new Map(cloneArray(Array.from(cur), clone))
  15099. } else if (cur instanceof Set) {
  15100. o2[k] = new Set(cloneArray(Array.from(cur), clone))
  15101. } else if (ArrayBuffer.isView(cur)) {
  15102. o2[k] = copyBuffer(cur)
  15103. } else {
  15104. var i = refs.indexOf(cur)
  15105. if (i !== -1) {
  15106. o2[k] = refsNew[i]
  15107. } else {
  15108. o2[k] = clone(cur)
  15109. }
  15110. }
  15111. }
  15112. refs.pop()
  15113. refsNew.pop()
  15114. return o2
  15115. }
  15116. function cloneProto (o) {
  15117. if (typeof o !== 'object' || o === null) return o
  15118. if (o instanceof Date) return new Date(o)
  15119. if (Array.isArray(o)) return cloneArray(o, cloneProto)
  15120. if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto))
  15121. if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto))
  15122. var o2 = {}
  15123. refs.push(o)
  15124. refsNew.push(o2)
  15125. for (var k in o) {
  15126. var cur = o[k]
  15127. if (typeof cur !== 'object' || cur === null) {
  15128. o2[k] = cur
  15129. } else if (cur instanceof Date) {
  15130. o2[k] = new Date(cur)
  15131. } else if (cur instanceof Map) {
  15132. o2[k] = new Map(cloneArray(Array.from(cur), cloneProto))
  15133. } else if (cur instanceof Set) {
  15134. o2[k] = new Set(cloneArray(Array.from(cur), cloneProto))
  15135. } else if (ArrayBuffer.isView(cur)) {
  15136. o2[k] = copyBuffer(cur)
  15137. } else {
  15138. var i = refs.indexOf(cur)
  15139. if (i !== -1) {
  15140. o2[k] = refsNew[i]
  15141. } else {
  15142. o2[k] = cloneProto(cur)
  15143. }
  15144. }
  15145. }
  15146. refs.pop()
  15147. refsNew.pop()
  15148. return o2
  15149. }
  15150. }
  15151. }).call(this)}).call(this,require("buffer").Buffer)
  15152. },{"buffer":17}],73:[function(require,module,exports){
  15153. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  15154. /* eslint-disable node/no-deprecated-api */
  15155. var buffer = require('buffer')
  15156. var Buffer = buffer.Buffer
  15157. // alternative to using Object.keys for old browsers
  15158. function copyProps (src, dst) {
  15159. for (var key in src) {
  15160. dst[key] = src[key]
  15161. }
  15162. }
  15163. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  15164. module.exports = buffer
  15165. } else {
  15166. // Copy properties from require('buffer')
  15167. copyProps(buffer, exports)
  15168. exports.Buffer = SafeBuffer
  15169. }
  15170. function SafeBuffer (arg, encodingOrOffset, length) {
  15171. return Buffer(arg, encodingOrOffset, length)
  15172. }
  15173. SafeBuffer.prototype = Object.create(Buffer.prototype)
  15174. // Copy static methods from Buffer
  15175. copyProps(Buffer, SafeBuffer)
  15176. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  15177. if (typeof arg === 'number') {
  15178. throw new TypeError('Argument must not be a number')
  15179. }
  15180. return Buffer(arg, encodingOrOffset, length)
  15181. }
  15182. SafeBuffer.alloc = function (size, fill, encoding) {
  15183. if (typeof size !== 'number') {
  15184. throw new TypeError('Argument must be a number')
  15185. }
  15186. var buf = Buffer(size)
  15187. if (fill !== undefined) {
  15188. if (typeof encoding === 'string') {
  15189. buf.fill(fill, encoding)
  15190. } else {
  15191. buf.fill(fill)
  15192. }
  15193. } else {
  15194. buf.fill(0)
  15195. }
  15196. return buf
  15197. }
  15198. SafeBuffer.allocUnsafe = function (size) {
  15199. if (typeof size !== 'number') {
  15200. throw new TypeError('Argument must be a number')
  15201. }
  15202. return Buffer(size)
  15203. }
  15204. SafeBuffer.allocUnsafeSlow = function (size) {
  15205. if (typeof size !== 'number') {
  15206. throw new TypeError('Argument must be a number')
  15207. }
  15208. return buffer.SlowBuffer(size)
  15209. }
  15210. },{"buffer":17}],74:[function(require,module,exports){
  15211. module.exports = shift
  15212. function shift (stream) {
  15213. var rs = stream._readableState
  15214. if (!rs) return null
  15215. return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs))
  15216. }
  15217. function getStateLength (state) {
  15218. if (state.buffer.length) {
  15219. // Since node 6.3.0 state.buffer is a BufferList not an array
  15220. if (state.buffer.head) {
  15221. return state.buffer.head.data.length
  15222. }
  15223. return state.buffer[0].length
  15224. }
  15225. return state.length
  15226. }
  15227. },{}],75:[function(require,module,exports){
  15228. // Copyright Joyent, Inc. and other Node contributors.
  15229. //
  15230. // Permission is hereby granted, free of charge, to any person obtaining a
  15231. // copy of this software and associated documentation files (the
  15232. // "Software"), to deal in the Software without restriction, including
  15233. // without limitation the rights to use, copy, modify, merge, publish,
  15234. // distribute, sublicense, and/or sell copies of the Software, and to permit
  15235. // persons to whom the Software is furnished to do so, subject to the
  15236. // following conditions:
  15237. //
  15238. // The above copyright notice and this permission notice shall be included
  15239. // in all copies or substantial portions of the Software.
  15240. //
  15241. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15242. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15243. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  15244. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15245. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15246. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  15247. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  15248. 'use strict';
  15249. /*<replacement>*/
  15250. var Buffer = require('safe-buffer').Buffer;
  15251. /*</replacement>*/
  15252. var isEncoding = Buffer.isEncoding || function (encoding) {
  15253. encoding = '' + encoding;
  15254. switch (encoding && encoding.toLowerCase()) {
  15255. 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':
  15256. return true;
  15257. default:
  15258. return false;
  15259. }
  15260. };
  15261. function _normalizeEncoding(enc) {
  15262. if (!enc) return 'utf8';
  15263. var retried;
  15264. while (true) {
  15265. switch (enc) {
  15266. case 'utf8':
  15267. case 'utf-8':
  15268. return 'utf8';
  15269. case 'ucs2':
  15270. case 'ucs-2':
  15271. case 'utf16le':
  15272. case 'utf-16le':
  15273. return 'utf16le';
  15274. case 'latin1':
  15275. case 'binary':
  15276. return 'latin1';
  15277. case 'base64':
  15278. case 'ascii':
  15279. case 'hex':
  15280. return enc;
  15281. default:
  15282. if (retried) return; // undefined
  15283. enc = ('' + enc).toLowerCase();
  15284. retried = true;
  15285. }
  15286. }
  15287. };
  15288. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  15289. // modules monkey-patch it to support additional encodings
  15290. function normalizeEncoding(enc) {
  15291. var nenc = _normalizeEncoding(enc);
  15292. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  15293. return nenc || enc;
  15294. }
  15295. // StringDecoder provides an interface for efficiently splitting a series of
  15296. // buffers into a series of JS strings without breaking apart multi-byte
  15297. // characters.
  15298. exports.StringDecoder = StringDecoder;
  15299. function StringDecoder(encoding) {
  15300. this.encoding = normalizeEncoding(encoding);
  15301. var nb;
  15302. switch (this.encoding) {
  15303. case 'utf16le':
  15304. this.text = utf16Text;
  15305. this.end = utf16End;
  15306. nb = 4;
  15307. break;
  15308. case 'utf8':
  15309. this.fillLast = utf8FillLast;
  15310. nb = 4;
  15311. break;
  15312. case 'base64':
  15313. this.text = base64Text;
  15314. this.end = base64End;
  15315. nb = 3;
  15316. break;
  15317. default:
  15318. this.write = simpleWrite;
  15319. this.end = simpleEnd;
  15320. return;
  15321. }
  15322. this.lastNeed = 0;
  15323. this.lastTotal = 0;
  15324. this.lastChar = Buffer.allocUnsafe(nb);
  15325. }
  15326. StringDecoder.prototype.write = function (buf) {
  15327. if (buf.length === 0) return '';
  15328. var r;
  15329. var i;
  15330. if (this.lastNeed) {
  15331. r = this.fillLast(buf);
  15332. if (r === undefined) return '';
  15333. i = this.lastNeed;
  15334. this.lastNeed = 0;
  15335. } else {
  15336. i = 0;
  15337. }
  15338. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  15339. return r || '';
  15340. };
  15341. StringDecoder.prototype.end = utf8End;
  15342. // Returns only complete characters in a Buffer
  15343. StringDecoder.prototype.text = utf8Text;
  15344. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  15345. StringDecoder.prototype.fillLast = function (buf) {
  15346. if (this.lastNeed <= buf.length) {
  15347. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  15348. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  15349. }
  15350. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  15351. this.lastNeed -= buf.length;
  15352. };
  15353. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  15354. // continuation byte. If an invalid byte is detected, -2 is returned.
  15355. function utf8CheckByte(byte) {
  15356. 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;
  15357. return byte >> 6 === 0x02 ? -1 : -2;
  15358. }
  15359. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  15360. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  15361. // needed to complete the UTF-8 character (if applicable) are returned.
  15362. function utf8CheckIncomplete(self, buf, i) {
  15363. var j = buf.length - 1;
  15364. if (j < i) return 0;
  15365. var nb = utf8CheckByte(buf[j]);
  15366. if (nb >= 0) {
  15367. if (nb > 0) self.lastNeed = nb - 1;
  15368. return nb;
  15369. }
  15370. if (--j < i || nb === -2) return 0;
  15371. nb = utf8CheckByte(buf[j]);
  15372. if (nb >= 0) {
  15373. if (nb > 0) self.lastNeed = nb - 2;
  15374. return nb;
  15375. }
  15376. if (--j < i || nb === -2) return 0;
  15377. nb = utf8CheckByte(buf[j]);
  15378. if (nb >= 0) {
  15379. if (nb > 0) {
  15380. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  15381. }
  15382. return nb;
  15383. }
  15384. return 0;
  15385. }
  15386. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  15387. // needed or are available. If we see a non-continuation byte where we expect
  15388. // one, we "replace" the validated continuation bytes we've seen so far with
  15389. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  15390. // behavior. The continuation byte check is included three times in the case
  15391. // where all of the continuation bytes for a character exist in the same buffer.
  15392. // It is also done this way as a slight performance increase instead of using a
  15393. // loop.
  15394. function utf8CheckExtraBytes(self, buf, p) {
  15395. if ((buf[0] & 0xC0) !== 0x80) {
  15396. self.lastNeed = 0;
  15397. return '\ufffd';
  15398. }
  15399. if (self.lastNeed > 1 && buf.length > 1) {
  15400. if ((buf[1] & 0xC0) !== 0x80) {
  15401. self.lastNeed = 1;
  15402. return '\ufffd';
  15403. }
  15404. if (self.lastNeed > 2 && buf.length > 2) {
  15405. if ((buf[2] & 0xC0) !== 0x80) {
  15406. self.lastNeed = 2;
  15407. return '\ufffd';
  15408. }
  15409. }
  15410. }
  15411. }
  15412. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  15413. function utf8FillLast(buf) {
  15414. var p = this.lastTotal - this.lastNeed;
  15415. var r = utf8CheckExtraBytes(this, buf, p);
  15416. if (r !== undefined) return r;
  15417. if (this.lastNeed <= buf.length) {
  15418. buf.copy(this.lastChar, p, 0, this.lastNeed);
  15419. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  15420. }
  15421. buf.copy(this.lastChar, p, 0, buf.length);
  15422. this.lastNeed -= buf.length;
  15423. }
  15424. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  15425. // partial character, the character's bytes are buffered until the required
  15426. // number of bytes are available.
  15427. function utf8Text(buf, i) {
  15428. var total = utf8CheckIncomplete(this, buf, i);
  15429. if (!this.lastNeed) return buf.toString('utf8', i);
  15430. this.lastTotal = total;
  15431. var end = buf.length - (total - this.lastNeed);
  15432. buf.copy(this.lastChar, 0, end);
  15433. return buf.toString('utf8', i, end);
  15434. }
  15435. // For UTF-8, a replacement character is added when ending on a partial
  15436. // character.
  15437. function utf8End(buf) {
  15438. var r = buf && buf.length ? this.write(buf) : '';
  15439. if (this.lastNeed) return r + '\ufffd';
  15440. return r;
  15441. }
  15442. // UTF-16LE typically needs two bytes per character, but even if we have an even
  15443. // number of bytes available, we need to check if we end on a leading/high
  15444. // surrogate. In that case, we need to wait for the next two bytes in order to
  15445. // decode the last character properly.
  15446. function utf16Text(buf, i) {
  15447. if ((buf.length - i) % 2 === 0) {
  15448. var r = buf.toString('utf16le', i);
  15449. if (r) {
  15450. var c = r.charCodeAt(r.length - 1);
  15451. if (c >= 0xD800 && c <= 0xDBFF) {
  15452. this.lastNeed = 2;
  15453. this.lastTotal = 4;
  15454. this.lastChar[0] = buf[buf.length - 2];
  15455. this.lastChar[1] = buf[buf.length - 1];
  15456. return r.slice(0, -1);
  15457. }
  15458. }
  15459. return r;
  15460. }
  15461. this.lastNeed = 1;
  15462. this.lastTotal = 2;
  15463. this.lastChar[0] = buf[buf.length - 1];
  15464. return buf.toString('utf16le', i, buf.length - 1);
  15465. }
  15466. // For UTF-16LE we do not explicitly append special replacement characters if we
  15467. // end on a partial character, we simply let v8 handle that.
  15468. function utf16End(buf) {
  15469. var r = buf && buf.length ? this.write(buf) : '';
  15470. if (this.lastNeed) {
  15471. var end = this.lastTotal - this.lastNeed;
  15472. return r + this.lastChar.toString('utf16le', 0, end);
  15473. }
  15474. return r;
  15475. }
  15476. function base64Text(buf, i) {
  15477. var n = (buf.length - i) % 3;
  15478. if (n === 0) return buf.toString('base64', i);
  15479. this.lastNeed = 3 - n;
  15480. this.lastTotal = 3;
  15481. if (n === 1) {
  15482. this.lastChar[0] = buf[buf.length - 1];
  15483. } else {
  15484. this.lastChar[0] = buf[buf.length - 2];
  15485. this.lastChar[1] = buf[buf.length - 1];
  15486. }
  15487. return buf.toString('base64', i, buf.length - n);
  15488. }
  15489. function base64End(buf) {
  15490. var r = buf && buf.length ? this.write(buf) : '';
  15491. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  15492. return r;
  15493. }
  15494. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  15495. function simpleWrite(buf) {
  15496. return buf.toString(this.encoding);
  15497. }
  15498. function simpleEnd(buf) {
  15499. return buf && buf.length ? this.write(buf) : '';
  15500. }
  15501. },{"safe-buffer":73}],76:[function(require,module,exports){
  15502. // Copyright Joyent, Inc. and other Node contributors.
  15503. //
  15504. // Permission is hereby granted, free of charge, to any person obtaining a
  15505. // copy of this software and associated documentation files (the
  15506. // "Software"), to deal in the Software without restriction, including
  15507. // without limitation the rights to use, copy, modify, merge, publish,
  15508. // distribute, sublicense, and/or sell copies of the Software, and to permit
  15509. // persons to whom the Software is furnished to do so, subject to the
  15510. // following conditions:
  15511. //
  15512. // The above copyright notice and this permission notice shall be included
  15513. // in all copies or substantial portions of the Software.
  15514. //
  15515. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15516. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15517. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  15518. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15519. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15520. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  15521. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  15522. 'use strict';
  15523. var punycode = require('punycode');
  15524. var util = require('./util');
  15525. exports.parse = urlParse;
  15526. exports.resolve = urlResolve;
  15527. exports.resolveObject = urlResolveObject;
  15528. exports.format = urlFormat;
  15529. exports.Url = Url;
  15530. function Url() {
  15531. this.protocol = null;
  15532. this.slashes = null;
  15533. this.auth = null;
  15534. this.host = null;
  15535. this.port = null;
  15536. this.hostname = null;
  15537. this.hash = null;
  15538. this.search = null;
  15539. this.query = null;
  15540. this.pathname = null;
  15541. this.path = null;
  15542. this.href = null;
  15543. }
  15544. // Reference: RFC 3986, RFC 1808, RFC 2396
  15545. // define these here so at least they only have to be
  15546. // compiled once on the first module load.
  15547. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  15548. portPattern = /:[0-9]*$/,
  15549. // Special case for a simple path URL
  15550. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  15551. // RFC 2396: characters reserved for delimiting URLs.
  15552. // We actually just auto-escape these.
  15553. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  15554. // RFC 2396: characters not allowed for various reasons.
  15555. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  15556. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  15557. autoEscape = ['\''].concat(unwise),
  15558. // Characters that are never ever allowed in a hostname.
  15559. // Note that any invalid chars are also handled, but these
  15560. // are the ones that are *expected* to be seen, so we fast-path
  15561. // them.
  15562. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  15563. hostEndingChars = ['/', '?', '#'],
  15564. hostnameMaxLen = 255,
  15565. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  15566. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  15567. // protocols that can allow "unsafe" and "unwise" chars.
  15568. unsafeProtocol = {
  15569. 'javascript': true,
  15570. 'javascript:': true
  15571. },
  15572. // protocols that never have a hostname.
  15573. hostlessProtocol = {
  15574. 'javascript': true,
  15575. 'javascript:': true
  15576. },
  15577. // protocols that always contain a // bit.
  15578. slashedProtocol = {
  15579. 'http': true,
  15580. 'https': true,
  15581. 'ftp': true,
  15582. 'gopher': true,
  15583. 'file': true,
  15584. 'http:': true,
  15585. 'https:': true,
  15586. 'ftp:': true,
  15587. 'gopher:': true,
  15588. 'file:': true
  15589. },
  15590. querystring = require('querystring');
  15591. function urlParse(url, parseQueryString, slashesDenoteHost) {
  15592. if (url && util.isObject(url) && url instanceof Url) return url;
  15593. var u = new Url;
  15594. u.parse(url, parseQueryString, slashesDenoteHost);
  15595. return u;
  15596. }
  15597. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  15598. if (!util.isString(url)) {
  15599. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  15600. }
  15601. // Copy chrome, IE, opera backslash-handling behavior.
  15602. // Back slashes before the query string get converted to forward slashes
  15603. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  15604. var queryIndex = url.indexOf('?'),
  15605. splitter =
  15606. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  15607. uSplit = url.split(splitter),
  15608. slashRegex = /\\/g;
  15609. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  15610. url = uSplit.join(splitter);
  15611. var rest = url;
  15612. // trim before proceeding.
  15613. // This is to support parse stuff like " http://foo.com \n"
  15614. rest = rest.trim();
  15615. if (!slashesDenoteHost && url.split('#').length === 1) {
  15616. // Try fast path regexp
  15617. var simplePath = simplePathPattern.exec(rest);
  15618. if (simplePath) {
  15619. this.path = rest;
  15620. this.href = rest;
  15621. this.pathname = simplePath[1];
  15622. if (simplePath[2]) {
  15623. this.search = simplePath[2];
  15624. if (parseQueryString) {
  15625. this.query = querystring.parse(this.search.substr(1));
  15626. } else {
  15627. this.query = this.search.substr(1);
  15628. }
  15629. } else if (parseQueryString) {
  15630. this.search = '';
  15631. this.query = {};
  15632. }
  15633. return this;
  15634. }
  15635. }
  15636. var proto = protocolPattern.exec(rest);
  15637. if (proto) {
  15638. proto = proto[0];
  15639. var lowerProto = proto.toLowerCase();
  15640. this.protocol = lowerProto;
  15641. rest = rest.substr(proto.length);
  15642. }
  15643. // figure out if it's got a host
  15644. // user@server is *always* interpreted as a hostname, and url
  15645. // resolution will treat //foo/bar as host=foo,path=bar because that's
  15646. // how the browser resolves relative URLs.
  15647. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  15648. var slashes = rest.substr(0, 2) === '//';
  15649. if (slashes && !(proto && hostlessProtocol[proto])) {
  15650. rest = rest.substr(2);
  15651. this.slashes = true;
  15652. }
  15653. }
  15654. if (!hostlessProtocol[proto] &&
  15655. (slashes || (proto && !slashedProtocol[proto]))) {
  15656. // there's a hostname.
  15657. // the first instance of /, ?, ;, or # ends the host.
  15658. //
  15659. // If there is an @ in the hostname, then non-host chars *are* allowed
  15660. // to the left of the last @ sign, unless some host-ending character
  15661. // comes *before* the @-sign.
  15662. // URLs are obnoxious.
  15663. //
  15664. // ex:
  15665. // http://a@b@c/ => user:a@b host:c
  15666. // http://a@b?@c => user:a host:c path:/?@c
  15667. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  15668. // Review our test case against browsers more comprehensively.
  15669. // find the first instance of any hostEndingChars
  15670. var hostEnd = -1;
  15671. for (var i = 0; i < hostEndingChars.length; i++) {
  15672. var hec = rest.indexOf(hostEndingChars[i]);
  15673. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  15674. hostEnd = hec;
  15675. }
  15676. // at this point, either we have an explicit point where the
  15677. // auth portion cannot go past, or the last @ char is the decider.
  15678. var auth, atSign;
  15679. if (hostEnd === -1) {
  15680. // atSign can be anywhere.
  15681. atSign = rest.lastIndexOf('@');
  15682. } else {
  15683. // atSign must be in auth portion.
  15684. // http://a@b/c@d => host:b auth:a path:/c@d
  15685. atSign = rest.lastIndexOf('@', hostEnd);
  15686. }
  15687. // Now we have a portion which is definitely the auth.
  15688. // Pull that off.
  15689. if (atSign !== -1) {
  15690. auth = rest.slice(0, atSign);
  15691. rest = rest.slice(atSign + 1);
  15692. this.auth = decodeURIComponent(auth);
  15693. }
  15694. // the host is the remaining to the left of the first non-host char
  15695. hostEnd = -1;
  15696. for (var i = 0; i < nonHostChars.length; i++) {
  15697. var hec = rest.indexOf(nonHostChars[i]);
  15698. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  15699. hostEnd = hec;
  15700. }
  15701. // if we still have not hit it, then the entire thing is a host.
  15702. if (hostEnd === -1)
  15703. hostEnd = rest.length;
  15704. this.host = rest.slice(0, hostEnd);
  15705. rest = rest.slice(hostEnd);
  15706. // pull out port.
  15707. this.parseHost();
  15708. // we've indicated that there is a hostname,
  15709. // so even if it's empty, it has to be present.
  15710. this.hostname = this.hostname || '';
  15711. // if hostname begins with [ and ends with ]
  15712. // assume that it's an IPv6 address.
  15713. var ipv6Hostname = this.hostname[0] === '[' &&
  15714. this.hostname[this.hostname.length - 1] === ']';
  15715. // validate a little.
  15716. if (!ipv6Hostname) {
  15717. var hostparts = this.hostname.split(/\./);
  15718. for (var i = 0, l = hostparts.length; i < l; i++) {
  15719. var part = hostparts[i];
  15720. if (!part) continue;
  15721. if (!part.match(hostnamePartPattern)) {
  15722. var newpart = '';
  15723. for (var j = 0, k = part.length; j < k; j++) {
  15724. if (part.charCodeAt(j) > 127) {
  15725. // we replace non-ASCII char with a temporary placeholder
  15726. // we need this to make sure size of hostname is not
  15727. // broken by replacing non-ASCII by nothing
  15728. newpart += 'x';
  15729. } else {
  15730. newpart += part[j];
  15731. }
  15732. }
  15733. // we test again with ASCII char only
  15734. if (!newpart.match(hostnamePartPattern)) {
  15735. var validParts = hostparts.slice(0, i);
  15736. var notHost = hostparts.slice(i + 1);
  15737. var bit = part.match(hostnamePartStart);
  15738. if (bit) {
  15739. validParts.push(bit[1]);
  15740. notHost.unshift(bit[2]);
  15741. }
  15742. if (notHost.length) {
  15743. rest = '/' + notHost.join('.') + rest;
  15744. }
  15745. this.hostname = validParts.join('.');
  15746. break;
  15747. }
  15748. }
  15749. }
  15750. }
  15751. if (this.hostname.length > hostnameMaxLen) {
  15752. this.hostname = '';
  15753. } else {
  15754. // hostnames are always lower case.
  15755. this.hostname = this.hostname.toLowerCase();
  15756. }
  15757. if (!ipv6Hostname) {
  15758. // IDNA Support: Returns a punycoded representation of "domain".
  15759. // It only converts parts of the domain name that
  15760. // have non-ASCII characters, i.e. it doesn't matter if
  15761. // you call it with a domain that already is ASCII-only.
  15762. this.hostname = punycode.toASCII(this.hostname);
  15763. }
  15764. var p = this.port ? ':' + this.port : '';
  15765. var h = this.hostname || '';
  15766. this.host = h + p;
  15767. this.href += this.host;
  15768. // strip [ and ] from the hostname
  15769. // the host field still retains them, though
  15770. if (ipv6Hostname) {
  15771. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  15772. if (rest[0] !== '/') {
  15773. rest = '/' + rest;
  15774. }
  15775. }
  15776. }
  15777. // now rest is set to the post-host stuff.
  15778. // chop off any delim chars.
  15779. if (!unsafeProtocol[lowerProto]) {
  15780. // First, make 100% sure that any "autoEscape" chars get
  15781. // escaped, even if encodeURIComponent doesn't think they
  15782. // need to be.
  15783. for (var i = 0, l = autoEscape.length; i < l; i++) {
  15784. var ae = autoEscape[i];
  15785. if (rest.indexOf(ae) === -1)
  15786. continue;
  15787. var esc = encodeURIComponent(ae);
  15788. if (esc === ae) {
  15789. esc = escape(ae);
  15790. }
  15791. rest = rest.split(ae).join(esc);
  15792. }
  15793. }
  15794. // chop off from the tail first.
  15795. var hash = rest.indexOf('#');
  15796. if (hash !== -1) {
  15797. // got a fragment string.
  15798. this.hash = rest.substr(hash);
  15799. rest = rest.slice(0, hash);
  15800. }
  15801. var qm = rest.indexOf('?');
  15802. if (qm !== -1) {
  15803. this.search = rest.substr(qm);
  15804. this.query = rest.substr(qm + 1);
  15805. if (parseQueryString) {
  15806. this.query = querystring.parse(this.query);
  15807. }
  15808. rest = rest.slice(0, qm);
  15809. } else if (parseQueryString) {
  15810. // no query string, but parseQueryString still requested
  15811. this.search = '';
  15812. this.query = {};
  15813. }
  15814. if (rest) this.pathname = rest;
  15815. if (slashedProtocol[lowerProto] &&
  15816. this.hostname && !this.pathname) {
  15817. this.pathname = '/';
  15818. }
  15819. //to support http.request
  15820. if (this.pathname || this.search) {
  15821. var p = this.pathname || '';
  15822. var s = this.search || '';
  15823. this.path = p + s;
  15824. }
  15825. // finally, reconstruct the href based on what has been validated.
  15826. this.href = this.format();
  15827. return this;
  15828. };
  15829. // format a parsed object into a url string
  15830. function urlFormat(obj) {
  15831. // ensure it's an object, and not a string url.
  15832. // If it's an obj, this is a no-op.
  15833. // this way, you can call url_format() on strings
  15834. // to clean up potentially wonky urls.
  15835. if (util.isString(obj)) obj = urlParse(obj);
  15836. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  15837. return obj.format();
  15838. }
  15839. Url.prototype.format = function() {
  15840. var auth = this.auth || '';
  15841. if (auth) {
  15842. auth = encodeURIComponent(auth);
  15843. auth = auth.replace(/%3A/i, ':');
  15844. auth += '@';
  15845. }
  15846. var protocol = this.protocol || '',
  15847. pathname = this.pathname || '',
  15848. hash = this.hash || '',
  15849. host = false,
  15850. query = '';
  15851. if (this.host) {
  15852. host = auth + this.host;
  15853. } else if (this.hostname) {
  15854. host = auth + (this.hostname.indexOf(':') === -1 ?
  15855. this.hostname :
  15856. '[' + this.hostname + ']');
  15857. if (this.port) {
  15858. host += ':' + this.port;
  15859. }
  15860. }
  15861. if (this.query &&
  15862. util.isObject(this.query) &&
  15863. Object.keys(this.query).length) {
  15864. query = querystring.stringify(this.query);
  15865. }
  15866. var search = this.search || (query && ('?' + query)) || '';
  15867. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  15868. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  15869. // unless they had them to begin with.
  15870. if (this.slashes ||
  15871. (!protocol || slashedProtocol[protocol]) && host !== false) {
  15872. host = '//' + (host || '');
  15873. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  15874. } else if (!host) {
  15875. host = '';
  15876. }
  15877. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  15878. if (search && search.charAt(0) !== '?') search = '?' + search;
  15879. pathname = pathname.replace(/[?#]/g, function(match) {
  15880. return encodeURIComponent(match);
  15881. });
  15882. search = search.replace('#', '%23');
  15883. return protocol + host + pathname + search + hash;
  15884. };
  15885. function urlResolve(source, relative) {
  15886. return urlParse(source, false, true).resolve(relative);
  15887. }
  15888. Url.prototype.resolve = function(relative) {
  15889. return this.resolveObject(urlParse(relative, false, true)).format();
  15890. };
  15891. function urlResolveObject(source, relative) {
  15892. if (!source) return relative;
  15893. return urlParse(source, false, true).resolveObject(relative);
  15894. }
  15895. Url.prototype.resolveObject = function(relative) {
  15896. if (util.isString(relative)) {
  15897. var rel = new Url();
  15898. rel.parse(relative, false, true);
  15899. relative = rel;
  15900. }
  15901. var result = new Url();
  15902. var tkeys = Object.keys(this);
  15903. for (var tk = 0; tk < tkeys.length; tk++) {
  15904. var tkey = tkeys[tk];
  15905. result[tkey] = this[tkey];
  15906. }
  15907. // hash is always overridden, no matter what.
  15908. // even href="" will remove it.
  15909. result.hash = relative.hash;
  15910. // if the relative url is empty, then there's nothing left to do here.
  15911. if (relative.href === '') {
  15912. result.href = result.format();
  15913. return result;
  15914. }
  15915. // hrefs like //foo/bar always cut to the protocol.
  15916. if (relative.slashes && !relative.protocol) {
  15917. // take everything except the protocol from relative
  15918. var rkeys = Object.keys(relative);
  15919. for (var rk = 0; rk < rkeys.length; rk++) {
  15920. var rkey = rkeys[rk];
  15921. if (rkey !== 'protocol')
  15922. result[rkey] = relative[rkey];
  15923. }
  15924. //urlParse appends trailing / to urls like http://www.example.com
  15925. if (slashedProtocol[result.protocol] &&
  15926. result.hostname && !result.pathname) {
  15927. result.path = result.pathname = '/';
  15928. }
  15929. result.href = result.format();
  15930. return result;
  15931. }
  15932. if (relative.protocol && relative.protocol !== result.protocol) {
  15933. // if it's a known url protocol, then changing
  15934. // the protocol does weird things
  15935. // first, if it's not file:, then we MUST have a host,
  15936. // and if there was a path
  15937. // to begin with, then we MUST have a path.
  15938. // if it is file:, then the host is dropped,
  15939. // because that's known to be hostless.
  15940. // anything else is assumed to be absolute.
  15941. if (!slashedProtocol[relative.protocol]) {
  15942. var keys = Object.keys(relative);
  15943. for (var v = 0; v < keys.length; v++) {
  15944. var k = keys[v];
  15945. result[k] = relative[k];
  15946. }
  15947. result.href = result.format();
  15948. return result;
  15949. }
  15950. result.protocol = relative.protocol;
  15951. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  15952. var relPath = (relative.pathname || '').split('/');
  15953. while (relPath.length && !(relative.host = relPath.shift()));
  15954. if (!relative.host) relative.host = '';
  15955. if (!relative.hostname) relative.hostname = '';
  15956. if (relPath[0] !== '') relPath.unshift('');
  15957. if (relPath.length < 2) relPath.unshift('');
  15958. result.pathname = relPath.join('/');
  15959. } else {
  15960. result.pathname = relative.pathname;
  15961. }
  15962. result.search = relative.search;
  15963. result.query = relative.query;
  15964. result.host = relative.host || '';
  15965. result.auth = relative.auth;
  15966. result.hostname = relative.hostname || relative.host;
  15967. result.port = relative.port;
  15968. // to support http.request
  15969. if (result.pathname || result.search) {
  15970. var p = result.pathname || '';
  15971. var s = result.search || '';
  15972. result.path = p + s;
  15973. }
  15974. result.slashes = result.slashes || relative.slashes;
  15975. result.href = result.format();
  15976. return result;
  15977. }
  15978. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  15979. isRelAbs = (
  15980. relative.host ||
  15981. relative.pathname && relative.pathname.charAt(0) === '/'
  15982. ),
  15983. mustEndAbs = (isRelAbs || isSourceAbs ||
  15984. (result.host && relative.pathname)),
  15985. removeAllDots = mustEndAbs,
  15986. srcPath = result.pathname && result.pathname.split('/') || [],
  15987. relPath = relative.pathname && relative.pathname.split('/') || [],
  15988. psychotic = result.protocol && !slashedProtocol[result.protocol];
  15989. // if the url is a non-slashed url, then relative
  15990. // links like ../.. should be able
  15991. // to crawl up to the hostname, as well. This is strange.
  15992. // result.protocol has already been set by now.
  15993. // Later on, put the first path part into the host field.
  15994. if (psychotic) {
  15995. result.hostname = '';
  15996. result.port = null;
  15997. if (result.host) {
  15998. if (srcPath[0] === '') srcPath[0] = result.host;
  15999. else srcPath.unshift(result.host);
  16000. }
  16001. result.host = '';
  16002. if (relative.protocol) {
  16003. relative.hostname = null;
  16004. relative.port = null;
  16005. if (relative.host) {
  16006. if (relPath[0] === '') relPath[0] = relative.host;
  16007. else relPath.unshift(relative.host);
  16008. }
  16009. relative.host = null;
  16010. }
  16011. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  16012. }
  16013. if (isRelAbs) {
  16014. // it's absolute.
  16015. result.host = (relative.host || relative.host === '') ?
  16016. relative.host : result.host;
  16017. result.hostname = (relative.hostname || relative.hostname === '') ?
  16018. relative.hostname : result.hostname;
  16019. result.search = relative.search;
  16020. result.query = relative.query;
  16021. srcPath = relPath;
  16022. // fall through to the dot-handling below.
  16023. } else if (relPath.length) {
  16024. // it's relative
  16025. // throw away the existing file, and take the new path instead.
  16026. if (!srcPath) srcPath = [];
  16027. srcPath.pop();
  16028. srcPath = srcPath.concat(relPath);
  16029. result.search = relative.search;
  16030. result.query = relative.query;
  16031. } else if (!util.isNullOrUndefined(relative.search)) {
  16032. // just pull out the search.
  16033. // like href='?foo'.
  16034. // Put this after the other two cases because it simplifies the booleans
  16035. if (psychotic) {
  16036. result.hostname = result.host = srcPath.shift();
  16037. //occationaly the auth can get stuck only in host
  16038. //this especially happens in cases like
  16039. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  16040. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  16041. result.host.split('@') : false;
  16042. if (authInHost) {
  16043. result.auth = authInHost.shift();
  16044. result.host = result.hostname = authInHost.shift();
  16045. }
  16046. }
  16047. result.search = relative.search;
  16048. result.query = relative.query;
  16049. //to support http.request
  16050. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  16051. result.path = (result.pathname ? result.pathname : '') +
  16052. (result.search ? result.search : '');
  16053. }
  16054. result.href = result.format();
  16055. return result;
  16056. }
  16057. if (!srcPath.length) {
  16058. // no path at all. easy.
  16059. // we've already handled the other stuff above.
  16060. result.pathname = null;
  16061. //to support http.request
  16062. if (result.search) {
  16063. result.path = '/' + result.search;
  16064. } else {
  16065. result.path = null;
  16066. }
  16067. result.href = result.format();
  16068. return result;
  16069. }
  16070. // if a url ENDs in . or .., then it must get a trailing slash.
  16071. // however, if it ends in anything else non-slashy,
  16072. // then it must NOT get a trailing slash.
  16073. var last = srcPath.slice(-1)[0];
  16074. var hasTrailingSlash = (
  16075. (result.host || relative.host || srcPath.length > 1) &&
  16076. (last === '.' || last === '..') || last === '');
  16077. // strip single dots, resolve double dots to parent dir
  16078. // if the path tries to go above the root, `up` ends up > 0
  16079. var up = 0;
  16080. for (var i = srcPath.length; i >= 0; i--) {
  16081. last = srcPath[i];
  16082. if (last === '.') {
  16083. srcPath.splice(i, 1);
  16084. } else if (last === '..') {
  16085. srcPath.splice(i, 1);
  16086. up++;
  16087. } else if (up) {
  16088. srcPath.splice(i, 1);
  16089. up--;
  16090. }
  16091. }
  16092. // if the path is allowed to go above the root, restore leading ..s
  16093. if (!mustEndAbs && !removeAllDots) {
  16094. for (; up--; up) {
  16095. srcPath.unshift('..');
  16096. }
  16097. }
  16098. if (mustEndAbs && srcPath[0] !== '' &&
  16099. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  16100. srcPath.unshift('');
  16101. }
  16102. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  16103. srcPath.push('');
  16104. }
  16105. var isAbsolute = srcPath[0] === '' ||
  16106. (srcPath[0] && srcPath[0].charAt(0) === '/');
  16107. // put the host back
  16108. if (psychotic) {
  16109. result.hostname = result.host = isAbsolute ? '' :
  16110. srcPath.length ? srcPath.shift() : '';
  16111. //occationaly the auth can get stuck only in host
  16112. //this especially happens in cases like
  16113. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  16114. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  16115. result.host.split('@') : false;
  16116. if (authInHost) {
  16117. result.auth = authInHost.shift();
  16118. result.host = result.hostname = authInHost.shift();
  16119. }
  16120. }
  16121. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  16122. if (mustEndAbs && !isAbsolute) {
  16123. srcPath.unshift('');
  16124. }
  16125. if (!srcPath.length) {
  16126. result.pathname = null;
  16127. result.path = null;
  16128. } else {
  16129. result.pathname = srcPath.join('/');
  16130. }
  16131. //to support request.http
  16132. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  16133. result.path = (result.pathname ? result.pathname : '') +
  16134. (result.search ? result.search : '');
  16135. }
  16136. result.auth = relative.auth || result.auth;
  16137. result.slashes = result.slashes || relative.slashes;
  16138. result.href = result.format();
  16139. return result;
  16140. };
  16141. Url.prototype.parseHost = function() {
  16142. var host = this.host;
  16143. var port = portPattern.exec(host);
  16144. if (port) {
  16145. port = port[0];
  16146. if (port !== ':') {
  16147. this.port = port.substr(1);
  16148. }
  16149. host = host.substr(0, host.length - port.length);
  16150. }
  16151. if (host) this.hostname = host;
  16152. };
  16153. },{"./util":77,"punycode":51,"querystring":54}],77:[function(require,module,exports){
  16154. 'use strict';
  16155. module.exports = {
  16156. isString: function(arg) {
  16157. return typeof(arg) === 'string';
  16158. },
  16159. isObject: function(arg) {
  16160. return typeof(arg) === 'object' && arg !== null;
  16161. },
  16162. isNull: function(arg) {
  16163. return arg === null;
  16164. },
  16165. isNullOrUndefined: function(arg) {
  16166. return arg == null;
  16167. }
  16168. };
  16169. },{}],78:[function(require,module,exports){
  16170. (function (global){(function (){
  16171. /**
  16172. * Module exports.
  16173. */
  16174. module.exports = deprecate;
  16175. /**
  16176. * Mark that a method should not be used.
  16177. * Returns a modified function which warns once by default.
  16178. *
  16179. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  16180. *
  16181. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  16182. * will throw an Error when invoked.
  16183. *
  16184. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  16185. * will invoke `console.trace()` instead of `console.error()`.
  16186. *
  16187. * @param {Function} fn - the function to deprecate
  16188. * @param {String} msg - the string to print to the console when `fn` is invoked
  16189. * @returns {Function} a new "deprecated" version of `fn`
  16190. * @api public
  16191. */
  16192. function deprecate (fn, msg) {
  16193. if (config('noDeprecation')) {
  16194. return fn;
  16195. }
  16196. var warned = false;
  16197. function deprecated() {
  16198. if (!warned) {
  16199. if (config('throwDeprecation')) {
  16200. throw new Error(msg);
  16201. } else if (config('traceDeprecation')) {
  16202. console.trace(msg);
  16203. } else {
  16204. console.warn(msg);
  16205. }
  16206. warned = true;
  16207. }
  16208. return fn.apply(this, arguments);
  16209. }
  16210. return deprecated;
  16211. }
  16212. /**
  16213. * Checks `localStorage` for boolean values for the given `name`.
  16214. *
  16215. * @param {String} name
  16216. * @returns {Boolean}
  16217. * @api private
  16218. */
  16219. function config (name) {
  16220. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  16221. try {
  16222. if (!global.localStorage) return false;
  16223. } catch (_) {
  16224. return false;
  16225. }
  16226. var val = global.localStorage[name];
  16227. if (null == val) return false;
  16228. return String(val).toLowerCase() === 'true';
  16229. }
  16230. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  16231. },{}],79:[function(require,module,exports){
  16232. // Returns a wrapper function that returns a wrapped callback
  16233. // The wrapper function should do some stuff, and return a
  16234. // presumably different callback function.
  16235. // This makes sure that own properties are retained, so that
  16236. // decorations and such are not lost along the way.
  16237. module.exports = wrappy
  16238. function wrappy (fn, cb) {
  16239. if (fn && cb) return wrappy(fn)(cb)
  16240. if (typeof fn !== 'function')
  16241. throw new TypeError('need wrapper function')
  16242. Object.keys(fn).forEach(function (k) {
  16243. wrapper[k] = fn[k]
  16244. })
  16245. return wrapper
  16246. function wrapper() {
  16247. var args = new Array(arguments.length)
  16248. for (var i = 0; i < args.length; i++) {
  16249. args[i] = arguments[i]
  16250. }
  16251. var ret = fn.apply(this, args)
  16252. var cb = args[args.length-1]
  16253. if (typeof ret === 'function' && ret !== cb) {
  16254. Object.keys(cb).forEach(function (k) {
  16255. ret[k] = cb[k]
  16256. })
  16257. }
  16258. return ret
  16259. }
  16260. }
  16261. },{}],80:[function(require,module,exports){
  16262. 'use strict';
  16263. module.exports = function () {
  16264. throw new Error(
  16265. 'ws does not work in the browser. Browser clients must use the native ' +
  16266. 'WebSocket object'
  16267. );
  16268. };
  16269. },{}],81:[function(require,module,exports){
  16270. module.exports = extend
  16271. var hasOwnProperty = Object.prototype.hasOwnProperty;
  16272. function extend() {
  16273. var target = {}
  16274. for (var i = 0; i < arguments.length; i++) {
  16275. var source = arguments[i]
  16276. for (var key in source) {
  16277. if (hasOwnProperty.call(source, key)) {
  16278. target[key] = source[key]
  16279. }
  16280. }
  16281. }
  16282. return target
  16283. }
  16284. },{}],82:[function(require,module,exports){
  16285. 'use strict'
  16286. module.exports = function (Yallist) {
  16287. Yallist.prototype[Symbol.iterator] = function* () {
  16288. for (let walker = this.head; walker; walker = walker.next) {
  16289. yield walker.value
  16290. }
  16291. }
  16292. }
  16293. },{}],83:[function(require,module,exports){
  16294. 'use strict'
  16295. module.exports = Yallist
  16296. Yallist.Node = Node
  16297. Yallist.create = Yallist
  16298. function Yallist (list) {
  16299. var self = this
  16300. if (!(self instanceof Yallist)) {
  16301. self = new Yallist()
  16302. }
  16303. self.tail = null
  16304. self.head = null
  16305. self.length = 0
  16306. if (list && typeof list.forEach === 'function') {
  16307. list.forEach(function (item) {
  16308. self.push(item)
  16309. })
  16310. } else if (arguments.length > 0) {
  16311. for (var i = 0, l = arguments.length; i < l; i++) {
  16312. self.push(arguments[i])
  16313. }
  16314. }
  16315. return self
  16316. }
  16317. Yallist.prototype.removeNode = function (node) {
  16318. if (node.list !== this) {
  16319. throw new Error('removing node which does not belong to this list')
  16320. }
  16321. var next = node.next
  16322. var prev = node.prev
  16323. if (next) {
  16324. next.prev = prev
  16325. }
  16326. if (prev) {
  16327. prev.next = next
  16328. }
  16329. if (node === this.head) {
  16330. this.head = next
  16331. }
  16332. if (node === this.tail) {
  16333. this.tail = prev
  16334. }
  16335. node.list.length--
  16336. node.next = null
  16337. node.prev = null
  16338. node.list = null
  16339. return next
  16340. }
  16341. Yallist.prototype.unshiftNode = function (node) {
  16342. if (node === this.head) {
  16343. return
  16344. }
  16345. if (node.list) {
  16346. node.list.removeNode(node)
  16347. }
  16348. var head = this.head
  16349. node.list = this
  16350. node.next = head
  16351. if (head) {
  16352. head.prev = node
  16353. }
  16354. this.head = node
  16355. if (!this.tail) {
  16356. this.tail = node
  16357. }
  16358. this.length++
  16359. }
  16360. Yallist.prototype.pushNode = function (node) {
  16361. if (node === this.tail) {
  16362. return
  16363. }
  16364. if (node.list) {
  16365. node.list.removeNode(node)
  16366. }
  16367. var tail = this.tail
  16368. node.list = this
  16369. node.prev = tail
  16370. if (tail) {
  16371. tail.next = node
  16372. }
  16373. this.tail = node
  16374. if (!this.head) {
  16375. this.head = node
  16376. }
  16377. this.length++
  16378. }
  16379. Yallist.prototype.push = function () {
  16380. for (var i = 0, l = arguments.length; i < l; i++) {
  16381. push(this, arguments[i])
  16382. }
  16383. return this.length
  16384. }
  16385. Yallist.prototype.unshift = function () {
  16386. for (var i = 0, l = arguments.length; i < l; i++) {
  16387. unshift(this, arguments[i])
  16388. }
  16389. return this.length
  16390. }
  16391. Yallist.prototype.pop = function () {
  16392. if (!this.tail) {
  16393. return undefined
  16394. }
  16395. var res = this.tail.value
  16396. this.tail = this.tail.prev
  16397. if (this.tail) {
  16398. this.tail.next = null
  16399. } else {
  16400. this.head = null
  16401. }
  16402. this.length--
  16403. return res
  16404. }
  16405. Yallist.prototype.shift = function () {
  16406. if (!this.head) {
  16407. return undefined
  16408. }
  16409. var res = this.head.value
  16410. this.head = this.head.next
  16411. if (this.head) {
  16412. this.head.prev = null
  16413. } else {
  16414. this.tail = null
  16415. }
  16416. this.length--
  16417. return res
  16418. }
  16419. Yallist.prototype.forEach = function (fn, thisp) {
  16420. thisp = thisp || this
  16421. for (var walker = this.head, i = 0; walker !== null; i++) {
  16422. fn.call(thisp, walker.value, i, this)
  16423. walker = walker.next
  16424. }
  16425. }
  16426. Yallist.prototype.forEachReverse = function (fn, thisp) {
  16427. thisp = thisp || this
  16428. for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
  16429. fn.call(thisp, walker.value, i, this)
  16430. walker = walker.prev
  16431. }
  16432. }
  16433. Yallist.prototype.get = function (n) {
  16434. for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
  16435. // abort out of the list early if we hit a cycle
  16436. walker = walker.next
  16437. }
  16438. if (i === n && walker !== null) {
  16439. return walker.value
  16440. }
  16441. }
  16442. Yallist.prototype.getReverse = function (n) {
  16443. for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
  16444. // abort out of the list early if we hit a cycle
  16445. walker = walker.prev
  16446. }
  16447. if (i === n && walker !== null) {
  16448. return walker.value
  16449. }
  16450. }
  16451. Yallist.prototype.map = function (fn, thisp) {
  16452. thisp = thisp || this
  16453. var res = new Yallist()
  16454. for (var walker = this.head; walker !== null;) {
  16455. res.push(fn.call(thisp, walker.value, this))
  16456. walker = walker.next
  16457. }
  16458. return res
  16459. }
  16460. Yallist.prototype.mapReverse = function (fn, thisp) {
  16461. thisp = thisp || this
  16462. var res = new Yallist()
  16463. for (var walker = this.tail; walker !== null;) {
  16464. res.push(fn.call(thisp, walker.value, this))
  16465. walker = walker.prev
  16466. }
  16467. return res
  16468. }
  16469. Yallist.prototype.reduce = function (fn, initial) {
  16470. var acc
  16471. var walker = this.head
  16472. if (arguments.length > 1) {
  16473. acc = initial
  16474. } else if (this.head) {
  16475. walker = this.head.next
  16476. acc = this.head.value
  16477. } else {
  16478. throw new TypeError('Reduce of empty list with no initial value')
  16479. }
  16480. for (var i = 0; walker !== null; i++) {
  16481. acc = fn(acc, walker.value, i)
  16482. walker = walker.next
  16483. }
  16484. return acc
  16485. }
  16486. Yallist.prototype.reduceReverse = function (fn, initial) {
  16487. var acc
  16488. var walker = this.tail
  16489. if (arguments.length > 1) {
  16490. acc = initial
  16491. } else if (this.tail) {
  16492. walker = this.tail.prev
  16493. acc = this.tail.value
  16494. } else {
  16495. throw new TypeError('Reduce of empty list with no initial value')
  16496. }
  16497. for (var i = this.length - 1; walker !== null; i--) {
  16498. acc = fn(acc, walker.value, i)
  16499. walker = walker.prev
  16500. }
  16501. return acc
  16502. }
  16503. Yallist.prototype.toArray = function () {
  16504. var arr = new Array(this.length)
  16505. for (var i = 0, walker = this.head; walker !== null; i++) {
  16506. arr[i] = walker.value
  16507. walker = walker.next
  16508. }
  16509. return arr
  16510. }
  16511. Yallist.prototype.toArrayReverse = function () {
  16512. var arr = new Array(this.length)
  16513. for (var i = 0, walker = this.tail; walker !== null; i++) {
  16514. arr[i] = walker.value
  16515. walker = walker.prev
  16516. }
  16517. return arr
  16518. }
  16519. Yallist.prototype.slice = function (from, to) {
  16520. to = to || this.length
  16521. if (to < 0) {
  16522. to += this.length
  16523. }
  16524. from = from || 0
  16525. if (from < 0) {
  16526. from += this.length
  16527. }
  16528. var ret = new Yallist()
  16529. if (to < from || to < 0) {
  16530. return ret
  16531. }
  16532. if (from < 0) {
  16533. from = 0
  16534. }
  16535. if (to > this.length) {
  16536. to = this.length
  16537. }
  16538. for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
  16539. walker = walker.next
  16540. }
  16541. for (; walker !== null && i < to; i++, walker = walker.next) {
  16542. ret.push(walker.value)
  16543. }
  16544. return ret
  16545. }
  16546. Yallist.prototype.sliceReverse = function (from, to) {
  16547. to = to || this.length
  16548. if (to < 0) {
  16549. to += this.length
  16550. }
  16551. from = from || 0
  16552. if (from < 0) {
  16553. from += this.length
  16554. }
  16555. var ret = new Yallist()
  16556. if (to < from || to < 0) {
  16557. return ret
  16558. }
  16559. if (from < 0) {
  16560. from = 0
  16561. }
  16562. if (to > this.length) {
  16563. to = this.length
  16564. }
  16565. for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
  16566. walker = walker.prev
  16567. }
  16568. for (; walker !== null && i > from; i--, walker = walker.prev) {
  16569. ret.push(walker.value)
  16570. }
  16571. return ret
  16572. }
  16573. Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
  16574. if (start > this.length) {
  16575. start = this.length - 1
  16576. }
  16577. if (start < 0) {
  16578. start = this.length + start;
  16579. }
  16580. for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
  16581. walker = walker.next
  16582. }
  16583. var ret = []
  16584. for (var i = 0; walker && i < deleteCount; i++) {
  16585. ret.push(walker.value)
  16586. walker = this.removeNode(walker)
  16587. }
  16588. if (walker === null) {
  16589. walker = this.tail
  16590. }
  16591. if (walker !== this.head && walker !== this.tail) {
  16592. walker = walker.prev
  16593. }
  16594. for (var i = 0; i < nodes.length; i++) {
  16595. walker = insert(this, walker, nodes[i])
  16596. }
  16597. return ret;
  16598. }
  16599. Yallist.prototype.reverse = function () {
  16600. var head = this.head
  16601. var tail = this.tail
  16602. for (var walker = head; walker !== null; walker = walker.prev) {
  16603. var p = walker.prev
  16604. walker.prev = walker.next
  16605. walker.next = p
  16606. }
  16607. this.head = tail
  16608. this.tail = head
  16609. return this
  16610. }
  16611. function insert (self, node, value) {
  16612. var inserted = node === self.head ?
  16613. new Node(value, null, node, self) :
  16614. new Node(value, node, node.next, self)
  16615. if (inserted.next === null) {
  16616. self.tail = inserted
  16617. }
  16618. if (inserted.prev === null) {
  16619. self.head = inserted
  16620. }
  16621. self.length++
  16622. return inserted
  16623. }
  16624. function push (self, item) {
  16625. self.tail = new Node(item, self.tail, null, self)
  16626. if (!self.head) {
  16627. self.head = self.tail
  16628. }
  16629. self.length++
  16630. }
  16631. function unshift (self, item) {
  16632. self.head = new Node(item, null, self.head, self)
  16633. if (!self.tail) {
  16634. self.tail = self.head
  16635. }
  16636. self.length++
  16637. }
  16638. function Node (value, prev, next, list) {
  16639. if (!(this instanceof Node)) {
  16640. return new Node(value, prev, next, list)
  16641. }
  16642. this.list = list
  16643. this.value = value
  16644. if (prev) {
  16645. prev.next = this
  16646. this.prev = prev
  16647. } else {
  16648. this.prev = null
  16649. }
  16650. if (next) {
  16651. next.prev = this
  16652. this.next = next
  16653. } else {
  16654. this.next = null
  16655. }
  16656. }
  16657. try {
  16658. // add if support for Symbol.iterator is present
  16659. require('./iterator.js')(Yallist)
  16660. } catch (er) {}
  16661. },{"./iterator.js":82}]},{},[12])(12)
  16662. });