index.js 265 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551
  1. var csv_parse = (function (exports) {
  2. 'use strict';
  3. var global$1 = (typeof global !== "undefined" ? global :
  4. typeof self !== "undefined" ? self :
  5. typeof window !== "undefined" ? window : {});
  6. var lookup = [];
  7. var revLookup = [];
  8. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  9. var inited = false;
  10. function init () {
  11. inited = true;
  12. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  13. for (var i = 0, len = code.length; i < len; ++i) {
  14. lookup[i] = code[i];
  15. revLookup[code.charCodeAt(i)] = i;
  16. }
  17. revLookup['-'.charCodeAt(0)] = 62;
  18. revLookup['_'.charCodeAt(0)] = 63;
  19. }
  20. function toByteArray (b64) {
  21. if (!inited) {
  22. init();
  23. }
  24. var i, j, l, tmp, placeHolders, arr;
  25. var len = b64.length;
  26. if (len % 4 > 0) {
  27. throw new Error('Invalid string. Length must be a multiple of 4')
  28. }
  29. // the number of equal signs (place holders)
  30. // if there are two placeholders, than the two characters before it
  31. // represent one byte
  32. // if there is only one, then the three characters before it represent 2 bytes
  33. // this is just a cheap hack to not do indexOf twice
  34. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  35. // base64 is 4/3 + up to two characters of the original data
  36. arr = new Arr(len * 3 / 4 - placeHolders);
  37. // if there are placeholders, only get up to the last complete 4 chars
  38. l = placeHolders > 0 ? len - 4 : len;
  39. var L = 0;
  40. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  41. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  42. arr[L++] = (tmp >> 16) & 0xFF;
  43. arr[L++] = (tmp >> 8) & 0xFF;
  44. arr[L++] = tmp & 0xFF;
  45. }
  46. if (placeHolders === 2) {
  47. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  48. arr[L++] = tmp & 0xFF;
  49. } else if (placeHolders === 1) {
  50. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  51. arr[L++] = (tmp >> 8) & 0xFF;
  52. arr[L++] = tmp & 0xFF;
  53. }
  54. return arr
  55. }
  56. function tripletToBase64 (num) {
  57. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  58. }
  59. function encodeChunk (uint8, start, end) {
  60. var tmp;
  61. var output = [];
  62. for (var i = start; i < end; i += 3) {
  63. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  64. output.push(tripletToBase64(tmp));
  65. }
  66. return output.join('')
  67. }
  68. function fromByteArray (uint8) {
  69. if (!inited) {
  70. init();
  71. }
  72. var tmp;
  73. var len = uint8.length;
  74. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  75. var output = '';
  76. var parts = [];
  77. var maxChunkLength = 16383; // must be multiple of 3
  78. // go through the array every three bytes, we'll deal with trailing stuff later
  79. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  80. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  81. }
  82. // pad the end with zeros, but make sure to not forget the extra bytes
  83. if (extraBytes === 1) {
  84. tmp = uint8[len - 1];
  85. output += lookup[tmp >> 2];
  86. output += lookup[(tmp << 4) & 0x3F];
  87. output += '==';
  88. } else if (extraBytes === 2) {
  89. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  90. output += lookup[tmp >> 10];
  91. output += lookup[(tmp >> 4) & 0x3F];
  92. output += lookup[(tmp << 2) & 0x3F];
  93. output += '=';
  94. }
  95. parts.push(output);
  96. return parts.join('')
  97. }
  98. function read (buffer, offset, isLE, mLen, nBytes) {
  99. var e, m;
  100. var eLen = nBytes * 8 - mLen - 1;
  101. var eMax = (1 << eLen) - 1;
  102. var eBias = eMax >> 1;
  103. var nBits = -7;
  104. var i = isLE ? (nBytes - 1) : 0;
  105. var d = isLE ? -1 : 1;
  106. var s = buffer[offset + i];
  107. i += d;
  108. e = s & ((1 << (-nBits)) - 1);
  109. s >>= (-nBits);
  110. nBits += eLen;
  111. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  112. m = e & ((1 << (-nBits)) - 1);
  113. e >>= (-nBits);
  114. nBits += mLen;
  115. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  116. if (e === 0) {
  117. e = 1 - eBias;
  118. } else if (e === eMax) {
  119. return m ? NaN : ((s ? -1 : 1) * Infinity)
  120. } else {
  121. m = m + Math.pow(2, mLen);
  122. e = e - eBias;
  123. }
  124. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  125. }
  126. function write (buffer, value, offset, isLE, mLen, nBytes) {
  127. var e, m, c;
  128. var eLen = nBytes * 8 - mLen - 1;
  129. var eMax = (1 << eLen) - 1;
  130. var eBias = eMax >> 1;
  131. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  132. var i = isLE ? 0 : (nBytes - 1);
  133. var d = isLE ? 1 : -1;
  134. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  135. value = Math.abs(value);
  136. if (isNaN(value) || value === Infinity) {
  137. m = isNaN(value) ? 1 : 0;
  138. e = eMax;
  139. } else {
  140. e = Math.floor(Math.log(value) / Math.LN2);
  141. if (value * (c = Math.pow(2, -e)) < 1) {
  142. e--;
  143. c *= 2;
  144. }
  145. if (e + eBias >= 1) {
  146. value += rt / c;
  147. } else {
  148. value += rt * Math.pow(2, 1 - eBias);
  149. }
  150. if (value * c >= 2) {
  151. e++;
  152. c /= 2;
  153. }
  154. if (e + eBias >= eMax) {
  155. m = 0;
  156. e = eMax;
  157. } else if (e + eBias >= 1) {
  158. m = (value * c - 1) * Math.pow(2, mLen);
  159. e = e + eBias;
  160. } else {
  161. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  162. e = 0;
  163. }
  164. }
  165. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  166. e = (e << mLen) | m;
  167. eLen += mLen;
  168. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  169. buffer[offset + i - d] |= s * 128;
  170. }
  171. var toString = {}.toString;
  172. var isArray$1 = Array.isArray || function (arr) {
  173. return toString.call(arr) == '[object Array]';
  174. };
  175. var INSPECT_MAX_BYTES = 50;
  176. /**
  177. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  178. * === true Use Uint8Array implementation (fastest)
  179. * === false Use Object implementation (most compatible, even IE6)
  180. *
  181. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  182. * Opera 11.6+, iOS 4.2+.
  183. *
  184. * Due to various browser bugs, sometimes the Object implementation will be used even
  185. * when the browser supports typed arrays.
  186. *
  187. * Note:
  188. *
  189. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  190. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  191. *
  192. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  193. *
  194. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  195. * incorrect length in some situations.
  196. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  197. * get the Object implementation, which is slower but behaves correctly.
  198. */
  199. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  200. ? global$1.TYPED_ARRAY_SUPPORT
  201. : true;
  202. /*
  203. * Export kMaxLength after typed array support is determined.
  204. */
  205. kMaxLength();
  206. function kMaxLength () {
  207. return Buffer.TYPED_ARRAY_SUPPORT
  208. ? 0x7fffffff
  209. : 0x3fffffff
  210. }
  211. function createBuffer (that, length) {
  212. if (kMaxLength() < length) {
  213. throw new RangeError('Invalid typed array length')
  214. }
  215. if (Buffer.TYPED_ARRAY_SUPPORT) {
  216. // Return an augmented `Uint8Array` instance, for best performance
  217. that = new Uint8Array(length);
  218. that.__proto__ = Buffer.prototype;
  219. } else {
  220. // Fallback: Return an object instance of the Buffer class
  221. if (that === null) {
  222. that = new Buffer(length);
  223. }
  224. that.length = length;
  225. }
  226. return that
  227. }
  228. /**
  229. * The Buffer constructor returns instances of `Uint8Array` that have their
  230. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  231. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  232. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  233. * returns a single octet.
  234. *
  235. * The `Uint8Array` prototype remains unmodified.
  236. */
  237. function Buffer (arg, encodingOrOffset, length) {
  238. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  239. return new Buffer(arg, encodingOrOffset, length)
  240. }
  241. // Common case.
  242. if (typeof arg === 'number') {
  243. if (typeof encodingOrOffset === 'string') {
  244. throw new Error(
  245. 'If encoding is specified then the first argument must be a string'
  246. )
  247. }
  248. return allocUnsafe(this, arg)
  249. }
  250. return from(this, arg, encodingOrOffset, length)
  251. }
  252. Buffer.poolSize = 8192; // not used by this implementation
  253. // TODO: Legacy, not needed anymore. Remove in next major version.
  254. Buffer._augment = function (arr) {
  255. arr.__proto__ = Buffer.prototype;
  256. return arr
  257. };
  258. function from (that, value, encodingOrOffset, length) {
  259. if (typeof value === 'number') {
  260. throw new TypeError('"value" argument must not be a number')
  261. }
  262. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  263. return fromArrayBuffer(that, value, encodingOrOffset, length)
  264. }
  265. if (typeof value === 'string') {
  266. return fromString(that, value, encodingOrOffset)
  267. }
  268. return fromObject(that, value)
  269. }
  270. /**
  271. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  272. * if value is a number.
  273. * Buffer.from(str[, encoding])
  274. * Buffer.from(array)
  275. * Buffer.from(buffer)
  276. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  277. **/
  278. Buffer.from = function (value, encodingOrOffset, length) {
  279. return from(null, value, encodingOrOffset, length)
  280. };
  281. if (Buffer.TYPED_ARRAY_SUPPORT) {
  282. Buffer.prototype.__proto__ = Uint8Array.prototype;
  283. Buffer.__proto__ = Uint8Array;
  284. if (typeof Symbol !== 'undefined' && Symbol.species &&
  285. Buffer[Symbol.species] === Buffer) ;
  286. }
  287. function assertSize (size) {
  288. if (typeof size !== 'number') {
  289. throw new TypeError('"size" argument must be a number')
  290. } else if (size < 0) {
  291. throw new RangeError('"size" argument must not be negative')
  292. }
  293. }
  294. function alloc (that, size, fill, encoding) {
  295. assertSize(size);
  296. if (size <= 0) {
  297. return createBuffer(that, size)
  298. }
  299. if (fill !== undefined) {
  300. // Only pay attention to encoding if it's a string. This
  301. // prevents accidentally sending in a number that would
  302. // be interpretted as a start offset.
  303. return typeof encoding === 'string'
  304. ? createBuffer(that, size).fill(fill, encoding)
  305. : createBuffer(that, size).fill(fill)
  306. }
  307. return createBuffer(that, size)
  308. }
  309. /**
  310. * Creates a new filled Buffer instance.
  311. * alloc(size[, fill[, encoding]])
  312. **/
  313. Buffer.alloc = function (size, fill, encoding) {
  314. return alloc(null, size, fill, encoding)
  315. };
  316. function allocUnsafe (that, size) {
  317. assertSize(size);
  318. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  319. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  320. for (var i = 0; i < size; ++i) {
  321. that[i] = 0;
  322. }
  323. }
  324. return that
  325. }
  326. /**
  327. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  328. * */
  329. Buffer.allocUnsafe = function (size) {
  330. return allocUnsafe(null, size)
  331. };
  332. /**
  333. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  334. */
  335. Buffer.allocUnsafeSlow = function (size) {
  336. return allocUnsafe(null, size)
  337. };
  338. function fromString (that, string, encoding) {
  339. if (typeof encoding !== 'string' || encoding === '') {
  340. encoding = 'utf8';
  341. }
  342. if (!Buffer.isEncoding(encoding)) {
  343. throw new TypeError('"encoding" must be a valid string encoding')
  344. }
  345. var length = byteLength(string, encoding) | 0;
  346. that = createBuffer(that, length);
  347. var actual = that.write(string, encoding);
  348. if (actual !== length) {
  349. // Writing a hex string, for example, that contains invalid characters will
  350. // cause everything after the first invalid character to be ignored. (e.g.
  351. // 'abxxcd' will be treated as 'ab')
  352. that = that.slice(0, actual);
  353. }
  354. return that
  355. }
  356. function fromArrayLike (that, array) {
  357. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  358. that = createBuffer(that, length);
  359. for (var i = 0; i < length; i += 1) {
  360. that[i] = array[i] & 255;
  361. }
  362. return that
  363. }
  364. function fromArrayBuffer (that, array, byteOffset, length) {
  365. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  366. if (byteOffset < 0 || array.byteLength < byteOffset) {
  367. throw new RangeError('\'offset\' is out of bounds')
  368. }
  369. if (array.byteLength < byteOffset + (length || 0)) {
  370. throw new RangeError('\'length\' is out of bounds')
  371. }
  372. if (byteOffset === undefined && length === undefined) {
  373. array = new Uint8Array(array);
  374. } else if (length === undefined) {
  375. array = new Uint8Array(array, byteOffset);
  376. } else {
  377. array = new Uint8Array(array, byteOffset, length);
  378. }
  379. if (Buffer.TYPED_ARRAY_SUPPORT) {
  380. // Return an augmented `Uint8Array` instance, for best performance
  381. that = array;
  382. that.__proto__ = Buffer.prototype;
  383. } else {
  384. // Fallback: Return an object instance of the Buffer class
  385. that = fromArrayLike(that, array);
  386. }
  387. return that
  388. }
  389. function fromObject (that, obj) {
  390. if (internalIsBuffer(obj)) {
  391. var len = checked(obj.length) | 0;
  392. that = createBuffer(that, len);
  393. if (that.length === 0) {
  394. return that
  395. }
  396. obj.copy(that, 0, 0, len);
  397. return that
  398. }
  399. if (obj) {
  400. if ((typeof ArrayBuffer !== 'undefined' &&
  401. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  402. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  403. return createBuffer(that, 0)
  404. }
  405. return fromArrayLike(that, obj)
  406. }
  407. if (obj.type === 'Buffer' && isArray$1(obj.data)) {
  408. return fromArrayLike(that, obj.data)
  409. }
  410. }
  411. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  412. }
  413. function checked (length) {
  414. // Note: cannot use `length < kMaxLength()` here because that fails when
  415. // length is NaN (which is otherwise coerced to zero.)
  416. if (length >= kMaxLength()) {
  417. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  418. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  419. }
  420. return length | 0
  421. }
  422. Buffer.isBuffer = isBuffer;
  423. function internalIsBuffer (b) {
  424. return !!(b != null && b._isBuffer)
  425. }
  426. Buffer.compare = function compare (a, b) {
  427. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  428. throw new TypeError('Arguments must be Buffers')
  429. }
  430. if (a === b) return 0
  431. var x = a.length;
  432. var y = b.length;
  433. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  434. if (a[i] !== b[i]) {
  435. x = a[i];
  436. y = b[i];
  437. break
  438. }
  439. }
  440. if (x < y) return -1
  441. if (y < x) return 1
  442. return 0
  443. };
  444. Buffer.isEncoding = function isEncoding (encoding) {
  445. switch (String(encoding).toLowerCase()) {
  446. case 'hex':
  447. case 'utf8':
  448. case 'utf-8':
  449. case 'ascii':
  450. case 'latin1':
  451. case 'binary':
  452. case 'base64':
  453. case 'ucs2':
  454. case 'ucs-2':
  455. case 'utf16le':
  456. case 'utf-16le':
  457. return true
  458. default:
  459. return false
  460. }
  461. };
  462. Buffer.concat = function concat (list, length) {
  463. if (!isArray$1(list)) {
  464. throw new TypeError('"list" argument must be an Array of Buffers')
  465. }
  466. if (list.length === 0) {
  467. return Buffer.alloc(0)
  468. }
  469. var i;
  470. if (length === undefined) {
  471. length = 0;
  472. for (i = 0; i < list.length; ++i) {
  473. length += list[i].length;
  474. }
  475. }
  476. var buffer = Buffer.allocUnsafe(length);
  477. var pos = 0;
  478. for (i = 0; i < list.length; ++i) {
  479. var buf = list[i];
  480. if (!internalIsBuffer(buf)) {
  481. throw new TypeError('"list" argument must be an Array of Buffers')
  482. }
  483. buf.copy(buffer, pos);
  484. pos += buf.length;
  485. }
  486. return buffer
  487. };
  488. function byteLength (string, encoding) {
  489. if (internalIsBuffer(string)) {
  490. return string.length
  491. }
  492. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  493. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  494. return string.byteLength
  495. }
  496. if (typeof string !== 'string') {
  497. string = '' + string;
  498. }
  499. var len = string.length;
  500. if (len === 0) return 0
  501. // Use a for loop to avoid recursion
  502. var loweredCase = false;
  503. for (;;) {
  504. switch (encoding) {
  505. case 'ascii':
  506. case 'latin1':
  507. case 'binary':
  508. return len
  509. case 'utf8':
  510. case 'utf-8':
  511. case undefined:
  512. return utf8ToBytes(string).length
  513. case 'ucs2':
  514. case 'ucs-2':
  515. case 'utf16le':
  516. case 'utf-16le':
  517. return len * 2
  518. case 'hex':
  519. return len >>> 1
  520. case 'base64':
  521. return base64ToBytes(string).length
  522. default:
  523. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  524. encoding = ('' + encoding).toLowerCase();
  525. loweredCase = true;
  526. }
  527. }
  528. }
  529. Buffer.byteLength = byteLength;
  530. function slowToString (encoding, start, end) {
  531. var loweredCase = false;
  532. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  533. // property of a typed array.
  534. // This behaves neither like String nor Uint8Array in that we set start/end
  535. // to their upper/lower bounds if the value passed is out of range.
  536. // undefined is handled specially as per ECMA-262 6th Edition,
  537. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  538. if (start === undefined || start < 0) {
  539. start = 0;
  540. }
  541. // Return early if start > this.length. Done here to prevent potential uint32
  542. // coercion fail below.
  543. if (start > this.length) {
  544. return ''
  545. }
  546. if (end === undefined || end > this.length) {
  547. end = this.length;
  548. }
  549. if (end <= 0) {
  550. return ''
  551. }
  552. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  553. end >>>= 0;
  554. start >>>= 0;
  555. if (end <= start) {
  556. return ''
  557. }
  558. if (!encoding) encoding = 'utf8';
  559. while (true) {
  560. switch (encoding) {
  561. case 'hex':
  562. return hexSlice(this, start, end)
  563. case 'utf8':
  564. case 'utf-8':
  565. return utf8Slice(this, start, end)
  566. case 'ascii':
  567. return asciiSlice(this, start, end)
  568. case 'latin1':
  569. case 'binary':
  570. return latin1Slice(this, start, end)
  571. case 'base64':
  572. return base64Slice(this, start, end)
  573. case 'ucs2':
  574. case 'ucs-2':
  575. case 'utf16le':
  576. case 'utf-16le':
  577. return utf16leSlice(this, start, end)
  578. default:
  579. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  580. encoding = (encoding + '').toLowerCase();
  581. loweredCase = true;
  582. }
  583. }
  584. }
  585. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  586. // Buffer instances.
  587. Buffer.prototype._isBuffer = true;
  588. function swap (b, n, m) {
  589. var i = b[n];
  590. b[n] = b[m];
  591. b[m] = i;
  592. }
  593. Buffer.prototype.swap16 = function swap16 () {
  594. var len = this.length;
  595. if (len % 2 !== 0) {
  596. throw new RangeError('Buffer size must be a multiple of 16-bits')
  597. }
  598. for (var i = 0; i < len; i += 2) {
  599. swap(this, i, i + 1);
  600. }
  601. return this
  602. };
  603. Buffer.prototype.swap32 = function swap32 () {
  604. var len = this.length;
  605. if (len % 4 !== 0) {
  606. throw new RangeError('Buffer size must be a multiple of 32-bits')
  607. }
  608. for (var i = 0; i < len; i += 4) {
  609. swap(this, i, i + 3);
  610. swap(this, i + 1, i + 2);
  611. }
  612. return this
  613. };
  614. Buffer.prototype.swap64 = function swap64 () {
  615. var len = this.length;
  616. if (len % 8 !== 0) {
  617. throw new RangeError('Buffer size must be a multiple of 64-bits')
  618. }
  619. for (var i = 0; i < len; i += 8) {
  620. swap(this, i, i + 7);
  621. swap(this, i + 1, i + 6);
  622. swap(this, i + 2, i + 5);
  623. swap(this, i + 3, i + 4);
  624. }
  625. return this
  626. };
  627. Buffer.prototype.toString = function toString () {
  628. var length = this.length | 0;
  629. if (length === 0) return ''
  630. if (arguments.length === 0) return utf8Slice(this, 0, length)
  631. return slowToString.apply(this, arguments)
  632. };
  633. Buffer.prototype.equals = function equals (b) {
  634. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  635. if (this === b) return true
  636. return Buffer.compare(this, b) === 0
  637. };
  638. Buffer.prototype.inspect = function inspect () {
  639. var str = '';
  640. var max = INSPECT_MAX_BYTES;
  641. if (this.length > 0) {
  642. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  643. if (this.length > max) str += ' ... ';
  644. }
  645. return '<Buffer ' + str + '>'
  646. };
  647. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  648. if (!internalIsBuffer(target)) {
  649. throw new TypeError('Argument must be a Buffer')
  650. }
  651. if (start === undefined) {
  652. start = 0;
  653. }
  654. if (end === undefined) {
  655. end = target ? target.length : 0;
  656. }
  657. if (thisStart === undefined) {
  658. thisStart = 0;
  659. }
  660. if (thisEnd === undefined) {
  661. thisEnd = this.length;
  662. }
  663. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  664. throw new RangeError('out of range index')
  665. }
  666. if (thisStart >= thisEnd && start >= end) {
  667. return 0
  668. }
  669. if (thisStart >= thisEnd) {
  670. return -1
  671. }
  672. if (start >= end) {
  673. return 1
  674. }
  675. start >>>= 0;
  676. end >>>= 0;
  677. thisStart >>>= 0;
  678. thisEnd >>>= 0;
  679. if (this === target) return 0
  680. var x = thisEnd - thisStart;
  681. var y = end - start;
  682. var len = Math.min(x, y);
  683. var thisCopy = this.slice(thisStart, thisEnd);
  684. var targetCopy = target.slice(start, end);
  685. for (var i = 0; i < len; ++i) {
  686. if (thisCopy[i] !== targetCopy[i]) {
  687. x = thisCopy[i];
  688. y = targetCopy[i];
  689. break
  690. }
  691. }
  692. if (x < y) return -1
  693. if (y < x) return 1
  694. return 0
  695. };
  696. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  697. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  698. //
  699. // Arguments:
  700. // - buffer - a Buffer to search
  701. // - val - a string, Buffer, or number
  702. // - byteOffset - an index into `buffer`; will be clamped to an int32
  703. // - encoding - an optional encoding, relevant is val is a string
  704. // - dir - true for indexOf, false for lastIndexOf
  705. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  706. // Empty buffer means no match
  707. if (buffer.length === 0) return -1
  708. // Normalize byteOffset
  709. if (typeof byteOffset === 'string') {
  710. encoding = byteOffset;
  711. byteOffset = 0;
  712. } else if (byteOffset > 0x7fffffff) {
  713. byteOffset = 0x7fffffff;
  714. } else if (byteOffset < -0x80000000) {
  715. byteOffset = -0x80000000;
  716. }
  717. byteOffset = +byteOffset; // Coerce to Number.
  718. if (isNaN(byteOffset)) {
  719. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  720. byteOffset = dir ? 0 : (buffer.length - 1);
  721. }
  722. // Normalize byteOffset: negative offsets start from the end of the buffer
  723. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  724. if (byteOffset >= buffer.length) {
  725. if (dir) return -1
  726. else byteOffset = buffer.length - 1;
  727. } else if (byteOffset < 0) {
  728. if (dir) byteOffset = 0;
  729. else return -1
  730. }
  731. // Normalize val
  732. if (typeof val === 'string') {
  733. val = Buffer.from(val, encoding);
  734. }
  735. // Finally, search either indexOf (if dir is true) or lastIndexOf
  736. if (internalIsBuffer(val)) {
  737. // Special case: looking for empty string/buffer always fails
  738. if (val.length === 0) {
  739. return -1
  740. }
  741. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  742. } else if (typeof val === 'number') {
  743. val = val & 0xFF; // Search for a byte value [0-255]
  744. if (Buffer.TYPED_ARRAY_SUPPORT &&
  745. typeof Uint8Array.prototype.indexOf === 'function') {
  746. if (dir) {
  747. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  748. } else {
  749. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  750. }
  751. }
  752. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  753. }
  754. throw new TypeError('val must be string, number or Buffer')
  755. }
  756. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  757. var indexSize = 1;
  758. var arrLength = arr.length;
  759. var valLength = val.length;
  760. if (encoding !== undefined) {
  761. encoding = String(encoding).toLowerCase();
  762. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  763. encoding === 'utf16le' || encoding === 'utf-16le') {
  764. if (arr.length < 2 || val.length < 2) {
  765. return -1
  766. }
  767. indexSize = 2;
  768. arrLength /= 2;
  769. valLength /= 2;
  770. byteOffset /= 2;
  771. }
  772. }
  773. function read (buf, i) {
  774. if (indexSize === 1) {
  775. return buf[i]
  776. } else {
  777. return buf.readUInt16BE(i * indexSize)
  778. }
  779. }
  780. var i;
  781. if (dir) {
  782. var foundIndex = -1;
  783. for (i = byteOffset; i < arrLength; i++) {
  784. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  785. if (foundIndex === -1) foundIndex = i;
  786. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  787. } else {
  788. if (foundIndex !== -1) i -= i - foundIndex;
  789. foundIndex = -1;
  790. }
  791. }
  792. } else {
  793. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  794. for (i = byteOffset; i >= 0; i--) {
  795. var found = true;
  796. for (var j = 0; j < valLength; j++) {
  797. if (read(arr, i + j) !== read(val, j)) {
  798. found = false;
  799. break
  800. }
  801. }
  802. if (found) return i
  803. }
  804. }
  805. return -1
  806. }
  807. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  808. return this.indexOf(val, byteOffset, encoding) !== -1
  809. };
  810. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  811. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  812. };
  813. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  814. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  815. };
  816. function hexWrite (buf, string, offset, length) {
  817. offset = Number(offset) || 0;
  818. var remaining = buf.length - offset;
  819. if (!length) {
  820. length = remaining;
  821. } else {
  822. length = Number(length);
  823. if (length > remaining) {
  824. length = remaining;
  825. }
  826. }
  827. // must be an even number of digits
  828. var strLen = string.length;
  829. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  830. if (length > strLen / 2) {
  831. length = strLen / 2;
  832. }
  833. for (var i = 0; i < length; ++i) {
  834. var parsed = parseInt(string.substr(i * 2, 2), 16);
  835. if (isNaN(parsed)) return i
  836. buf[offset + i] = parsed;
  837. }
  838. return i
  839. }
  840. function utf8Write (buf, string, offset, length) {
  841. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  842. }
  843. function asciiWrite (buf, string, offset, length) {
  844. return blitBuffer(asciiToBytes(string), buf, offset, length)
  845. }
  846. function latin1Write (buf, string, offset, length) {
  847. return asciiWrite(buf, string, offset, length)
  848. }
  849. function base64Write (buf, string, offset, length) {
  850. return blitBuffer(base64ToBytes(string), buf, offset, length)
  851. }
  852. function ucs2Write (buf, string, offset, length) {
  853. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  854. }
  855. Buffer.prototype.write = function write (string, offset, length, encoding) {
  856. // Buffer#write(string)
  857. if (offset === undefined) {
  858. encoding = 'utf8';
  859. length = this.length;
  860. offset = 0;
  861. // Buffer#write(string, encoding)
  862. } else if (length === undefined && typeof offset === 'string') {
  863. encoding = offset;
  864. length = this.length;
  865. offset = 0;
  866. // Buffer#write(string, offset[, length][, encoding])
  867. } else if (isFinite(offset)) {
  868. offset = offset | 0;
  869. if (isFinite(length)) {
  870. length = length | 0;
  871. if (encoding === undefined) encoding = 'utf8';
  872. } else {
  873. encoding = length;
  874. length = undefined;
  875. }
  876. // legacy write(string, encoding, offset, length) - remove in v0.13
  877. } else {
  878. throw new Error(
  879. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  880. )
  881. }
  882. var remaining = this.length - offset;
  883. if (length === undefined || length > remaining) length = remaining;
  884. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  885. throw new RangeError('Attempt to write outside buffer bounds')
  886. }
  887. if (!encoding) encoding = 'utf8';
  888. var loweredCase = false;
  889. for (;;) {
  890. switch (encoding) {
  891. case 'hex':
  892. return hexWrite(this, string, offset, length)
  893. case 'utf8':
  894. case 'utf-8':
  895. return utf8Write(this, string, offset, length)
  896. case 'ascii':
  897. return asciiWrite(this, string, offset, length)
  898. case 'latin1':
  899. case 'binary':
  900. return latin1Write(this, string, offset, length)
  901. case 'base64':
  902. // Warning: maxLength not taken into account in base64Write
  903. return base64Write(this, string, offset, length)
  904. case 'ucs2':
  905. case 'ucs-2':
  906. case 'utf16le':
  907. case 'utf-16le':
  908. return ucs2Write(this, string, offset, length)
  909. default:
  910. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  911. encoding = ('' + encoding).toLowerCase();
  912. loweredCase = true;
  913. }
  914. }
  915. };
  916. Buffer.prototype.toJSON = function toJSON () {
  917. return {
  918. type: 'Buffer',
  919. data: Array.prototype.slice.call(this._arr || this, 0)
  920. }
  921. };
  922. function base64Slice (buf, start, end) {
  923. if (start === 0 && end === buf.length) {
  924. return fromByteArray(buf)
  925. } else {
  926. return fromByteArray(buf.slice(start, end))
  927. }
  928. }
  929. function utf8Slice (buf, start, end) {
  930. end = Math.min(buf.length, end);
  931. var res = [];
  932. var i = start;
  933. while (i < end) {
  934. var firstByte = buf[i];
  935. var codePoint = null;
  936. var bytesPerSequence = (firstByte > 0xEF) ? 4
  937. : (firstByte > 0xDF) ? 3
  938. : (firstByte > 0xBF) ? 2
  939. : 1;
  940. if (i + bytesPerSequence <= end) {
  941. var secondByte, thirdByte, fourthByte, tempCodePoint;
  942. switch (bytesPerSequence) {
  943. case 1:
  944. if (firstByte < 0x80) {
  945. codePoint = firstByte;
  946. }
  947. break
  948. case 2:
  949. secondByte = buf[i + 1];
  950. if ((secondByte & 0xC0) === 0x80) {
  951. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  952. if (tempCodePoint > 0x7F) {
  953. codePoint = tempCodePoint;
  954. }
  955. }
  956. break
  957. case 3:
  958. secondByte = buf[i + 1];
  959. thirdByte = buf[i + 2];
  960. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  961. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  962. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  963. codePoint = tempCodePoint;
  964. }
  965. }
  966. break
  967. case 4:
  968. secondByte = buf[i + 1];
  969. thirdByte = buf[i + 2];
  970. fourthByte = buf[i + 3];
  971. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  972. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  973. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  974. codePoint = tempCodePoint;
  975. }
  976. }
  977. }
  978. }
  979. if (codePoint === null) {
  980. // we did not generate a valid codePoint so insert a
  981. // replacement char (U+FFFD) and advance only 1 byte
  982. codePoint = 0xFFFD;
  983. bytesPerSequence = 1;
  984. } else if (codePoint > 0xFFFF) {
  985. // encode to utf16 (surrogate pair dance)
  986. codePoint -= 0x10000;
  987. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  988. codePoint = 0xDC00 | codePoint & 0x3FF;
  989. }
  990. res.push(codePoint);
  991. i += bytesPerSequence;
  992. }
  993. return decodeCodePointsArray(res)
  994. }
  995. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  996. // the lowest limit is Chrome, with 0x10000 args.
  997. // We go 1 magnitude less, for safety
  998. var MAX_ARGUMENTS_LENGTH = 0x1000;
  999. function decodeCodePointsArray (codePoints) {
  1000. var len = codePoints.length;
  1001. if (len <= MAX_ARGUMENTS_LENGTH) {
  1002. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1003. }
  1004. // Decode in chunks to avoid "call stack size exceeded".
  1005. var res = '';
  1006. var i = 0;
  1007. while (i < len) {
  1008. res += String.fromCharCode.apply(
  1009. String,
  1010. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1011. );
  1012. }
  1013. return res
  1014. }
  1015. function asciiSlice (buf, start, end) {
  1016. var ret = '';
  1017. end = Math.min(buf.length, end);
  1018. for (var i = start; i < end; ++i) {
  1019. ret += String.fromCharCode(buf[i] & 0x7F);
  1020. }
  1021. return ret
  1022. }
  1023. function latin1Slice (buf, start, end) {
  1024. var ret = '';
  1025. end = Math.min(buf.length, end);
  1026. for (var i = start; i < end; ++i) {
  1027. ret += String.fromCharCode(buf[i]);
  1028. }
  1029. return ret
  1030. }
  1031. function hexSlice (buf, start, end) {
  1032. var len = buf.length;
  1033. if (!start || start < 0) start = 0;
  1034. if (!end || end < 0 || end > len) end = len;
  1035. var out = '';
  1036. for (var i = start; i < end; ++i) {
  1037. out += toHex(buf[i]);
  1038. }
  1039. return out
  1040. }
  1041. function utf16leSlice (buf, start, end) {
  1042. var bytes = buf.slice(start, end);
  1043. var res = '';
  1044. for (var i = 0; i < bytes.length; i += 2) {
  1045. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1046. }
  1047. return res
  1048. }
  1049. Buffer.prototype.slice = function slice (start, end) {
  1050. var len = this.length;
  1051. start = ~~start;
  1052. end = end === undefined ? len : ~~end;
  1053. if (start < 0) {
  1054. start += len;
  1055. if (start < 0) start = 0;
  1056. } else if (start > len) {
  1057. start = len;
  1058. }
  1059. if (end < 0) {
  1060. end += len;
  1061. if (end < 0) end = 0;
  1062. } else if (end > len) {
  1063. end = len;
  1064. }
  1065. if (end < start) end = start;
  1066. var newBuf;
  1067. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1068. newBuf = this.subarray(start, end);
  1069. newBuf.__proto__ = Buffer.prototype;
  1070. } else {
  1071. var sliceLen = end - start;
  1072. newBuf = new Buffer(sliceLen, undefined);
  1073. for (var i = 0; i < sliceLen; ++i) {
  1074. newBuf[i] = this[i + start];
  1075. }
  1076. }
  1077. return newBuf
  1078. };
  1079. /*
  1080. * Need to make sure that buffer isn't trying to write out of bounds.
  1081. */
  1082. function checkOffset (offset, ext, length) {
  1083. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1084. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1085. }
  1086. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1087. offset = offset | 0;
  1088. byteLength = byteLength | 0;
  1089. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1090. var val = this[offset];
  1091. var mul = 1;
  1092. var i = 0;
  1093. while (++i < byteLength && (mul *= 0x100)) {
  1094. val += this[offset + i] * mul;
  1095. }
  1096. return val
  1097. };
  1098. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1099. offset = offset | 0;
  1100. byteLength = byteLength | 0;
  1101. if (!noAssert) {
  1102. checkOffset(offset, byteLength, this.length);
  1103. }
  1104. var val = this[offset + --byteLength];
  1105. var mul = 1;
  1106. while (byteLength > 0 && (mul *= 0x100)) {
  1107. val += this[offset + --byteLength] * mul;
  1108. }
  1109. return val
  1110. };
  1111. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1112. if (!noAssert) checkOffset(offset, 1, this.length);
  1113. return this[offset]
  1114. };
  1115. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1116. if (!noAssert) checkOffset(offset, 2, this.length);
  1117. return this[offset] | (this[offset + 1] << 8)
  1118. };
  1119. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1120. if (!noAssert) checkOffset(offset, 2, this.length);
  1121. return (this[offset] << 8) | this[offset + 1]
  1122. };
  1123. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1124. if (!noAssert) checkOffset(offset, 4, this.length);
  1125. return ((this[offset]) |
  1126. (this[offset + 1] << 8) |
  1127. (this[offset + 2] << 16)) +
  1128. (this[offset + 3] * 0x1000000)
  1129. };
  1130. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1131. if (!noAssert) checkOffset(offset, 4, this.length);
  1132. return (this[offset] * 0x1000000) +
  1133. ((this[offset + 1] << 16) |
  1134. (this[offset + 2] << 8) |
  1135. this[offset + 3])
  1136. };
  1137. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1138. offset = offset | 0;
  1139. byteLength = byteLength | 0;
  1140. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1141. var val = this[offset];
  1142. var mul = 1;
  1143. var i = 0;
  1144. while (++i < byteLength && (mul *= 0x100)) {
  1145. val += this[offset + i] * mul;
  1146. }
  1147. mul *= 0x80;
  1148. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1149. return val
  1150. };
  1151. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1152. offset = offset | 0;
  1153. byteLength = byteLength | 0;
  1154. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1155. var i = byteLength;
  1156. var mul = 1;
  1157. var val = this[offset + --i];
  1158. while (i > 0 && (mul *= 0x100)) {
  1159. val += this[offset + --i] * mul;
  1160. }
  1161. mul *= 0x80;
  1162. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1163. return val
  1164. };
  1165. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1166. if (!noAssert) checkOffset(offset, 1, this.length);
  1167. if (!(this[offset] & 0x80)) return (this[offset])
  1168. return ((0xff - this[offset] + 1) * -1)
  1169. };
  1170. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1171. if (!noAssert) checkOffset(offset, 2, this.length);
  1172. var val = this[offset] | (this[offset + 1] << 8);
  1173. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1174. };
  1175. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1176. if (!noAssert) checkOffset(offset, 2, this.length);
  1177. var val = this[offset + 1] | (this[offset] << 8);
  1178. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1179. };
  1180. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1181. if (!noAssert) checkOffset(offset, 4, this.length);
  1182. return (this[offset]) |
  1183. (this[offset + 1] << 8) |
  1184. (this[offset + 2] << 16) |
  1185. (this[offset + 3] << 24)
  1186. };
  1187. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1188. if (!noAssert) checkOffset(offset, 4, this.length);
  1189. return (this[offset] << 24) |
  1190. (this[offset + 1] << 16) |
  1191. (this[offset + 2] << 8) |
  1192. (this[offset + 3])
  1193. };
  1194. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1195. if (!noAssert) checkOffset(offset, 4, this.length);
  1196. return read(this, offset, true, 23, 4)
  1197. };
  1198. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1199. if (!noAssert) checkOffset(offset, 4, this.length);
  1200. return read(this, offset, false, 23, 4)
  1201. };
  1202. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1203. if (!noAssert) checkOffset(offset, 8, this.length);
  1204. return read(this, offset, true, 52, 8)
  1205. };
  1206. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1207. if (!noAssert) checkOffset(offset, 8, this.length);
  1208. return read(this, offset, false, 52, 8)
  1209. };
  1210. function checkInt (buf, value, offset, ext, max, min) {
  1211. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1212. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1213. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1214. }
  1215. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1216. value = +value;
  1217. offset = offset | 0;
  1218. byteLength = byteLength | 0;
  1219. if (!noAssert) {
  1220. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1221. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1222. }
  1223. var mul = 1;
  1224. var i = 0;
  1225. this[offset] = value & 0xFF;
  1226. while (++i < byteLength && (mul *= 0x100)) {
  1227. this[offset + i] = (value / mul) & 0xFF;
  1228. }
  1229. return offset + byteLength
  1230. };
  1231. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1232. value = +value;
  1233. offset = offset | 0;
  1234. byteLength = byteLength | 0;
  1235. if (!noAssert) {
  1236. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1237. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1238. }
  1239. var i = byteLength - 1;
  1240. var mul = 1;
  1241. this[offset + i] = value & 0xFF;
  1242. while (--i >= 0 && (mul *= 0x100)) {
  1243. this[offset + i] = (value / mul) & 0xFF;
  1244. }
  1245. return offset + byteLength
  1246. };
  1247. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1248. value = +value;
  1249. offset = offset | 0;
  1250. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  1251. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  1252. this[offset] = (value & 0xff);
  1253. return offset + 1
  1254. };
  1255. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1256. if (value < 0) value = 0xffff + value + 1;
  1257. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1258. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1259. (littleEndian ? i : 1 - i) * 8;
  1260. }
  1261. }
  1262. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1263. value = +value;
  1264. offset = offset | 0;
  1265. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1266. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1267. this[offset] = (value & 0xff);
  1268. this[offset + 1] = (value >>> 8);
  1269. } else {
  1270. objectWriteUInt16(this, value, offset, true);
  1271. }
  1272. return offset + 2
  1273. };
  1274. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1275. value = +value;
  1276. offset = offset | 0;
  1277. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1278. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1279. this[offset] = (value >>> 8);
  1280. this[offset + 1] = (value & 0xff);
  1281. } else {
  1282. objectWriteUInt16(this, value, offset, false);
  1283. }
  1284. return offset + 2
  1285. };
  1286. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1287. if (value < 0) value = 0xffffffff + value + 1;
  1288. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1289. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  1290. }
  1291. }
  1292. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1293. value = +value;
  1294. offset = offset | 0;
  1295. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1296. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1297. this[offset + 3] = (value >>> 24);
  1298. this[offset + 2] = (value >>> 16);
  1299. this[offset + 1] = (value >>> 8);
  1300. this[offset] = (value & 0xff);
  1301. } else {
  1302. objectWriteUInt32(this, value, offset, true);
  1303. }
  1304. return offset + 4
  1305. };
  1306. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1307. value = +value;
  1308. offset = offset | 0;
  1309. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1310. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1311. this[offset] = (value >>> 24);
  1312. this[offset + 1] = (value >>> 16);
  1313. this[offset + 2] = (value >>> 8);
  1314. this[offset + 3] = (value & 0xff);
  1315. } else {
  1316. objectWriteUInt32(this, value, offset, false);
  1317. }
  1318. return offset + 4
  1319. };
  1320. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1321. value = +value;
  1322. offset = offset | 0;
  1323. if (!noAssert) {
  1324. var limit = Math.pow(2, 8 * byteLength - 1);
  1325. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1326. }
  1327. var i = 0;
  1328. var mul = 1;
  1329. var sub = 0;
  1330. this[offset] = value & 0xFF;
  1331. while (++i < byteLength && (mul *= 0x100)) {
  1332. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1333. sub = 1;
  1334. }
  1335. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  1336. }
  1337. return offset + byteLength
  1338. };
  1339. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1340. value = +value;
  1341. offset = offset | 0;
  1342. if (!noAssert) {
  1343. var limit = Math.pow(2, 8 * byteLength - 1);
  1344. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1345. }
  1346. var i = byteLength - 1;
  1347. var mul = 1;
  1348. var sub = 0;
  1349. this[offset + i] = value & 0xFF;
  1350. while (--i >= 0 && (mul *= 0x100)) {
  1351. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1352. sub = 1;
  1353. }
  1354. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  1355. }
  1356. return offset + byteLength
  1357. };
  1358. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1359. value = +value;
  1360. offset = offset | 0;
  1361. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  1362. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  1363. if (value < 0) value = 0xff + value + 1;
  1364. this[offset] = (value & 0xff);
  1365. return offset + 1
  1366. };
  1367. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1368. value = +value;
  1369. offset = offset | 0;
  1370. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1371. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1372. this[offset] = (value & 0xff);
  1373. this[offset + 1] = (value >>> 8);
  1374. } else {
  1375. objectWriteUInt16(this, value, offset, true);
  1376. }
  1377. return offset + 2
  1378. };
  1379. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1380. value = +value;
  1381. offset = offset | 0;
  1382. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1383. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1384. this[offset] = (value >>> 8);
  1385. this[offset + 1] = (value & 0xff);
  1386. } else {
  1387. objectWriteUInt16(this, value, offset, false);
  1388. }
  1389. return offset + 2
  1390. };
  1391. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1392. value = +value;
  1393. offset = offset | 0;
  1394. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1395. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1396. this[offset] = (value & 0xff);
  1397. this[offset + 1] = (value >>> 8);
  1398. this[offset + 2] = (value >>> 16);
  1399. this[offset + 3] = (value >>> 24);
  1400. } else {
  1401. objectWriteUInt32(this, value, offset, true);
  1402. }
  1403. return offset + 4
  1404. };
  1405. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1406. value = +value;
  1407. offset = offset | 0;
  1408. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1409. if (value < 0) value = 0xffffffff + value + 1;
  1410. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1411. this[offset] = (value >>> 24);
  1412. this[offset + 1] = (value >>> 16);
  1413. this[offset + 2] = (value >>> 8);
  1414. this[offset + 3] = (value & 0xff);
  1415. } else {
  1416. objectWriteUInt32(this, value, offset, false);
  1417. }
  1418. return offset + 4
  1419. };
  1420. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1421. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1422. if (offset < 0) throw new RangeError('Index out of range')
  1423. }
  1424. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1425. if (!noAssert) {
  1426. checkIEEE754(buf, value, offset, 4);
  1427. }
  1428. write(buf, value, offset, littleEndian, 23, 4);
  1429. return offset + 4
  1430. }
  1431. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1432. return writeFloat(this, value, offset, true, noAssert)
  1433. };
  1434. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1435. return writeFloat(this, value, offset, false, noAssert)
  1436. };
  1437. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1438. if (!noAssert) {
  1439. checkIEEE754(buf, value, offset, 8);
  1440. }
  1441. write(buf, value, offset, littleEndian, 52, 8);
  1442. return offset + 8
  1443. }
  1444. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1445. return writeDouble(this, value, offset, true, noAssert)
  1446. };
  1447. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1448. return writeDouble(this, value, offset, false, noAssert)
  1449. };
  1450. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1451. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1452. if (!start) start = 0;
  1453. if (!end && end !== 0) end = this.length;
  1454. if (targetStart >= target.length) targetStart = target.length;
  1455. if (!targetStart) targetStart = 0;
  1456. if (end > 0 && end < start) end = start;
  1457. // Copy 0 bytes; we're done
  1458. if (end === start) return 0
  1459. if (target.length === 0 || this.length === 0) return 0
  1460. // Fatal error conditions
  1461. if (targetStart < 0) {
  1462. throw new RangeError('targetStart out of bounds')
  1463. }
  1464. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1465. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1466. // Are we oob?
  1467. if (end > this.length) end = this.length;
  1468. if (target.length - targetStart < end - start) {
  1469. end = target.length - targetStart + start;
  1470. }
  1471. var len = end - start;
  1472. var i;
  1473. if (this === target && start < targetStart && targetStart < end) {
  1474. // descending copy from end
  1475. for (i = len - 1; i >= 0; --i) {
  1476. target[i + targetStart] = this[i + start];
  1477. }
  1478. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1479. // ascending copy from start
  1480. for (i = 0; i < len; ++i) {
  1481. target[i + targetStart] = this[i + start];
  1482. }
  1483. } else {
  1484. Uint8Array.prototype.set.call(
  1485. target,
  1486. this.subarray(start, start + len),
  1487. targetStart
  1488. );
  1489. }
  1490. return len
  1491. };
  1492. // Usage:
  1493. // buffer.fill(number[, offset[, end]])
  1494. // buffer.fill(buffer[, offset[, end]])
  1495. // buffer.fill(string[, offset[, end]][, encoding])
  1496. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1497. // Handle string cases:
  1498. if (typeof val === 'string') {
  1499. if (typeof start === 'string') {
  1500. encoding = start;
  1501. start = 0;
  1502. end = this.length;
  1503. } else if (typeof end === 'string') {
  1504. encoding = end;
  1505. end = this.length;
  1506. }
  1507. if (val.length === 1) {
  1508. var code = val.charCodeAt(0);
  1509. if (code < 256) {
  1510. val = code;
  1511. }
  1512. }
  1513. if (encoding !== undefined && typeof encoding !== 'string') {
  1514. throw new TypeError('encoding must be a string')
  1515. }
  1516. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1517. throw new TypeError('Unknown encoding: ' + encoding)
  1518. }
  1519. } else if (typeof val === 'number') {
  1520. val = val & 255;
  1521. }
  1522. // Invalid ranges are not set to a default, so can range check early.
  1523. if (start < 0 || this.length < start || this.length < end) {
  1524. throw new RangeError('Out of range index')
  1525. }
  1526. if (end <= start) {
  1527. return this
  1528. }
  1529. start = start >>> 0;
  1530. end = end === undefined ? this.length : end >>> 0;
  1531. if (!val) val = 0;
  1532. var i;
  1533. if (typeof val === 'number') {
  1534. for (i = start; i < end; ++i) {
  1535. this[i] = val;
  1536. }
  1537. } else {
  1538. var bytes = internalIsBuffer(val)
  1539. ? val
  1540. : utf8ToBytes(new Buffer(val, encoding).toString());
  1541. var len = bytes.length;
  1542. for (i = 0; i < end - start; ++i) {
  1543. this[i + start] = bytes[i % len];
  1544. }
  1545. }
  1546. return this
  1547. };
  1548. // HELPER FUNCTIONS
  1549. // ================
  1550. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  1551. function base64clean (str) {
  1552. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1553. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  1554. // Node converts strings with length < 2 to ''
  1555. if (str.length < 2) return ''
  1556. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1557. while (str.length % 4 !== 0) {
  1558. str = str + '=';
  1559. }
  1560. return str
  1561. }
  1562. function stringtrim (str) {
  1563. if (str.trim) return str.trim()
  1564. return str.replace(/^\s+|\s+$/g, '')
  1565. }
  1566. function toHex (n) {
  1567. if (n < 16) return '0' + n.toString(16)
  1568. return n.toString(16)
  1569. }
  1570. function utf8ToBytes (string, units) {
  1571. units = units || Infinity;
  1572. var codePoint;
  1573. var length = string.length;
  1574. var leadSurrogate = null;
  1575. var bytes = [];
  1576. for (var i = 0; i < length; ++i) {
  1577. codePoint = string.charCodeAt(i);
  1578. // is surrogate component
  1579. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1580. // last char was a lead
  1581. if (!leadSurrogate) {
  1582. // no lead yet
  1583. if (codePoint > 0xDBFF) {
  1584. // unexpected trail
  1585. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1586. continue
  1587. } else if (i + 1 === length) {
  1588. // unpaired lead
  1589. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1590. continue
  1591. }
  1592. // valid lead
  1593. leadSurrogate = codePoint;
  1594. continue
  1595. }
  1596. // 2 leads in a row
  1597. if (codePoint < 0xDC00) {
  1598. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1599. leadSurrogate = codePoint;
  1600. continue
  1601. }
  1602. // valid surrogate pair
  1603. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  1604. } else if (leadSurrogate) {
  1605. // valid bmp char, but last char was a lead
  1606. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1607. }
  1608. leadSurrogate = null;
  1609. // encode utf8
  1610. if (codePoint < 0x80) {
  1611. if ((units -= 1) < 0) break
  1612. bytes.push(codePoint);
  1613. } else if (codePoint < 0x800) {
  1614. if ((units -= 2) < 0) break
  1615. bytes.push(
  1616. codePoint >> 0x6 | 0xC0,
  1617. codePoint & 0x3F | 0x80
  1618. );
  1619. } else if (codePoint < 0x10000) {
  1620. if ((units -= 3) < 0) break
  1621. bytes.push(
  1622. codePoint >> 0xC | 0xE0,
  1623. codePoint >> 0x6 & 0x3F | 0x80,
  1624. codePoint & 0x3F | 0x80
  1625. );
  1626. } else if (codePoint < 0x110000) {
  1627. if ((units -= 4) < 0) break
  1628. bytes.push(
  1629. codePoint >> 0x12 | 0xF0,
  1630. codePoint >> 0xC & 0x3F | 0x80,
  1631. codePoint >> 0x6 & 0x3F | 0x80,
  1632. codePoint & 0x3F | 0x80
  1633. );
  1634. } else {
  1635. throw new Error('Invalid code point')
  1636. }
  1637. }
  1638. return bytes
  1639. }
  1640. function asciiToBytes (str) {
  1641. var byteArray = [];
  1642. for (var i = 0; i < str.length; ++i) {
  1643. // Node's code seems to be doing this and not & 0x7F..
  1644. byteArray.push(str.charCodeAt(i) & 0xFF);
  1645. }
  1646. return byteArray
  1647. }
  1648. function utf16leToBytes (str, units) {
  1649. var c, hi, lo;
  1650. var byteArray = [];
  1651. for (var i = 0; i < str.length; ++i) {
  1652. if ((units -= 2) < 0) break
  1653. c = str.charCodeAt(i);
  1654. hi = c >> 8;
  1655. lo = c % 256;
  1656. byteArray.push(lo);
  1657. byteArray.push(hi);
  1658. }
  1659. return byteArray
  1660. }
  1661. function base64ToBytes (str) {
  1662. return toByteArray(base64clean(str))
  1663. }
  1664. function blitBuffer (src, dst, offset, length) {
  1665. for (var i = 0; i < length; ++i) {
  1666. if ((i + offset >= dst.length) || (i >= src.length)) break
  1667. dst[i + offset] = src[i];
  1668. }
  1669. return i
  1670. }
  1671. function isnan (val) {
  1672. return val !== val // eslint-disable-line no-self-compare
  1673. }
  1674. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  1675. // The _isBuffer check is for Safari 5-7 support, because it's missing
  1676. // Object.prototype.constructor. Remove this eventually
  1677. function isBuffer(obj) {
  1678. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  1679. }
  1680. function isFastBuffer (obj) {
  1681. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  1682. }
  1683. // For Node v0.10 support. Remove this eventually.
  1684. function isSlowBuffer (obj) {
  1685. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  1686. }
  1687. var domain;
  1688. // This constructor is used to store event handlers. Instantiating this is
  1689. // faster than explicitly calling `Object.create(null)` to get a "clean" empty
  1690. // object (tested with v8 v4.9).
  1691. function EventHandlers() {}
  1692. EventHandlers.prototype = Object.create(null);
  1693. function EventEmitter() {
  1694. EventEmitter.init.call(this);
  1695. }
  1696. // nodejs oddity
  1697. // require('events') === require('events').EventEmitter
  1698. EventEmitter.EventEmitter = EventEmitter;
  1699. EventEmitter.usingDomains = false;
  1700. EventEmitter.prototype.domain = undefined;
  1701. EventEmitter.prototype._events = undefined;
  1702. EventEmitter.prototype._maxListeners = undefined;
  1703. // By default EventEmitters will print a warning if more than 10 listeners are
  1704. // added to it. This is a useful default which helps finding memory leaks.
  1705. EventEmitter.defaultMaxListeners = 10;
  1706. EventEmitter.init = function() {
  1707. this.domain = null;
  1708. if (EventEmitter.usingDomains) {
  1709. // if there is an active domain, then attach to it.
  1710. if (domain.active ) ;
  1711. }
  1712. if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
  1713. this._events = new EventHandlers();
  1714. this._eventsCount = 0;
  1715. }
  1716. this._maxListeners = this._maxListeners || undefined;
  1717. };
  1718. // Obviously not all Emitters should be limited to 10. This function allows
  1719. // that to be increased. Set to zero for unlimited.
  1720. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  1721. if (typeof n !== 'number' || n < 0 || isNaN(n))
  1722. throw new TypeError('"n" argument must be a positive number');
  1723. this._maxListeners = n;
  1724. return this;
  1725. };
  1726. function $getMaxListeners(that) {
  1727. if (that._maxListeners === undefined)
  1728. return EventEmitter.defaultMaxListeners;
  1729. return that._maxListeners;
  1730. }
  1731. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  1732. return $getMaxListeners(this);
  1733. };
  1734. // These standalone emit* functions are used to optimize calling of event
  1735. // handlers for fast cases because emit() itself often has a variable number of
  1736. // arguments and can be deoptimized because of that. These functions always have
  1737. // the same number of arguments and thus do not get deoptimized, so the code
  1738. // inside them can execute faster.
  1739. function emitNone(handler, isFn, self) {
  1740. if (isFn)
  1741. handler.call(self);
  1742. else {
  1743. var len = handler.length;
  1744. var listeners = arrayClone(handler, len);
  1745. for (var i = 0; i < len; ++i)
  1746. listeners[i].call(self);
  1747. }
  1748. }
  1749. function emitOne(handler, isFn, self, arg1) {
  1750. if (isFn)
  1751. handler.call(self, arg1);
  1752. else {
  1753. var len = handler.length;
  1754. var listeners = arrayClone(handler, len);
  1755. for (var i = 0; i < len; ++i)
  1756. listeners[i].call(self, arg1);
  1757. }
  1758. }
  1759. function emitTwo(handler, isFn, self, arg1, arg2) {
  1760. if (isFn)
  1761. handler.call(self, arg1, arg2);
  1762. else {
  1763. var len = handler.length;
  1764. var listeners = arrayClone(handler, len);
  1765. for (var i = 0; i < len; ++i)
  1766. listeners[i].call(self, arg1, arg2);
  1767. }
  1768. }
  1769. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  1770. if (isFn)
  1771. handler.call(self, arg1, arg2, arg3);
  1772. else {
  1773. var len = handler.length;
  1774. var listeners = arrayClone(handler, len);
  1775. for (var i = 0; i < len; ++i)
  1776. listeners[i].call(self, arg1, arg2, arg3);
  1777. }
  1778. }
  1779. function emitMany(handler, isFn, self, args) {
  1780. if (isFn)
  1781. handler.apply(self, args);
  1782. else {
  1783. var len = handler.length;
  1784. var listeners = arrayClone(handler, len);
  1785. for (var i = 0; i < len; ++i)
  1786. listeners[i].apply(self, args);
  1787. }
  1788. }
  1789. EventEmitter.prototype.emit = function emit(type) {
  1790. var er, handler, len, args, i, events, domain;
  1791. var doError = (type === 'error');
  1792. events = this._events;
  1793. if (events)
  1794. doError = (doError && events.error == null);
  1795. else if (!doError)
  1796. return false;
  1797. domain = this.domain;
  1798. // If there is no 'error' event listener then throw.
  1799. if (doError) {
  1800. er = arguments[1];
  1801. if (domain) {
  1802. if (!er)
  1803. er = new Error('Uncaught, unspecified "error" event');
  1804. er.domainEmitter = this;
  1805. er.domain = domain;
  1806. er.domainThrown = false;
  1807. domain.emit('error', er);
  1808. } else if (er instanceof Error) {
  1809. throw er; // Unhandled 'error' event
  1810. } else {
  1811. // At least give some kind of context to the user
  1812. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  1813. err.context = er;
  1814. throw err;
  1815. }
  1816. return false;
  1817. }
  1818. handler = events[type];
  1819. if (!handler)
  1820. return false;
  1821. var isFn = typeof handler === 'function';
  1822. len = arguments.length;
  1823. switch (len) {
  1824. // fast cases
  1825. case 1:
  1826. emitNone(handler, isFn, this);
  1827. break;
  1828. case 2:
  1829. emitOne(handler, isFn, this, arguments[1]);
  1830. break;
  1831. case 3:
  1832. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  1833. break;
  1834. case 4:
  1835. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  1836. break;
  1837. // slower
  1838. default:
  1839. args = new Array(len - 1);
  1840. for (i = 1; i < len; i++)
  1841. args[i - 1] = arguments[i];
  1842. emitMany(handler, isFn, this, args);
  1843. }
  1844. return true;
  1845. };
  1846. function _addListener(target, type, listener, prepend) {
  1847. var m;
  1848. var events;
  1849. var existing;
  1850. if (typeof listener !== 'function')
  1851. throw new TypeError('"listener" argument must be a function');
  1852. events = target._events;
  1853. if (!events) {
  1854. events = target._events = new EventHandlers();
  1855. target._eventsCount = 0;
  1856. } else {
  1857. // To avoid recursion in the case that type === "newListener"! Before
  1858. // adding it to the listeners, first emit "newListener".
  1859. if (events.newListener) {
  1860. target.emit('newListener', type,
  1861. listener.listener ? listener.listener : listener);
  1862. // Re-assign `events` because a newListener handler could have caused the
  1863. // this._events to be assigned to a new object
  1864. events = target._events;
  1865. }
  1866. existing = events[type];
  1867. }
  1868. if (!existing) {
  1869. // Optimize the case of one listener. Don't need the extra array object.
  1870. existing = events[type] = listener;
  1871. ++target._eventsCount;
  1872. } else {
  1873. if (typeof existing === 'function') {
  1874. // Adding the second element, need to change to array.
  1875. existing = events[type] = prepend ? [listener, existing] :
  1876. [existing, listener];
  1877. } else {
  1878. // If we've already got an array, just append.
  1879. if (prepend) {
  1880. existing.unshift(listener);
  1881. } else {
  1882. existing.push(listener);
  1883. }
  1884. }
  1885. // Check for listener leak
  1886. if (!existing.warned) {
  1887. m = $getMaxListeners(target);
  1888. if (m && m > 0 && existing.length > m) {
  1889. existing.warned = true;
  1890. var w = new Error('Possible EventEmitter memory leak detected. ' +
  1891. existing.length + ' ' + type + ' listeners added. ' +
  1892. 'Use emitter.setMaxListeners() to increase limit');
  1893. w.name = 'MaxListenersExceededWarning';
  1894. w.emitter = target;
  1895. w.type = type;
  1896. w.count = existing.length;
  1897. emitWarning(w);
  1898. }
  1899. }
  1900. }
  1901. return target;
  1902. }
  1903. function emitWarning(e) {
  1904. typeof console.warn === 'function' ? console.warn(e) : console.log(e);
  1905. }
  1906. EventEmitter.prototype.addListener = function addListener(type, listener) {
  1907. return _addListener(this, type, listener, false);
  1908. };
  1909. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1910. EventEmitter.prototype.prependListener =
  1911. function prependListener(type, listener) {
  1912. return _addListener(this, type, listener, true);
  1913. };
  1914. function _onceWrap(target, type, listener) {
  1915. var fired = false;
  1916. function g() {
  1917. target.removeListener(type, g);
  1918. if (!fired) {
  1919. fired = true;
  1920. listener.apply(target, arguments);
  1921. }
  1922. }
  1923. g.listener = listener;
  1924. return g;
  1925. }
  1926. EventEmitter.prototype.once = function once(type, listener) {
  1927. if (typeof listener !== 'function')
  1928. throw new TypeError('"listener" argument must be a function');
  1929. this.on(type, _onceWrap(this, type, listener));
  1930. return this;
  1931. };
  1932. EventEmitter.prototype.prependOnceListener =
  1933. function prependOnceListener(type, listener) {
  1934. if (typeof listener !== 'function')
  1935. throw new TypeError('"listener" argument must be a function');
  1936. this.prependListener(type, _onceWrap(this, type, listener));
  1937. return this;
  1938. };
  1939. // emits a 'removeListener' event iff the listener was removed
  1940. EventEmitter.prototype.removeListener =
  1941. function removeListener(type, listener) {
  1942. var list, events, position, i, originalListener;
  1943. if (typeof listener !== 'function')
  1944. throw new TypeError('"listener" argument must be a function');
  1945. events = this._events;
  1946. if (!events)
  1947. return this;
  1948. list = events[type];
  1949. if (!list)
  1950. return this;
  1951. if (list === listener || (list.listener && list.listener === listener)) {
  1952. if (--this._eventsCount === 0)
  1953. this._events = new EventHandlers();
  1954. else {
  1955. delete events[type];
  1956. if (events.removeListener)
  1957. this.emit('removeListener', type, list.listener || listener);
  1958. }
  1959. } else if (typeof list !== 'function') {
  1960. position = -1;
  1961. for (i = list.length; i-- > 0;) {
  1962. if (list[i] === listener ||
  1963. (list[i].listener && list[i].listener === listener)) {
  1964. originalListener = list[i].listener;
  1965. position = i;
  1966. break;
  1967. }
  1968. }
  1969. if (position < 0)
  1970. return this;
  1971. if (list.length === 1) {
  1972. list[0] = undefined;
  1973. if (--this._eventsCount === 0) {
  1974. this._events = new EventHandlers();
  1975. return this;
  1976. } else {
  1977. delete events[type];
  1978. }
  1979. } else {
  1980. spliceOne(list, position);
  1981. }
  1982. if (events.removeListener)
  1983. this.emit('removeListener', type, originalListener || listener);
  1984. }
  1985. return this;
  1986. };
  1987. EventEmitter.prototype.removeAllListeners =
  1988. function removeAllListeners(type) {
  1989. var listeners, events;
  1990. events = this._events;
  1991. if (!events)
  1992. return this;
  1993. // not listening for removeListener, no need to emit
  1994. if (!events.removeListener) {
  1995. if (arguments.length === 0) {
  1996. this._events = new EventHandlers();
  1997. this._eventsCount = 0;
  1998. } else if (events[type]) {
  1999. if (--this._eventsCount === 0)
  2000. this._events = new EventHandlers();
  2001. else
  2002. delete events[type];
  2003. }
  2004. return this;
  2005. }
  2006. // emit removeListener for all listeners on all events
  2007. if (arguments.length === 0) {
  2008. var keys = Object.keys(events);
  2009. for (var i = 0, key; i < keys.length; ++i) {
  2010. key = keys[i];
  2011. if (key === 'removeListener') continue;
  2012. this.removeAllListeners(key);
  2013. }
  2014. this.removeAllListeners('removeListener');
  2015. this._events = new EventHandlers();
  2016. this._eventsCount = 0;
  2017. return this;
  2018. }
  2019. listeners = events[type];
  2020. if (typeof listeners === 'function') {
  2021. this.removeListener(type, listeners);
  2022. } else if (listeners) {
  2023. // LIFO order
  2024. do {
  2025. this.removeListener(type, listeners[listeners.length - 1]);
  2026. } while (listeners[0]);
  2027. }
  2028. return this;
  2029. };
  2030. EventEmitter.prototype.listeners = function listeners(type) {
  2031. var evlistener;
  2032. var ret;
  2033. var events = this._events;
  2034. if (!events)
  2035. ret = [];
  2036. else {
  2037. evlistener = events[type];
  2038. if (!evlistener)
  2039. ret = [];
  2040. else if (typeof evlistener === 'function')
  2041. ret = [evlistener.listener || evlistener];
  2042. else
  2043. ret = unwrapListeners(evlistener);
  2044. }
  2045. return ret;
  2046. };
  2047. EventEmitter.listenerCount = function(emitter, type) {
  2048. if (typeof emitter.listenerCount === 'function') {
  2049. return emitter.listenerCount(type);
  2050. } else {
  2051. return listenerCount$1.call(emitter, type);
  2052. }
  2053. };
  2054. EventEmitter.prototype.listenerCount = listenerCount$1;
  2055. function listenerCount$1(type) {
  2056. var events = this._events;
  2057. if (events) {
  2058. var evlistener = events[type];
  2059. if (typeof evlistener === 'function') {
  2060. return 1;
  2061. } else if (evlistener) {
  2062. return evlistener.length;
  2063. }
  2064. }
  2065. return 0;
  2066. }
  2067. EventEmitter.prototype.eventNames = function eventNames() {
  2068. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  2069. };
  2070. // About 1.5x faster than the two-arg version of Array#splice().
  2071. function spliceOne(list, index) {
  2072. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  2073. list[i] = list[k];
  2074. list.pop();
  2075. }
  2076. function arrayClone(arr, i) {
  2077. var copy = new Array(i);
  2078. while (i--)
  2079. copy[i] = arr[i];
  2080. return copy;
  2081. }
  2082. function unwrapListeners(arr) {
  2083. var ret = new Array(arr.length);
  2084. for (var i = 0; i < ret.length; ++i) {
  2085. ret[i] = arr[i].listener || arr[i];
  2086. }
  2087. return ret;
  2088. }
  2089. // shim for using process in browser
  2090. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  2091. function defaultSetTimout() {
  2092. throw new Error('setTimeout has not been defined');
  2093. }
  2094. function defaultClearTimeout () {
  2095. throw new Error('clearTimeout has not been defined');
  2096. }
  2097. var cachedSetTimeout = defaultSetTimout;
  2098. var cachedClearTimeout = defaultClearTimeout;
  2099. if (typeof global$1.setTimeout === 'function') {
  2100. cachedSetTimeout = setTimeout;
  2101. }
  2102. if (typeof global$1.clearTimeout === 'function') {
  2103. cachedClearTimeout = clearTimeout;
  2104. }
  2105. function runTimeout(fun) {
  2106. if (cachedSetTimeout === setTimeout) {
  2107. //normal enviroments in sane situations
  2108. return setTimeout(fun, 0);
  2109. }
  2110. // if setTimeout wasn't available but was latter defined
  2111. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2112. cachedSetTimeout = setTimeout;
  2113. return setTimeout(fun, 0);
  2114. }
  2115. try {
  2116. // when when somebody has screwed with setTimeout but no I.E. maddness
  2117. return cachedSetTimeout(fun, 0);
  2118. } catch(e){
  2119. try {
  2120. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2121. return cachedSetTimeout.call(null, fun, 0);
  2122. } catch(e){
  2123. // 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
  2124. return cachedSetTimeout.call(this, fun, 0);
  2125. }
  2126. }
  2127. }
  2128. function runClearTimeout(marker) {
  2129. if (cachedClearTimeout === clearTimeout) {
  2130. //normal enviroments in sane situations
  2131. return clearTimeout(marker);
  2132. }
  2133. // if clearTimeout wasn't available but was latter defined
  2134. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2135. cachedClearTimeout = clearTimeout;
  2136. return clearTimeout(marker);
  2137. }
  2138. try {
  2139. // when when somebody has screwed with setTimeout but no I.E. maddness
  2140. return cachedClearTimeout(marker);
  2141. } catch (e){
  2142. try {
  2143. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2144. return cachedClearTimeout.call(null, marker);
  2145. } catch (e){
  2146. // 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.
  2147. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  2148. return cachedClearTimeout.call(this, marker);
  2149. }
  2150. }
  2151. }
  2152. var queue = [];
  2153. var draining = false;
  2154. var currentQueue;
  2155. var queueIndex = -1;
  2156. function cleanUpNextTick() {
  2157. if (!draining || !currentQueue) {
  2158. return;
  2159. }
  2160. draining = false;
  2161. if (currentQueue.length) {
  2162. queue = currentQueue.concat(queue);
  2163. } else {
  2164. queueIndex = -1;
  2165. }
  2166. if (queue.length) {
  2167. drainQueue();
  2168. }
  2169. }
  2170. function drainQueue() {
  2171. if (draining) {
  2172. return;
  2173. }
  2174. var timeout = runTimeout(cleanUpNextTick);
  2175. draining = true;
  2176. var len = queue.length;
  2177. while(len) {
  2178. currentQueue = queue;
  2179. queue = [];
  2180. while (++queueIndex < len) {
  2181. if (currentQueue) {
  2182. currentQueue[queueIndex].run();
  2183. }
  2184. }
  2185. queueIndex = -1;
  2186. len = queue.length;
  2187. }
  2188. currentQueue = null;
  2189. draining = false;
  2190. runClearTimeout(timeout);
  2191. }
  2192. function nextTick(fun) {
  2193. var args = new Array(arguments.length - 1);
  2194. if (arguments.length > 1) {
  2195. for (var i = 1; i < arguments.length; i++) {
  2196. args[i - 1] = arguments[i];
  2197. }
  2198. }
  2199. queue.push(new Item(fun, args));
  2200. if (queue.length === 1 && !draining) {
  2201. runTimeout(drainQueue);
  2202. }
  2203. }
  2204. // v8 likes predictible objects
  2205. function Item(fun, array) {
  2206. this.fun = fun;
  2207. this.array = array;
  2208. }
  2209. Item.prototype.run = function () {
  2210. this.fun.apply(null, this.array);
  2211. };
  2212. var title = 'browser';
  2213. var platform = 'browser';
  2214. var browser = true;
  2215. var env = {};
  2216. var argv = [];
  2217. var version = ''; // empty string to avoid regexp issues
  2218. var versions = {};
  2219. var release = {};
  2220. var config = {};
  2221. function noop() {}
  2222. var on = noop;
  2223. var addListener = noop;
  2224. var once = noop;
  2225. var off = noop;
  2226. var removeListener = noop;
  2227. var removeAllListeners = noop;
  2228. var emit = noop;
  2229. function binding(name) {
  2230. throw new Error('process.binding is not supported');
  2231. }
  2232. function cwd () { return '/' }
  2233. function chdir (dir) {
  2234. throw new Error('process.chdir is not supported');
  2235. }function umask() { return 0; }
  2236. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  2237. var performance = global$1.performance || {};
  2238. var performanceNow =
  2239. performance.now ||
  2240. performance.mozNow ||
  2241. performance.msNow ||
  2242. performance.oNow ||
  2243. performance.webkitNow ||
  2244. function(){ return (new Date()).getTime() };
  2245. // generate timestamp or delta
  2246. // see http://nodejs.org/api/process.html#process_process_hrtime
  2247. function hrtime(previousTimestamp){
  2248. var clocktime = performanceNow.call(performance)*1e-3;
  2249. var seconds = Math.floor(clocktime);
  2250. var nanoseconds = Math.floor((clocktime%1)*1e9);
  2251. if (previousTimestamp) {
  2252. seconds = seconds - previousTimestamp[0];
  2253. nanoseconds = nanoseconds - previousTimestamp[1];
  2254. if (nanoseconds<0) {
  2255. seconds--;
  2256. nanoseconds += 1e9;
  2257. }
  2258. }
  2259. return [seconds,nanoseconds]
  2260. }
  2261. var startTime = new Date();
  2262. function uptime() {
  2263. var currentTime = new Date();
  2264. var dif = currentTime - startTime;
  2265. return dif / 1000;
  2266. }
  2267. var process = {
  2268. nextTick: nextTick,
  2269. title: title,
  2270. browser: browser,
  2271. env: env,
  2272. argv: argv,
  2273. version: version,
  2274. versions: versions,
  2275. on: on,
  2276. addListener: addListener,
  2277. once: once,
  2278. off: off,
  2279. removeListener: removeListener,
  2280. removeAllListeners: removeAllListeners,
  2281. emit: emit,
  2282. binding: binding,
  2283. cwd: cwd,
  2284. chdir: chdir,
  2285. umask: umask,
  2286. hrtime: hrtime,
  2287. platform: platform,
  2288. release: release,
  2289. config: config,
  2290. uptime: uptime
  2291. };
  2292. var inherits;
  2293. if (typeof Object.create === 'function'){
  2294. inherits = function inherits(ctor, superCtor) {
  2295. // implementation from standard node.js 'util' module
  2296. ctor.super_ = superCtor;
  2297. ctor.prototype = Object.create(superCtor.prototype, {
  2298. constructor: {
  2299. value: ctor,
  2300. enumerable: false,
  2301. writable: true,
  2302. configurable: true
  2303. }
  2304. });
  2305. };
  2306. } else {
  2307. inherits = function inherits(ctor, superCtor) {
  2308. ctor.super_ = superCtor;
  2309. var TempCtor = function () {};
  2310. TempCtor.prototype = superCtor.prototype;
  2311. ctor.prototype = new TempCtor();
  2312. ctor.prototype.constructor = ctor;
  2313. };
  2314. }
  2315. var inherits$1 = inherits;
  2316. var formatRegExp = /%[sdj%]/g;
  2317. function format(f) {
  2318. if (!isString(f)) {
  2319. var objects = [];
  2320. for (var i = 0; i < arguments.length; i++) {
  2321. objects.push(inspect(arguments[i]));
  2322. }
  2323. return objects.join(' ');
  2324. }
  2325. var i = 1;
  2326. var args = arguments;
  2327. var len = args.length;
  2328. var str = String(f).replace(formatRegExp, function(x) {
  2329. if (x === '%%') return '%';
  2330. if (i >= len) return x;
  2331. switch (x) {
  2332. case '%s': return String(args[i++]);
  2333. case '%d': return Number(args[i++]);
  2334. case '%j':
  2335. try {
  2336. return JSON.stringify(args[i++]);
  2337. } catch (_) {
  2338. return '[Circular]';
  2339. }
  2340. default:
  2341. return x;
  2342. }
  2343. });
  2344. for (var x = args[i]; i < len; x = args[++i]) {
  2345. if (isNull(x) || !isObject(x)) {
  2346. str += ' ' + x;
  2347. } else {
  2348. str += ' ' + inspect(x);
  2349. }
  2350. }
  2351. return str;
  2352. }
  2353. // Mark that a method should not be used.
  2354. // Returns a modified function which warns once by default.
  2355. // If --no-deprecation is set, then it is a no-op.
  2356. function deprecate(fn, msg) {
  2357. // Allow for deprecating things in the process of starting up.
  2358. if (isUndefined(global$1.process)) {
  2359. return function() {
  2360. return deprecate(fn, msg).apply(this, arguments);
  2361. };
  2362. }
  2363. if (process.noDeprecation === true) {
  2364. return fn;
  2365. }
  2366. var warned = false;
  2367. function deprecated() {
  2368. if (!warned) {
  2369. if (process.throwDeprecation) {
  2370. throw new Error(msg);
  2371. } else if (process.traceDeprecation) {
  2372. console.trace(msg);
  2373. } else {
  2374. console.error(msg);
  2375. }
  2376. warned = true;
  2377. }
  2378. return fn.apply(this, arguments);
  2379. }
  2380. return deprecated;
  2381. }
  2382. var debugs = {};
  2383. var debugEnviron;
  2384. function debuglog(set) {
  2385. if (isUndefined(debugEnviron))
  2386. debugEnviron = process.env.NODE_DEBUG || '';
  2387. set = set.toUpperCase();
  2388. if (!debugs[set]) {
  2389. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  2390. var pid = 0;
  2391. debugs[set] = function() {
  2392. var msg = format.apply(null, arguments);
  2393. console.error('%s %d: %s', set, pid, msg);
  2394. };
  2395. } else {
  2396. debugs[set] = function() {};
  2397. }
  2398. }
  2399. return debugs[set];
  2400. }
  2401. /**
  2402. * Echos the value of a value. Trys to print the value out
  2403. * in the best way possible given the different types.
  2404. *
  2405. * @param {Object} obj The object to print out.
  2406. * @param {Object} opts Optional options object that alters the output.
  2407. */
  2408. /* legacy: obj, showHidden, depth, colors*/
  2409. function inspect(obj, opts) {
  2410. // default options
  2411. var ctx = {
  2412. seen: [],
  2413. stylize: stylizeNoColor
  2414. };
  2415. // legacy...
  2416. if (arguments.length >= 3) ctx.depth = arguments[2];
  2417. if (arguments.length >= 4) ctx.colors = arguments[3];
  2418. if (isBoolean(opts)) {
  2419. // legacy...
  2420. ctx.showHidden = opts;
  2421. } else if (opts) {
  2422. // got an "options" object
  2423. _extend(ctx, opts);
  2424. }
  2425. // set default options
  2426. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  2427. if (isUndefined(ctx.depth)) ctx.depth = 2;
  2428. if (isUndefined(ctx.colors)) ctx.colors = false;
  2429. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  2430. if (ctx.colors) ctx.stylize = stylizeWithColor;
  2431. return formatValue(ctx, obj, ctx.depth);
  2432. }
  2433. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  2434. inspect.colors = {
  2435. 'bold' : [1, 22],
  2436. 'italic' : [3, 23],
  2437. 'underline' : [4, 24],
  2438. 'inverse' : [7, 27],
  2439. 'white' : [37, 39],
  2440. 'grey' : [90, 39],
  2441. 'black' : [30, 39],
  2442. 'blue' : [34, 39],
  2443. 'cyan' : [36, 39],
  2444. 'green' : [32, 39],
  2445. 'magenta' : [35, 39],
  2446. 'red' : [31, 39],
  2447. 'yellow' : [33, 39]
  2448. };
  2449. // Don't use 'blue' not visible on cmd.exe
  2450. inspect.styles = {
  2451. 'special': 'cyan',
  2452. 'number': 'yellow',
  2453. 'boolean': 'yellow',
  2454. 'undefined': 'grey',
  2455. 'null': 'bold',
  2456. 'string': 'green',
  2457. 'date': 'magenta',
  2458. // "name": intentionally not styling
  2459. 'regexp': 'red'
  2460. };
  2461. function stylizeWithColor(str, styleType) {
  2462. var style = inspect.styles[styleType];
  2463. if (style) {
  2464. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  2465. '\u001b[' + inspect.colors[style][1] + 'm';
  2466. } else {
  2467. return str;
  2468. }
  2469. }
  2470. function stylizeNoColor(str, styleType) {
  2471. return str;
  2472. }
  2473. function arrayToHash(array) {
  2474. var hash = {};
  2475. array.forEach(function(val, idx) {
  2476. hash[val] = true;
  2477. });
  2478. return hash;
  2479. }
  2480. function formatValue(ctx, value, recurseTimes) {
  2481. // Provide a hook for user-specified inspect functions.
  2482. // Check that value is an object with an inspect function on it
  2483. if (ctx.customInspect &&
  2484. value &&
  2485. isFunction(value.inspect) &&
  2486. // Filter out the util module, it's inspect function is special
  2487. value.inspect !== inspect &&
  2488. // Also filter out any prototype objects using the circular check.
  2489. !(value.constructor && value.constructor.prototype === value)) {
  2490. var ret = value.inspect(recurseTimes, ctx);
  2491. if (!isString(ret)) {
  2492. ret = formatValue(ctx, ret, recurseTimes);
  2493. }
  2494. return ret;
  2495. }
  2496. // Primitive types cannot have properties
  2497. var primitive = formatPrimitive(ctx, value);
  2498. if (primitive) {
  2499. return primitive;
  2500. }
  2501. // Look up the keys of the object.
  2502. var keys = Object.keys(value);
  2503. var visibleKeys = arrayToHash(keys);
  2504. if (ctx.showHidden) {
  2505. keys = Object.getOwnPropertyNames(value);
  2506. }
  2507. // IE doesn't make error fields non-enumerable
  2508. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  2509. if (isError(value)
  2510. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  2511. return formatError(value);
  2512. }
  2513. // Some type of object without properties can be shortcutted.
  2514. if (keys.length === 0) {
  2515. if (isFunction(value)) {
  2516. var name = value.name ? ': ' + value.name : '';
  2517. return ctx.stylize('[Function' + name + ']', 'special');
  2518. }
  2519. if (isRegExp(value)) {
  2520. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  2521. }
  2522. if (isDate(value)) {
  2523. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  2524. }
  2525. if (isError(value)) {
  2526. return formatError(value);
  2527. }
  2528. }
  2529. var base = '', array = false, braces = ['{', '}'];
  2530. // Make Array say that they are Array
  2531. if (isArray(value)) {
  2532. array = true;
  2533. braces = ['[', ']'];
  2534. }
  2535. // Make functions say that they are functions
  2536. if (isFunction(value)) {
  2537. var n = value.name ? ': ' + value.name : '';
  2538. base = ' [Function' + n + ']';
  2539. }
  2540. // Make RegExps say that they are RegExps
  2541. if (isRegExp(value)) {
  2542. base = ' ' + RegExp.prototype.toString.call(value);
  2543. }
  2544. // Make dates with properties first say the date
  2545. if (isDate(value)) {
  2546. base = ' ' + Date.prototype.toUTCString.call(value);
  2547. }
  2548. // Make error with message first say the error
  2549. if (isError(value)) {
  2550. base = ' ' + formatError(value);
  2551. }
  2552. if (keys.length === 0 && (!array || value.length == 0)) {
  2553. return braces[0] + base + braces[1];
  2554. }
  2555. if (recurseTimes < 0) {
  2556. if (isRegExp(value)) {
  2557. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  2558. } else {
  2559. return ctx.stylize('[Object]', 'special');
  2560. }
  2561. }
  2562. ctx.seen.push(value);
  2563. var output;
  2564. if (array) {
  2565. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  2566. } else {
  2567. output = keys.map(function(key) {
  2568. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  2569. });
  2570. }
  2571. ctx.seen.pop();
  2572. return reduceToSingleString(output, base, braces);
  2573. }
  2574. function formatPrimitive(ctx, value) {
  2575. if (isUndefined(value))
  2576. return ctx.stylize('undefined', 'undefined');
  2577. if (isString(value)) {
  2578. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  2579. .replace(/'/g, "\\'")
  2580. .replace(/\\"/g, '"') + '\'';
  2581. return ctx.stylize(simple, 'string');
  2582. }
  2583. if (isNumber(value))
  2584. return ctx.stylize('' + value, 'number');
  2585. if (isBoolean(value))
  2586. return ctx.stylize('' + value, 'boolean');
  2587. // For some reason typeof null is "object", so special case here.
  2588. if (isNull(value))
  2589. return ctx.stylize('null', 'null');
  2590. }
  2591. function formatError(value) {
  2592. return '[' + Error.prototype.toString.call(value) + ']';
  2593. }
  2594. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  2595. var output = [];
  2596. for (var i = 0, l = value.length; i < l; ++i) {
  2597. if (hasOwnProperty(value, String(i))) {
  2598. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  2599. String(i), true));
  2600. } else {
  2601. output.push('');
  2602. }
  2603. }
  2604. keys.forEach(function(key) {
  2605. if (!key.match(/^\d+$/)) {
  2606. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  2607. key, true));
  2608. }
  2609. });
  2610. return output;
  2611. }
  2612. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  2613. var name, str, desc;
  2614. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  2615. if (desc.get) {
  2616. if (desc.set) {
  2617. str = ctx.stylize('[Getter/Setter]', 'special');
  2618. } else {
  2619. str = ctx.stylize('[Getter]', 'special');
  2620. }
  2621. } else {
  2622. if (desc.set) {
  2623. str = ctx.stylize('[Setter]', 'special');
  2624. }
  2625. }
  2626. if (!hasOwnProperty(visibleKeys, key)) {
  2627. name = '[' + key + ']';
  2628. }
  2629. if (!str) {
  2630. if (ctx.seen.indexOf(desc.value) < 0) {
  2631. if (isNull(recurseTimes)) {
  2632. str = formatValue(ctx, desc.value, null);
  2633. } else {
  2634. str = formatValue(ctx, desc.value, recurseTimes - 1);
  2635. }
  2636. if (str.indexOf('\n') > -1) {
  2637. if (array) {
  2638. str = str.split('\n').map(function(line) {
  2639. return ' ' + line;
  2640. }).join('\n').substr(2);
  2641. } else {
  2642. str = '\n' + str.split('\n').map(function(line) {
  2643. return ' ' + line;
  2644. }).join('\n');
  2645. }
  2646. }
  2647. } else {
  2648. str = ctx.stylize('[Circular]', 'special');
  2649. }
  2650. }
  2651. if (isUndefined(name)) {
  2652. if (array && key.match(/^\d+$/)) {
  2653. return str;
  2654. }
  2655. name = JSON.stringify('' + key);
  2656. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  2657. name = name.substr(1, name.length - 2);
  2658. name = ctx.stylize(name, 'name');
  2659. } else {
  2660. name = name.replace(/'/g, "\\'")
  2661. .replace(/\\"/g, '"')
  2662. .replace(/(^"|"$)/g, "'");
  2663. name = ctx.stylize(name, 'string');
  2664. }
  2665. }
  2666. return name + ': ' + str;
  2667. }
  2668. function reduceToSingleString(output, base, braces) {
  2669. var length = output.reduce(function(prev, cur) {
  2670. if (cur.indexOf('\n') >= 0) ;
  2671. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  2672. }, 0);
  2673. if (length > 60) {
  2674. return braces[0] +
  2675. (base === '' ? '' : base + '\n ') +
  2676. ' ' +
  2677. output.join(',\n ') +
  2678. ' ' +
  2679. braces[1];
  2680. }
  2681. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  2682. }
  2683. // NOTE: These type checking functions intentionally don't use `instanceof`
  2684. // because it is fragile and can be easily faked with `Object.create()`.
  2685. function isArray(ar) {
  2686. return Array.isArray(ar);
  2687. }
  2688. function isBoolean(arg) {
  2689. return typeof arg === 'boolean';
  2690. }
  2691. function isNull(arg) {
  2692. return arg === null;
  2693. }
  2694. function isNumber(arg) {
  2695. return typeof arg === 'number';
  2696. }
  2697. function isString(arg) {
  2698. return typeof arg === 'string';
  2699. }
  2700. function isUndefined(arg) {
  2701. return arg === void 0;
  2702. }
  2703. function isRegExp(re) {
  2704. return isObject(re) && objectToString(re) === '[object RegExp]';
  2705. }
  2706. function isObject(arg) {
  2707. return typeof arg === 'object' && arg !== null;
  2708. }
  2709. function isDate(d) {
  2710. return isObject(d) && objectToString(d) === '[object Date]';
  2711. }
  2712. function isError(e) {
  2713. return isObject(e) &&
  2714. (objectToString(e) === '[object Error]' || e instanceof Error);
  2715. }
  2716. function isFunction(arg) {
  2717. return typeof arg === 'function';
  2718. }
  2719. function objectToString(o) {
  2720. return Object.prototype.toString.call(o);
  2721. }
  2722. function _extend(origin, add) {
  2723. // Don't do anything if add isn't an object
  2724. if (!add || !isObject(add)) return origin;
  2725. var keys = Object.keys(add);
  2726. var i = keys.length;
  2727. while (i--) {
  2728. origin[keys[i]] = add[keys[i]];
  2729. }
  2730. return origin;
  2731. }
  2732. function hasOwnProperty(obj, prop) {
  2733. return Object.prototype.hasOwnProperty.call(obj, prop);
  2734. }
  2735. function BufferList() {
  2736. this.head = null;
  2737. this.tail = null;
  2738. this.length = 0;
  2739. }
  2740. BufferList.prototype.push = function (v) {
  2741. var entry = { data: v, next: null };
  2742. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  2743. this.tail = entry;
  2744. ++this.length;
  2745. };
  2746. BufferList.prototype.unshift = function (v) {
  2747. var entry = { data: v, next: this.head };
  2748. if (this.length === 0) this.tail = entry;
  2749. this.head = entry;
  2750. ++this.length;
  2751. };
  2752. BufferList.prototype.shift = function () {
  2753. if (this.length === 0) return;
  2754. var ret = this.head.data;
  2755. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  2756. --this.length;
  2757. return ret;
  2758. };
  2759. BufferList.prototype.clear = function () {
  2760. this.head = this.tail = null;
  2761. this.length = 0;
  2762. };
  2763. BufferList.prototype.join = function (s) {
  2764. if (this.length === 0) return '';
  2765. var p = this.head;
  2766. var ret = '' + p.data;
  2767. while (p = p.next) {
  2768. ret += s + p.data;
  2769. }return ret;
  2770. };
  2771. BufferList.prototype.concat = function (n) {
  2772. if (this.length === 0) return Buffer.alloc(0);
  2773. if (this.length === 1) return this.head.data;
  2774. var ret = Buffer.allocUnsafe(n >>> 0);
  2775. var p = this.head;
  2776. var i = 0;
  2777. while (p) {
  2778. p.data.copy(ret, i);
  2779. i += p.data.length;
  2780. p = p.next;
  2781. }
  2782. return ret;
  2783. };
  2784. // Copyright Joyent, Inc. and other Node contributors.
  2785. //
  2786. // Permission is hereby granted, free of charge, to any person obtaining a
  2787. // copy of this software and associated documentation files (the
  2788. // "Software"), to deal in the Software without restriction, including
  2789. // without limitation the rights to use, copy, modify, merge, publish,
  2790. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2791. // persons to whom the Software is furnished to do so, subject to the
  2792. // following conditions:
  2793. //
  2794. // The above copyright notice and this permission notice shall be included
  2795. // in all copies or substantial portions of the Software.
  2796. //
  2797. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2798. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2799. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2800. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2801. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2802. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2803. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2804. var isBufferEncoding = Buffer.isEncoding
  2805. || function(encoding) {
  2806. switch (encoding && encoding.toLowerCase()) {
  2807. 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': return true;
  2808. default: return false;
  2809. }
  2810. };
  2811. function assertEncoding(encoding) {
  2812. if (encoding && !isBufferEncoding(encoding)) {
  2813. throw new Error('Unknown encoding: ' + encoding);
  2814. }
  2815. }
  2816. // StringDecoder provides an interface for efficiently splitting a series of
  2817. // buffers into a series of JS strings without breaking apart multi-byte
  2818. // characters. CESU-8 is handled as part of the UTF-8 encoding.
  2819. //
  2820. // @TODO Handling all encodings inside a single object makes it very difficult
  2821. // to reason about this code, so it should be split up in the future.
  2822. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  2823. // points as used by CESU-8.
  2824. function StringDecoder(encoding) {
  2825. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  2826. assertEncoding(encoding);
  2827. switch (this.encoding) {
  2828. case 'utf8':
  2829. // CESU-8 represents each of Surrogate Pair by 3-bytes
  2830. this.surrogateSize = 3;
  2831. break;
  2832. case 'ucs2':
  2833. case 'utf16le':
  2834. // UTF-16 represents each of Surrogate Pair by 2-bytes
  2835. this.surrogateSize = 2;
  2836. this.detectIncompleteChar = utf16DetectIncompleteChar;
  2837. break;
  2838. case 'base64':
  2839. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  2840. this.surrogateSize = 3;
  2841. this.detectIncompleteChar = base64DetectIncompleteChar;
  2842. break;
  2843. default:
  2844. this.write = passThroughWrite;
  2845. return;
  2846. }
  2847. // Enough space to store all bytes of a single character. UTF-8 needs 4
  2848. // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  2849. this.charBuffer = new Buffer(6);
  2850. // Number of bytes received for the current incomplete multi-byte character.
  2851. this.charReceived = 0;
  2852. // Number of bytes expected for the current incomplete multi-byte character.
  2853. this.charLength = 0;
  2854. }
  2855. // write decodes the given buffer and returns it as JS string that is
  2856. // guaranteed to not contain any partial multi-byte characters. Any partial
  2857. // character found at the end of the buffer is buffered up, and will be
  2858. // returned when calling write again with the remaining bytes.
  2859. //
  2860. // Note: Converting a Buffer containing an orphan surrogate to a String
  2861. // currently works, but converting a String to a Buffer (via `new Buffer`, or
  2862. // Buffer#write) will replace incomplete surrogates with the unicode
  2863. // replacement character. See https://codereview.chromium.org/121173009/ .
  2864. StringDecoder.prototype.write = function(buffer) {
  2865. var charStr = '';
  2866. // if our last write ended with an incomplete multibyte character
  2867. while (this.charLength) {
  2868. // determine how many remaining bytes this buffer has to offer for this char
  2869. var available = (buffer.length >= this.charLength - this.charReceived) ?
  2870. this.charLength - this.charReceived :
  2871. buffer.length;
  2872. // add the new bytes to the char buffer
  2873. buffer.copy(this.charBuffer, this.charReceived, 0, available);
  2874. this.charReceived += available;
  2875. if (this.charReceived < this.charLength) {
  2876. // still not enough chars in this buffer? wait for more ...
  2877. return '';
  2878. }
  2879. // remove bytes belonging to the current character from the buffer
  2880. buffer = buffer.slice(available, buffer.length);
  2881. // get the character that was split
  2882. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  2883. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  2884. var charCode = charStr.charCodeAt(charStr.length - 1);
  2885. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  2886. this.charLength += this.surrogateSize;
  2887. charStr = '';
  2888. continue;
  2889. }
  2890. this.charReceived = this.charLength = 0;
  2891. // if there are no more bytes in this buffer, just emit our char
  2892. if (buffer.length === 0) {
  2893. return charStr;
  2894. }
  2895. break;
  2896. }
  2897. // determine and set charLength / charReceived
  2898. this.detectIncompleteChar(buffer);
  2899. var end = buffer.length;
  2900. if (this.charLength) {
  2901. // buffer the incomplete character bytes we got
  2902. buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
  2903. end -= this.charReceived;
  2904. }
  2905. charStr += buffer.toString(this.encoding, 0, end);
  2906. var end = charStr.length - 1;
  2907. var charCode = charStr.charCodeAt(end);
  2908. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  2909. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  2910. var size = this.surrogateSize;
  2911. this.charLength += size;
  2912. this.charReceived += size;
  2913. this.charBuffer.copy(this.charBuffer, size, 0, size);
  2914. buffer.copy(this.charBuffer, 0, 0, size);
  2915. return charStr.substring(0, end);
  2916. }
  2917. // or just emit the charStr
  2918. return charStr;
  2919. };
  2920. // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  2921. // the end of the given buffer. If so, it sets this.charLength to the byte
  2922. // length that character, and sets this.charReceived to the number of bytes
  2923. // that are available for this character.
  2924. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  2925. // determine how many bytes we have to check at the end of this buffer
  2926. var i = (buffer.length >= 3) ? 3 : buffer.length;
  2927. // Figure out if one of the last i bytes of our buffer announces an
  2928. // incomplete char.
  2929. for (; i > 0; i--) {
  2930. var c = buffer[buffer.length - i];
  2931. // See http://en.wikipedia.org/wiki/UTF-8#Description
  2932. // 110XXXXX
  2933. if (i == 1 && c >> 5 == 0x06) {
  2934. this.charLength = 2;
  2935. break;
  2936. }
  2937. // 1110XXXX
  2938. if (i <= 2 && c >> 4 == 0x0E) {
  2939. this.charLength = 3;
  2940. break;
  2941. }
  2942. // 11110XXX
  2943. if (i <= 3 && c >> 3 == 0x1E) {
  2944. this.charLength = 4;
  2945. break;
  2946. }
  2947. }
  2948. this.charReceived = i;
  2949. };
  2950. StringDecoder.prototype.end = function(buffer) {
  2951. var res = '';
  2952. if (buffer && buffer.length)
  2953. res = this.write(buffer);
  2954. if (this.charReceived) {
  2955. var cr = this.charReceived;
  2956. var buf = this.charBuffer;
  2957. var enc = this.encoding;
  2958. res += buf.slice(0, cr).toString(enc);
  2959. }
  2960. return res;
  2961. };
  2962. function passThroughWrite(buffer) {
  2963. return buffer.toString(this.encoding);
  2964. }
  2965. function utf16DetectIncompleteChar(buffer) {
  2966. this.charReceived = buffer.length % 2;
  2967. this.charLength = this.charReceived ? 2 : 0;
  2968. }
  2969. function base64DetectIncompleteChar(buffer) {
  2970. this.charReceived = buffer.length % 3;
  2971. this.charLength = this.charReceived ? 3 : 0;
  2972. }
  2973. Readable.ReadableState = ReadableState;
  2974. var debug = debuglog('stream');
  2975. inherits$1(Readable, EventEmitter);
  2976. function prependListener(emitter, event, fn) {
  2977. // Sadly this is not cacheable as some libraries bundle their own
  2978. // event emitter implementation with them.
  2979. if (typeof emitter.prependListener === 'function') {
  2980. return emitter.prependListener(event, fn);
  2981. } else {
  2982. // This is a hack to make sure that our error handler is attached before any
  2983. // userland ones. NEVER DO THIS. This is here only because this code needs
  2984. // to continue to work with older versions of Node.js that do not include
  2985. // the prependListener() method. The goal is to eventually remove this hack.
  2986. if (!emitter._events || !emitter._events[event])
  2987. emitter.on(event, fn);
  2988. else if (Array.isArray(emitter._events[event]))
  2989. emitter._events[event].unshift(fn);
  2990. else
  2991. emitter._events[event] = [fn, emitter._events[event]];
  2992. }
  2993. }
  2994. function listenerCount (emitter, type) {
  2995. return emitter.listeners(type).length;
  2996. }
  2997. function ReadableState(options, stream) {
  2998. options = options || {};
  2999. // object stream flag. Used to make read(n) ignore n and to
  3000. // make all the buffer merging and length checks go away
  3001. this.objectMode = !!options.objectMode;
  3002. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  3003. // the point at which it stops calling _read() to fill the buffer
  3004. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  3005. var hwm = options.highWaterMark;
  3006. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  3007. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  3008. // cast to ints.
  3009. this.highWaterMark = ~ ~this.highWaterMark;
  3010. // A linked list is used to store data chunks instead of an array because the
  3011. // linked list can remove elements from the beginning faster than
  3012. // array.shift()
  3013. this.buffer = new BufferList();
  3014. this.length = 0;
  3015. this.pipes = null;
  3016. this.pipesCount = 0;
  3017. this.flowing = null;
  3018. this.ended = false;
  3019. this.endEmitted = false;
  3020. this.reading = false;
  3021. // a flag to be able to tell if the onwrite cb is called immediately,
  3022. // or on a later tick. We set this to true at first, because any
  3023. // actions that shouldn't happen until "later" should generally also
  3024. // not happen before the first write call.
  3025. this.sync = true;
  3026. // whenever we return null, then we set a flag to say
  3027. // that we're awaiting a 'readable' event emission.
  3028. this.needReadable = false;
  3029. this.emittedReadable = false;
  3030. this.readableListening = false;
  3031. this.resumeScheduled = false;
  3032. // Crypto is kind of old and crusty. Historically, its default string
  3033. // encoding is 'binary' so we have to make this configurable.
  3034. // Everything else in the universe uses 'utf8', though.
  3035. this.defaultEncoding = options.defaultEncoding || 'utf8';
  3036. // when piping, we only care about 'readable' events that happen
  3037. // after read()ing all the bytes and not getting any pushback.
  3038. this.ranOut = false;
  3039. // the number of writers that are awaiting a drain event in .pipe()s
  3040. this.awaitDrain = 0;
  3041. // if true, a maybeReadMore has been scheduled
  3042. this.readingMore = false;
  3043. this.decoder = null;
  3044. this.encoding = null;
  3045. if (options.encoding) {
  3046. this.decoder = new StringDecoder(options.encoding);
  3047. this.encoding = options.encoding;
  3048. }
  3049. }
  3050. function Readable(options) {
  3051. if (!(this instanceof Readable)) return new Readable(options);
  3052. this._readableState = new ReadableState(options, this);
  3053. // legacy
  3054. this.readable = true;
  3055. if (options && typeof options.read === 'function') this._read = options.read;
  3056. EventEmitter.call(this);
  3057. }
  3058. // Manually shove something into the read() buffer.
  3059. // This returns true if the highWaterMark has not been hit yet,
  3060. // similar to how Writable.write() returns true if you should
  3061. // write() some more.
  3062. Readable.prototype.push = function (chunk, encoding) {
  3063. var state = this._readableState;
  3064. if (!state.objectMode && typeof chunk === 'string') {
  3065. encoding = encoding || state.defaultEncoding;
  3066. if (encoding !== state.encoding) {
  3067. chunk = Buffer.from(chunk, encoding);
  3068. encoding = '';
  3069. }
  3070. }
  3071. return readableAddChunk(this, state, chunk, encoding, false);
  3072. };
  3073. // Unshift should *always* be something directly out of read()
  3074. Readable.prototype.unshift = function (chunk) {
  3075. var state = this._readableState;
  3076. return readableAddChunk(this, state, chunk, '', true);
  3077. };
  3078. Readable.prototype.isPaused = function () {
  3079. return this._readableState.flowing === false;
  3080. };
  3081. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  3082. var er = chunkInvalid(state, chunk);
  3083. if (er) {
  3084. stream.emit('error', er);
  3085. } else if (chunk === null) {
  3086. state.reading = false;
  3087. onEofChunk(stream, state);
  3088. } else if (state.objectMode || chunk && chunk.length > 0) {
  3089. if (state.ended && !addToFront) {
  3090. var e = new Error('stream.push() after EOF');
  3091. stream.emit('error', e);
  3092. } else if (state.endEmitted && addToFront) {
  3093. var _e = new Error('stream.unshift() after end event');
  3094. stream.emit('error', _e);
  3095. } else {
  3096. var skipAdd;
  3097. if (state.decoder && !addToFront && !encoding) {
  3098. chunk = state.decoder.write(chunk);
  3099. skipAdd = !state.objectMode && chunk.length === 0;
  3100. }
  3101. if (!addToFront) state.reading = false;
  3102. // Don't add to the buffer if we've decoded to an empty string chunk and
  3103. // we're not in object mode
  3104. if (!skipAdd) {
  3105. // if we want the data now, just emit it.
  3106. if (state.flowing && state.length === 0 && !state.sync) {
  3107. stream.emit('data', chunk);
  3108. stream.read(0);
  3109. } else {
  3110. // update the buffer info.
  3111. state.length += state.objectMode ? 1 : chunk.length;
  3112. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  3113. if (state.needReadable) emitReadable(stream);
  3114. }
  3115. }
  3116. maybeReadMore(stream, state);
  3117. }
  3118. } else if (!addToFront) {
  3119. state.reading = false;
  3120. }
  3121. return needMoreData(state);
  3122. }
  3123. // if it's past the high water mark, we can push in some more.
  3124. // Also, if we have no data yet, we can stand some
  3125. // more bytes. This is to work around cases where hwm=0,
  3126. // such as the repl. Also, if the push() triggered a
  3127. // readable event, and the user called read(largeNumber) such that
  3128. // needReadable was set, then we ought to push more, so that another
  3129. // 'readable' event will be triggered.
  3130. function needMoreData(state) {
  3131. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  3132. }
  3133. // backwards compatibility.
  3134. Readable.prototype.setEncoding = function (enc) {
  3135. this._readableState.decoder = new StringDecoder(enc);
  3136. this._readableState.encoding = enc;
  3137. return this;
  3138. };
  3139. // Don't raise the hwm > 8MB
  3140. var MAX_HWM = 0x800000;
  3141. function computeNewHighWaterMark(n) {
  3142. if (n >= MAX_HWM) {
  3143. n = MAX_HWM;
  3144. } else {
  3145. // Get the next highest power of 2 to prevent increasing hwm excessively in
  3146. // tiny amounts
  3147. n--;
  3148. n |= n >>> 1;
  3149. n |= n >>> 2;
  3150. n |= n >>> 4;
  3151. n |= n >>> 8;
  3152. n |= n >>> 16;
  3153. n++;
  3154. }
  3155. return n;
  3156. }
  3157. // This function is designed to be inlinable, so please take care when making
  3158. // changes to the function body.
  3159. function howMuchToRead(n, state) {
  3160. if (n <= 0 || state.length === 0 && state.ended) return 0;
  3161. if (state.objectMode) return 1;
  3162. if (n !== n) {
  3163. // Only flow one buffer at a time
  3164. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  3165. }
  3166. // If we're asking for more than the current hwm, then raise the hwm.
  3167. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  3168. if (n <= state.length) return n;
  3169. // Don't have enough
  3170. if (!state.ended) {
  3171. state.needReadable = true;
  3172. return 0;
  3173. }
  3174. return state.length;
  3175. }
  3176. // you can override either this method, or the async _read(n) below.
  3177. Readable.prototype.read = function (n) {
  3178. debug('read', n);
  3179. n = parseInt(n, 10);
  3180. var state = this._readableState;
  3181. var nOrig = n;
  3182. if (n !== 0) state.emittedReadable = false;
  3183. // if we're doing read(0) to trigger a readable event, but we
  3184. // already have a bunch of data in the buffer, then just trigger
  3185. // the 'readable' event and move on.
  3186. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  3187. debug('read: emitReadable', state.length, state.ended);
  3188. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  3189. return null;
  3190. }
  3191. n = howMuchToRead(n, state);
  3192. // if we've ended, and we're now clear, then finish it up.
  3193. if (n === 0 && state.ended) {
  3194. if (state.length === 0) endReadable(this);
  3195. return null;
  3196. }
  3197. // All the actual chunk generation logic needs to be
  3198. // *below* the call to _read. The reason is that in certain
  3199. // synthetic stream cases, such as passthrough streams, _read
  3200. // may be a completely synchronous operation which may change
  3201. // the state of the read buffer, providing enough data when
  3202. // before there was *not* enough.
  3203. //
  3204. // So, the steps are:
  3205. // 1. Figure out what the state of things will be after we do
  3206. // a read from the buffer.
  3207. //
  3208. // 2. If that resulting state will trigger a _read, then call _read.
  3209. // Note that this may be asynchronous, or synchronous. Yes, it is
  3210. // deeply ugly to write APIs this way, but that still doesn't mean
  3211. // that the Readable class should behave improperly, as streams are
  3212. // designed to be sync/async agnostic.
  3213. // Take note if the _read call is sync or async (ie, if the read call
  3214. // has returned yet), so that we know whether or not it's safe to emit
  3215. // 'readable' etc.
  3216. //
  3217. // 3. Actually pull the requested chunks out of the buffer and return.
  3218. // if we need a readable event, then we need to do some reading.
  3219. var doRead = state.needReadable;
  3220. debug('need readable', doRead);
  3221. // if we currently have less than the highWaterMark, then also read some
  3222. if (state.length === 0 || state.length - n < state.highWaterMark) {
  3223. doRead = true;
  3224. debug('length less than watermark', doRead);
  3225. }
  3226. // however, if we've ended, then there's no point, and if we're already
  3227. // reading, then it's unnecessary.
  3228. if (state.ended || state.reading) {
  3229. doRead = false;
  3230. debug('reading or ended', doRead);
  3231. } else if (doRead) {
  3232. debug('do read');
  3233. state.reading = true;
  3234. state.sync = true;
  3235. // if the length is currently zero, then we *need* a readable event.
  3236. if (state.length === 0) state.needReadable = true;
  3237. // call internal read method
  3238. this._read(state.highWaterMark);
  3239. state.sync = false;
  3240. // If _read pushed data synchronously, then `reading` will be false,
  3241. // and we need to re-evaluate how much data we can return to the user.
  3242. if (!state.reading) n = howMuchToRead(nOrig, state);
  3243. }
  3244. var ret;
  3245. if (n > 0) ret = fromList(n, state);else ret = null;
  3246. if (ret === null) {
  3247. state.needReadable = true;
  3248. n = 0;
  3249. } else {
  3250. state.length -= n;
  3251. }
  3252. if (state.length === 0) {
  3253. // If we have nothing in the buffer, then we want to know
  3254. // as soon as we *do* get something into the buffer.
  3255. if (!state.ended) state.needReadable = true;
  3256. // If we tried to read() past the EOF, then emit end on the next tick.
  3257. if (nOrig !== n && state.ended) endReadable(this);
  3258. }
  3259. if (ret !== null) this.emit('data', ret);
  3260. return ret;
  3261. };
  3262. function chunkInvalid(state, chunk) {
  3263. var er = null;
  3264. if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
  3265. er = new TypeError('Invalid non-string/buffer chunk');
  3266. }
  3267. return er;
  3268. }
  3269. function onEofChunk(stream, state) {
  3270. if (state.ended) return;
  3271. if (state.decoder) {
  3272. var chunk = state.decoder.end();
  3273. if (chunk && chunk.length) {
  3274. state.buffer.push(chunk);
  3275. state.length += state.objectMode ? 1 : chunk.length;
  3276. }
  3277. }
  3278. state.ended = true;
  3279. // emit 'readable' now to make sure it gets picked up.
  3280. emitReadable(stream);
  3281. }
  3282. // Don't emit readable right away in sync mode, because this can trigger
  3283. // another read() call => stack overflow. This way, it might trigger
  3284. // a nextTick recursion warning, but that's not so bad.
  3285. function emitReadable(stream) {
  3286. var state = stream._readableState;
  3287. state.needReadable = false;
  3288. if (!state.emittedReadable) {
  3289. debug('emitReadable', state.flowing);
  3290. state.emittedReadable = true;
  3291. if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream);
  3292. }
  3293. }
  3294. function emitReadable_(stream) {
  3295. debug('emit readable');
  3296. stream.emit('readable');
  3297. flow(stream);
  3298. }
  3299. // at this point, the user has presumably seen the 'readable' event,
  3300. // and called read() to consume some data. that may have triggered
  3301. // in turn another _read(n) call, in which case reading = true if
  3302. // it's in progress.
  3303. // However, if we're not ended, or reading, and the length < hwm,
  3304. // then go ahead and try to read some more preemptively.
  3305. function maybeReadMore(stream, state) {
  3306. if (!state.readingMore) {
  3307. state.readingMore = true;
  3308. nextTick(maybeReadMore_, stream, state);
  3309. }
  3310. }
  3311. function maybeReadMore_(stream, state) {
  3312. var len = state.length;
  3313. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  3314. debug('maybeReadMore read 0');
  3315. stream.read(0);
  3316. if (len === state.length)
  3317. // didn't get any data, stop spinning.
  3318. break;else len = state.length;
  3319. }
  3320. state.readingMore = false;
  3321. }
  3322. // abstract method. to be overridden in specific implementation classes.
  3323. // call cb(er, data) where data is <= n in length.
  3324. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  3325. // arbitrary, and perhaps not very meaningful.
  3326. Readable.prototype._read = function (n) {
  3327. this.emit('error', new Error('not implemented'));
  3328. };
  3329. Readable.prototype.pipe = function (dest, pipeOpts) {
  3330. var src = this;
  3331. var state = this._readableState;
  3332. switch (state.pipesCount) {
  3333. case 0:
  3334. state.pipes = dest;
  3335. break;
  3336. case 1:
  3337. state.pipes = [state.pipes, dest];
  3338. break;
  3339. default:
  3340. state.pipes.push(dest);
  3341. break;
  3342. }
  3343. state.pipesCount += 1;
  3344. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  3345. var doEnd = (!pipeOpts || pipeOpts.end !== false);
  3346. var endFn = doEnd ? onend : cleanup;
  3347. if (state.endEmitted) nextTick(endFn);else src.once('end', endFn);
  3348. dest.on('unpipe', onunpipe);
  3349. function onunpipe(readable) {
  3350. debug('onunpipe');
  3351. if (readable === src) {
  3352. cleanup();
  3353. }
  3354. }
  3355. function onend() {
  3356. debug('onend');
  3357. dest.end();
  3358. }
  3359. // when the dest drains, it reduces the awaitDrain counter
  3360. // on the source. This would be more elegant with a .once()
  3361. // handler in flow(), but adding and removing repeatedly is
  3362. // too slow.
  3363. var ondrain = pipeOnDrain(src);
  3364. dest.on('drain', ondrain);
  3365. var cleanedUp = false;
  3366. function cleanup() {
  3367. debug('cleanup');
  3368. // cleanup event handlers once the pipe is broken
  3369. dest.removeListener('close', onclose);
  3370. dest.removeListener('finish', onfinish);
  3371. dest.removeListener('drain', ondrain);
  3372. dest.removeListener('error', onerror);
  3373. dest.removeListener('unpipe', onunpipe);
  3374. src.removeListener('end', onend);
  3375. src.removeListener('end', cleanup);
  3376. src.removeListener('data', ondata);
  3377. cleanedUp = true;
  3378. // if the reader is waiting for a drain event from this
  3379. // specific writer, then it would cause it to never start
  3380. // flowing again.
  3381. // So, if this is awaiting a drain, then we just call it now.
  3382. // If we don't know, then assume that we are waiting for one.
  3383. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  3384. }
  3385. // If the user pushes more data while we're writing to dest then we'll end up
  3386. // in ondata again. However, we only want to increase awaitDrain once because
  3387. // dest will only emit one 'drain' event for the multiple writes.
  3388. // => Introduce a guard on increasing awaitDrain.
  3389. var increasedAwaitDrain = false;
  3390. src.on('data', ondata);
  3391. function ondata(chunk) {
  3392. debug('ondata');
  3393. increasedAwaitDrain = false;
  3394. var ret = dest.write(chunk);
  3395. if (false === ret && !increasedAwaitDrain) {
  3396. // If the user unpiped during `dest.write()`, it is possible
  3397. // to get stuck in a permanently paused state if that write
  3398. // also returned false.
  3399. // => Check whether `dest` is still a piping destination.
  3400. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  3401. debug('false write response, pause', src._readableState.awaitDrain);
  3402. src._readableState.awaitDrain++;
  3403. increasedAwaitDrain = true;
  3404. }
  3405. src.pause();
  3406. }
  3407. }
  3408. // if the dest has an error, then stop piping into it.
  3409. // however, don't suppress the throwing behavior for this.
  3410. function onerror(er) {
  3411. debug('onerror', er);
  3412. unpipe();
  3413. dest.removeListener('error', onerror);
  3414. if (listenerCount(dest, 'error') === 0) dest.emit('error', er);
  3415. }
  3416. // Make sure our error handler is attached before userland ones.
  3417. prependListener(dest, 'error', onerror);
  3418. // Both close and finish should trigger unpipe, but only once.
  3419. function onclose() {
  3420. dest.removeListener('finish', onfinish);
  3421. unpipe();
  3422. }
  3423. dest.once('close', onclose);
  3424. function onfinish() {
  3425. debug('onfinish');
  3426. dest.removeListener('close', onclose);
  3427. unpipe();
  3428. }
  3429. dest.once('finish', onfinish);
  3430. function unpipe() {
  3431. debug('unpipe');
  3432. src.unpipe(dest);
  3433. }
  3434. // tell the dest that it's being piped to
  3435. dest.emit('pipe', src);
  3436. // start the flow if it hasn't been started already.
  3437. if (!state.flowing) {
  3438. debug('pipe resume');
  3439. src.resume();
  3440. }
  3441. return dest;
  3442. };
  3443. function pipeOnDrain(src) {
  3444. return function () {
  3445. var state = src._readableState;
  3446. debug('pipeOnDrain', state.awaitDrain);
  3447. if (state.awaitDrain) state.awaitDrain--;
  3448. if (state.awaitDrain === 0 && src.listeners('data').length) {
  3449. state.flowing = true;
  3450. flow(src);
  3451. }
  3452. };
  3453. }
  3454. Readable.prototype.unpipe = function (dest) {
  3455. var state = this._readableState;
  3456. // if we're not piping anywhere, then do nothing.
  3457. if (state.pipesCount === 0) return this;
  3458. // just one destination. most common case.
  3459. if (state.pipesCount === 1) {
  3460. // passed in one, but it's not the right one.
  3461. if (dest && dest !== state.pipes) return this;
  3462. if (!dest) dest = state.pipes;
  3463. // got a match.
  3464. state.pipes = null;
  3465. state.pipesCount = 0;
  3466. state.flowing = false;
  3467. if (dest) dest.emit('unpipe', this);
  3468. return this;
  3469. }
  3470. // slow case. multiple pipe destinations.
  3471. if (!dest) {
  3472. // remove all.
  3473. var dests = state.pipes;
  3474. var len = state.pipesCount;
  3475. state.pipes = null;
  3476. state.pipesCount = 0;
  3477. state.flowing = false;
  3478. for (var _i = 0; _i < len; _i++) {
  3479. dests[_i].emit('unpipe', this);
  3480. }return this;
  3481. }
  3482. // try to find the right one.
  3483. var i = indexOf(state.pipes, dest);
  3484. if (i === -1) return this;
  3485. state.pipes.splice(i, 1);
  3486. state.pipesCount -= 1;
  3487. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  3488. dest.emit('unpipe', this);
  3489. return this;
  3490. };
  3491. // set up data events if they are asked for
  3492. // Ensure readable listeners eventually get something
  3493. Readable.prototype.on = function (ev, fn) {
  3494. var res = EventEmitter.prototype.on.call(this, ev, fn);
  3495. if (ev === 'data') {
  3496. // Start flowing on next tick if stream isn't explicitly paused
  3497. if (this._readableState.flowing !== false) this.resume();
  3498. } else if (ev === 'readable') {
  3499. var state = this._readableState;
  3500. if (!state.endEmitted && !state.readableListening) {
  3501. state.readableListening = state.needReadable = true;
  3502. state.emittedReadable = false;
  3503. if (!state.reading) {
  3504. nextTick(nReadingNextTick, this);
  3505. } else if (state.length) {
  3506. emitReadable(this);
  3507. }
  3508. }
  3509. }
  3510. return res;
  3511. };
  3512. Readable.prototype.addListener = Readable.prototype.on;
  3513. function nReadingNextTick(self) {
  3514. debug('readable nexttick read 0');
  3515. self.read(0);
  3516. }
  3517. // pause() and resume() are remnants of the legacy readable stream API
  3518. // If the user uses them, then switch into old mode.
  3519. Readable.prototype.resume = function () {
  3520. var state = this._readableState;
  3521. if (!state.flowing) {
  3522. debug('resume');
  3523. state.flowing = true;
  3524. resume(this, state);
  3525. }
  3526. return this;
  3527. };
  3528. function resume(stream, state) {
  3529. if (!state.resumeScheduled) {
  3530. state.resumeScheduled = true;
  3531. nextTick(resume_, stream, state);
  3532. }
  3533. }
  3534. function resume_(stream, state) {
  3535. if (!state.reading) {
  3536. debug('resume read 0');
  3537. stream.read(0);
  3538. }
  3539. state.resumeScheduled = false;
  3540. state.awaitDrain = 0;
  3541. stream.emit('resume');
  3542. flow(stream);
  3543. if (state.flowing && !state.reading) stream.read(0);
  3544. }
  3545. Readable.prototype.pause = function () {
  3546. debug('call pause flowing=%j', this._readableState.flowing);
  3547. if (false !== this._readableState.flowing) {
  3548. debug('pause');
  3549. this._readableState.flowing = false;
  3550. this.emit('pause');
  3551. }
  3552. return this;
  3553. };
  3554. function flow(stream) {
  3555. var state = stream._readableState;
  3556. debug('flow', state.flowing);
  3557. while (state.flowing && stream.read() !== null) {}
  3558. }
  3559. // wrap an old-style stream as the async data source.
  3560. // This is *not* part of the readable stream interface.
  3561. // It is an ugly unfortunate mess of history.
  3562. Readable.prototype.wrap = function (stream) {
  3563. var state = this._readableState;
  3564. var paused = false;
  3565. var self = this;
  3566. stream.on('end', function () {
  3567. debug('wrapped end');
  3568. if (state.decoder && !state.ended) {
  3569. var chunk = state.decoder.end();
  3570. if (chunk && chunk.length) self.push(chunk);
  3571. }
  3572. self.push(null);
  3573. });
  3574. stream.on('data', function (chunk) {
  3575. debug('wrapped data');
  3576. if (state.decoder) chunk = state.decoder.write(chunk);
  3577. // don't skip over falsy values in objectMode
  3578. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  3579. var ret = self.push(chunk);
  3580. if (!ret) {
  3581. paused = true;
  3582. stream.pause();
  3583. }
  3584. });
  3585. // proxy all the other methods.
  3586. // important when wrapping filters and duplexes.
  3587. for (var i in stream) {
  3588. if (this[i] === undefined && typeof stream[i] === 'function') {
  3589. this[i] = function (method) {
  3590. return function () {
  3591. return stream[method].apply(stream, arguments);
  3592. };
  3593. }(i);
  3594. }
  3595. }
  3596. // proxy certain important events.
  3597. var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  3598. forEach(events, function (ev) {
  3599. stream.on(ev, self.emit.bind(self, ev));
  3600. });
  3601. // when we try to consume some more bytes, simply unpause the
  3602. // underlying stream.
  3603. self._read = function (n) {
  3604. debug('wrapped _read', n);
  3605. if (paused) {
  3606. paused = false;
  3607. stream.resume();
  3608. }
  3609. };
  3610. return self;
  3611. };
  3612. // exposed for testing purposes only.
  3613. Readable._fromList = fromList;
  3614. // Pluck off n bytes from an array of buffers.
  3615. // Length is the combined lengths of all the buffers in the list.
  3616. // This function is designed to be inlinable, so please take care when making
  3617. // changes to the function body.
  3618. function fromList(n, state) {
  3619. // nothing buffered
  3620. if (state.length === 0) return null;
  3621. var ret;
  3622. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  3623. // read it all, truncate the list
  3624. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  3625. state.buffer.clear();
  3626. } else {
  3627. // read part of list
  3628. ret = fromListPartial(n, state.buffer, state.decoder);
  3629. }
  3630. return ret;
  3631. }
  3632. // Extracts only enough buffered data to satisfy the amount requested.
  3633. // This function is designed to be inlinable, so please take care when making
  3634. // changes to the function body.
  3635. function fromListPartial(n, list, hasStrings) {
  3636. var ret;
  3637. if (n < list.head.data.length) {
  3638. // slice is the same for buffers and strings
  3639. ret = list.head.data.slice(0, n);
  3640. list.head.data = list.head.data.slice(n);
  3641. } else if (n === list.head.data.length) {
  3642. // first chunk is a perfect match
  3643. ret = list.shift();
  3644. } else {
  3645. // result spans more than one buffer
  3646. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  3647. }
  3648. return ret;
  3649. }
  3650. // Copies a specified amount of characters from the list of buffered data
  3651. // chunks.
  3652. // This function is designed to be inlinable, so please take care when making
  3653. // changes to the function body.
  3654. function copyFromBufferString(n, list) {
  3655. var p = list.head;
  3656. var c = 1;
  3657. var ret = p.data;
  3658. n -= ret.length;
  3659. while (p = p.next) {
  3660. var str = p.data;
  3661. var nb = n > str.length ? str.length : n;
  3662. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  3663. n -= nb;
  3664. if (n === 0) {
  3665. if (nb === str.length) {
  3666. ++c;
  3667. if (p.next) list.head = p.next;else list.head = list.tail = null;
  3668. } else {
  3669. list.head = p;
  3670. p.data = str.slice(nb);
  3671. }
  3672. break;
  3673. }
  3674. ++c;
  3675. }
  3676. list.length -= c;
  3677. return ret;
  3678. }
  3679. // Copies a specified amount of bytes from the list of buffered data chunks.
  3680. // This function is designed to be inlinable, so please take care when making
  3681. // changes to the function body.
  3682. function copyFromBuffer(n, list) {
  3683. var ret = Buffer.allocUnsafe(n);
  3684. var p = list.head;
  3685. var c = 1;
  3686. p.data.copy(ret);
  3687. n -= p.data.length;
  3688. while (p = p.next) {
  3689. var buf = p.data;
  3690. var nb = n > buf.length ? buf.length : n;
  3691. buf.copy(ret, ret.length - n, 0, nb);
  3692. n -= nb;
  3693. if (n === 0) {
  3694. if (nb === buf.length) {
  3695. ++c;
  3696. if (p.next) list.head = p.next;else list.head = list.tail = null;
  3697. } else {
  3698. list.head = p;
  3699. p.data = buf.slice(nb);
  3700. }
  3701. break;
  3702. }
  3703. ++c;
  3704. }
  3705. list.length -= c;
  3706. return ret;
  3707. }
  3708. function endReadable(stream) {
  3709. var state = stream._readableState;
  3710. // If we get here before consuming all the bytes, then that is a
  3711. // bug in node. Should never happen.
  3712. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  3713. if (!state.endEmitted) {
  3714. state.ended = true;
  3715. nextTick(endReadableNT, state, stream);
  3716. }
  3717. }
  3718. function endReadableNT(state, stream) {
  3719. // Check that we didn't get one last unshift.
  3720. if (!state.endEmitted && state.length === 0) {
  3721. state.endEmitted = true;
  3722. stream.readable = false;
  3723. stream.emit('end');
  3724. }
  3725. }
  3726. function forEach(xs, f) {
  3727. for (var i = 0, l = xs.length; i < l; i++) {
  3728. f(xs[i], i);
  3729. }
  3730. }
  3731. function indexOf(xs, x) {
  3732. for (var i = 0, l = xs.length; i < l; i++) {
  3733. if (xs[i] === x) return i;
  3734. }
  3735. return -1;
  3736. }
  3737. // A bit simpler than readable streams.
  3738. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  3739. // the drain event emission and buffering.
  3740. Writable.WritableState = WritableState;
  3741. inherits$1(Writable, EventEmitter);
  3742. function nop() {}
  3743. function WriteReq(chunk, encoding, cb) {
  3744. this.chunk = chunk;
  3745. this.encoding = encoding;
  3746. this.callback = cb;
  3747. this.next = null;
  3748. }
  3749. function WritableState(options, stream) {
  3750. Object.defineProperty(this, 'buffer', {
  3751. get: deprecate(function () {
  3752. return this.getBuffer();
  3753. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
  3754. });
  3755. options = options || {};
  3756. // object stream flag to indicate whether or not this stream
  3757. // contains buffers or objects.
  3758. this.objectMode = !!options.objectMode;
  3759. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  3760. // the point at which write() starts returning false
  3761. // Note: 0 is a valid value, means that we always return false if
  3762. // the entire buffer is not flushed immediately on write()
  3763. var hwm = options.highWaterMark;
  3764. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  3765. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  3766. // cast to ints.
  3767. this.highWaterMark = ~ ~this.highWaterMark;
  3768. this.needDrain = false;
  3769. // at the start of calling end()
  3770. this.ending = false;
  3771. // when end() has been called, and returned
  3772. this.ended = false;
  3773. // when 'finish' is emitted
  3774. this.finished = false;
  3775. // should we decode strings into buffers before passing to _write?
  3776. // this is here so that some node-core streams can optimize string
  3777. // handling at a lower level.
  3778. var noDecode = options.decodeStrings === false;
  3779. this.decodeStrings = !noDecode;
  3780. // Crypto is kind of old and crusty. Historically, its default string
  3781. // encoding is 'binary' so we have to make this configurable.
  3782. // Everything else in the universe uses 'utf8', though.
  3783. this.defaultEncoding = options.defaultEncoding || 'utf8';
  3784. // not an actual buffer we keep track of, but a measurement
  3785. // of how much we're waiting to get pushed to some underlying
  3786. // socket or file.
  3787. this.length = 0;
  3788. // a flag to see when we're in the middle of a write.
  3789. this.writing = false;
  3790. // when true all writes will be buffered until .uncork() call
  3791. this.corked = 0;
  3792. // a flag to be able to tell if the onwrite cb is called immediately,
  3793. // or on a later tick. We set this to true at first, because any
  3794. // actions that shouldn't happen until "later" should generally also
  3795. // not happen before the first write call.
  3796. this.sync = true;
  3797. // a flag to know if we're processing previously buffered items, which
  3798. // may call the _write() callback in the same tick, so that we don't
  3799. // end up in an overlapped onwrite situation.
  3800. this.bufferProcessing = false;
  3801. // the callback that's passed to _write(chunk,cb)
  3802. this.onwrite = function (er) {
  3803. onwrite(stream, er);
  3804. };
  3805. // the callback that the user supplies to write(chunk,encoding,cb)
  3806. this.writecb = null;
  3807. // the amount that is being written when _write is called.
  3808. this.writelen = 0;
  3809. this.bufferedRequest = null;
  3810. this.lastBufferedRequest = null;
  3811. // number of pending user-supplied write callbacks
  3812. // this must be 0 before 'finish' can be emitted
  3813. this.pendingcb = 0;
  3814. // emit prefinish if the only thing we're waiting for is _write cbs
  3815. // This is relevant for synchronous Transform streams
  3816. this.prefinished = false;
  3817. // True if the error was already emitted and should not be thrown again
  3818. this.errorEmitted = false;
  3819. // count buffered requests
  3820. this.bufferedRequestCount = 0;
  3821. // allocate the first CorkedRequest, there is always
  3822. // one allocated and free to use, and we maintain at most two
  3823. this.corkedRequestsFree = new CorkedRequest(this);
  3824. }
  3825. WritableState.prototype.getBuffer = function writableStateGetBuffer() {
  3826. var current = this.bufferedRequest;
  3827. var out = [];
  3828. while (current) {
  3829. out.push(current);
  3830. current = current.next;
  3831. }
  3832. return out;
  3833. };
  3834. function Writable(options) {
  3835. // Writable ctor is applied to Duplexes, though they're not
  3836. // instanceof Writable, they're instanceof Readable.
  3837. if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
  3838. this._writableState = new WritableState(options, this);
  3839. // legacy.
  3840. this.writable = true;
  3841. if (options) {
  3842. if (typeof options.write === 'function') this._write = options.write;
  3843. if (typeof options.writev === 'function') this._writev = options.writev;
  3844. }
  3845. EventEmitter.call(this);
  3846. }
  3847. // Otherwise people can pipe Writable streams, which is just wrong.
  3848. Writable.prototype.pipe = function () {
  3849. this.emit('error', new Error('Cannot pipe, not readable'));
  3850. };
  3851. function writeAfterEnd(stream, cb) {
  3852. var er = new Error('write after end');
  3853. // TODO: defer error events consistently everywhere, not just the cb
  3854. stream.emit('error', er);
  3855. nextTick(cb, er);
  3856. }
  3857. // If we get something that is not a buffer, string, null, or undefined,
  3858. // and we're not in objectMode, then that's an error.
  3859. // Otherwise stream chunks are all considered to be of length=1, and the
  3860. // watermarks determine how many objects to keep in the buffer, rather than
  3861. // how many bytes or characters.
  3862. function validChunk(stream, state, chunk, cb) {
  3863. var valid = true;
  3864. var er = false;
  3865. // Always throw error if a null is written
  3866. // if we are not in object mode then throw
  3867. // if it is not a buffer, string, or undefined.
  3868. if (chunk === null) {
  3869. er = new TypeError('May not write null values to stream');
  3870. } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  3871. er = new TypeError('Invalid non-string/buffer chunk');
  3872. }
  3873. if (er) {
  3874. stream.emit('error', er);
  3875. nextTick(cb, er);
  3876. valid = false;
  3877. }
  3878. return valid;
  3879. }
  3880. Writable.prototype.write = function (chunk, encoding, cb) {
  3881. var state = this._writableState;
  3882. var ret = false;
  3883. if (typeof encoding === 'function') {
  3884. cb = encoding;
  3885. encoding = null;
  3886. }
  3887. if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  3888. if (typeof cb !== 'function') cb = nop;
  3889. if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
  3890. state.pendingcb++;
  3891. ret = writeOrBuffer(this, state, chunk, encoding, cb);
  3892. }
  3893. return ret;
  3894. };
  3895. Writable.prototype.cork = function () {
  3896. var state = this._writableState;
  3897. state.corked++;
  3898. };
  3899. Writable.prototype.uncork = function () {
  3900. var state = this._writableState;
  3901. if (state.corked) {
  3902. state.corked--;
  3903. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  3904. }
  3905. };
  3906. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  3907. // node::ParseEncoding() requires lower case.
  3908. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  3909. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  3910. this._writableState.defaultEncoding = encoding;
  3911. return this;
  3912. };
  3913. function decodeChunk(state, chunk, encoding) {
  3914. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  3915. chunk = Buffer.from(chunk, encoding);
  3916. }
  3917. return chunk;
  3918. }
  3919. // if we're already writing something, then just put this
  3920. // in the queue, and wait our turn. Otherwise, call _write
  3921. // If we return false, then we need a drain event, so set that flag.
  3922. function writeOrBuffer(stream, state, chunk, encoding, cb) {
  3923. chunk = decodeChunk(state, chunk, encoding);
  3924. if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  3925. var len = state.objectMode ? 1 : chunk.length;
  3926. state.length += len;
  3927. var ret = state.length < state.highWaterMark;
  3928. // we must ensure that previous needDrain will not be reset to false.
  3929. if (!ret) state.needDrain = true;
  3930. if (state.writing || state.corked) {
  3931. var last = state.lastBufferedRequest;
  3932. state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
  3933. if (last) {
  3934. last.next = state.lastBufferedRequest;
  3935. } else {
  3936. state.bufferedRequest = state.lastBufferedRequest;
  3937. }
  3938. state.bufferedRequestCount += 1;
  3939. } else {
  3940. doWrite(stream, state, false, len, chunk, encoding, cb);
  3941. }
  3942. return ret;
  3943. }
  3944. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  3945. state.writelen = len;
  3946. state.writecb = cb;
  3947. state.writing = true;
  3948. state.sync = true;
  3949. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  3950. state.sync = false;
  3951. }
  3952. function onwriteError(stream, state, sync, er, cb) {
  3953. --state.pendingcb;
  3954. if (sync) nextTick(cb, er);else cb(er);
  3955. stream._writableState.errorEmitted = true;
  3956. stream.emit('error', er);
  3957. }
  3958. function onwriteStateUpdate(state) {
  3959. state.writing = false;
  3960. state.writecb = null;
  3961. state.length -= state.writelen;
  3962. state.writelen = 0;
  3963. }
  3964. function onwrite(stream, er) {
  3965. var state = stream._writableState;
  3966. var sync = state.sync;
  3967. var cb = state.writecb;
  3968. onwriteStateUpdate(state);
  3969. if (er) onwriteError(stream, state, sync, er, cb);else {
  3970. // Check if we're actually ready to finish, but don't emit yet
  3971. var finished = needFinish(state);
  3972. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  3973. clearBuffer(stream, state);
  3974. }
  3975. if (sync) {
  3976. /*<replacement>*/
  3977. nextTick(afterWrite, stream, state, finished, cb);
  3978. /*</replacement>*/
  3979. } else {
  3980. afterWrite(stream, state, finished, cb);
  3981. }
  3982. }
  3983. }
  3984. function afterWrite(stream, state, finished, cb) {
  3985. if (!finished) onwriteDrain(stream, state);
  3986. state.pendingcb--;
  3987. cb();
  3988. finishMaybe(stream, state);
  3989. }
  3990. // Must force callback to be called on nextTick, so that we don't
  3991. // emit 'drain' before the write() consumer gets the 'false' return
  3992. // value, and has a chance to attach a 'drain' listener.
  3993. function onwriteDrain(stream, state) {
  3994. if (state.length === 0 && state.needDrain) {
  3995. state.needDrain = false;
  3996. stream.emit('drain');
  3997. }
  3998. }
  3999. // if there's something in the buffer waiting, then process it
  4000. function clearBuffer(stream, state) {
  4001. state.bufferProcessing = true;
  4002. var entry = state.bufferedRequest;
  4003. if (stream._writev && entry && entry.next) {
  4004. // Fast case, write everything using _writev()
  4005. var l = state.bufferedRequestCount;
  4006. var buffer = new Array(l);
  4007. var holder = state.corkedRequestsFree;
  4008. holder.entry = entry;
  4009. var count = 0;
  4010. while (entry) {
  4011. buffer[count] = entry;
  4012. entry = entry.next;
  4013. count += 1;
  4014. }
  4015. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  4016. // doWrite is almost always async, defer these to save a bit of time
  4017. // as the hot path ends with doWrite
  4018. state.pendingcb++;
  4019. state.lastBufferedRequest = null;
  4020. if (holder.next) {
  4021. state.corkedRequestsFree = holder.next;
  4022. holder.next = null;
  4023. } else {
  4024. state.corkedRequestsFree = new CorkedRequest(state);
  4025. }
  4026. } else {
  4027. // Slow case, write chunks one-by-one
  4028. while (entry) {
  4029. var chunk = entry.chunk;
  4030. var encoding = entry.encoding;
  4031. var cb = entry.callback;
  4032. var len = state.objectMode ? 1 : chunk.length;
  4033. doWrite(stream, state, false, len, chunk, encoding, cb);
  4034. entry = entry.next;
  4035. // if we didn't call the onwrite immediately, then
  4036. // it means that we need to wait until it does.
  4037. // also, that means that the chunk and cb are currently
  4038. // being processed, so move the buffer counter past them.
  4039. if (state.writing) {
  4040. break;
  4041. }
  4042. }
  4043. if (entry === null) state.lastBufferedRequest = null;
  4044. }
  4045. state.bufferedRequestCount = 0;
  4046. state.bufferedRequest = entry;
  4047. state.bufferProcessing = false;
  4048. }
  4049. Writable.prototype._write = function (chunk, encoding, cb) {
  4050. cb(new Error('not implemented'));
  4051. };
  4052. Writable.prototype._writev = null;
  4053. Writable.prototype.end = function (chunk, encoding, cb) {
  4054. var state = this._writableState;
  4055. if (typeof chunk === 'function') {
  4056. cb = chunk;
  4057. chunk = null;
  4058. encoding = null;
  4059. } else if (typeof encoding === 'function') {
  4060. cb = encoding;
  4061. encoding = null;
  4062. }
  4063. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  4064. // .end() fully uncorks
  4065. if (state.corked) {
  4066. state.corked = 1;
  4067. this.uncork();
  4068. }
  4069. // ignore unnecessary end() calls.
  4070. if (!state.ending && !state.finished) endWritable(this, state, cb);
  4071. };
  4072. function needFinish(state) {
  4073. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  4074. }
  4075. function prefinish(stream, state) {
  4076. if (!state.prefinished) {
  4077. state.prefinished = true;
  4078. stream.emit('prefinish');
  4079. }
  4080. }
  4081. function finishMaybe(stream, state) {
  4082. var need = needFinish(state);
  4083. if (need) {
  4084. if (state.pendingcb === 0) {
  4085. prefinish(stream, state);
  4086. state.finished = true;
  4087. stream.emit('finish');
  4088. } else {
  4089. prefinish(stream, state);
  4090. }
  4091. }
  4092. return need;
  4093. }
  4094. function endWritable(stream, state, cb) {
  4095. state.ending = true;
  4096. finishMaybe(stream, state);
  4097. if (cb) {
  4098. if (state.finished) nextTick(cb);else stream.once('finish', cb);
  4099. }
  4100. state.ended = true;
  4101. stream.writable = false;
  4102. }
  4103. // It seems a linked list but it is not
  4104. // there will be only 2 of these for each stream
  4105. function CorkedRequest(state) {
  4106. var _this = this;
  4107. this.next = null;
  4108. this.entry = null;
  4109. this.finish = function (err) {
  4110. var entry = _this.entry;
  4111. _this.entry = null;
  4112. while (entry) {
  4113. var cb = entry.callback;
  4114. state.pendingcb--;
  4115. cb(err);
  4116. entry = entry.next;
  4117. }
  4118. if (state.corkedRequestsFree) {
  4119. state.corkedRequestsFree.next = _this;
  4120. } else {
  4121. state.corkedRequestsFree = _this;
  4122. }
  4123. };
  4124. }
  4125. inherits$1(Duplex, Readable);
  4126. var keys = Object.keys(Writable.prototype);
  4127. for (var v = 0; v < keys.length; v++) {
  4128. var method = keys[v];
  4129. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  4130. }
  4131. function Duplex(options) {
  4132. if (!(this instanceof Duplex)) return new Duplex(options);
  4133. Readable.call(this, options);
  4134. Writable.call(this, options);
  4135. if (options && options.readable === false) this.readable = false;
  4136. if (options && options.writable === false) this.writable = false;
  4137. this.allowHalfOpen = true;
  4138. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  4139. this.once('end', onend);
  4140. }
  4141. // the no-half-open enforcer
  4142. function onend() {
  4143. // if we allow half-open state, or if the writable side ended,
  4144. // then we're ok.
  4145. if (this.allowHalfOpen || this._writableState.ended) return;
  4146. // no more data can be written.
  4147. // But allow more writes to happen in this tick.
  4148. nextTick(onEndNT, this);
  4149. }
  4150. function onEndNT(self) {
  4151. self.end();
  4152. }
  4153. // a transform stream is a readable/writable stream where you do
  4154. // something with the data. Sometimes it's called a "filter",
  4155. // but that's not a great name for it, since that implies a thing where
  4156. // some bits pass through, and others are simply ignored. (That would
  4157. // be a valid example of a transform, of course.)
  4158. //
  4159. // While the output is causally related to the input, it's not a
  4160. // necessarily symmetric or synchronous transformation. For example,
  4161. // a zlib stream might take multiple plain-text writes(), and then
  4162. // emit a single compressed chunk some time in the future.
  4163. //
  4164. // Here's how this works:
  4165. //
  4166. // The Transform stream has all the aspects of the readable and writable
  4167. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  4168. // internally, and returns false if there's a lot of pending writes
  4169. // buffered up. When you call read(), that calls _read(n) until
  4170. // there's enough pending readable data buffered up.
  4171. //
  4172. // In a transform stream, the written data is placed in a buffer. When
  4173. // _read(n) is called, it transforms the queued up data, calling the
  4174. // buffered _write cb's as it consumes chunks. If consuming a single
  4175. // written chunk would result in multiple output chunks, then the first
  4176. // outputted bit calls the readcb, and subsequent chunks just go into
  4177. // the read buffer, and will cause it to emit 'readable' if necessary.
  4178. //
  4179. // This way, back-pressure is actually determined by the reading side,
  4180. // since _read has to be called to start processing a new chunk. However,
  4181. // a pathological inflate type of transform can cause excessive buffering
  4182. // here. For example, imagine a stream where every byte of input is
  4183. // interpreted as an integer from 0-255, and then results in that many
  4184. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  4185. // 1kb of data being output. In this case, you could write a very small
  4186. // amount of input, and end up with a very large amount of output. In
  4187. // such a pathological inflating mechanism, there'd be no way to tell
  4188. // the system to stop doing the transform. A single 4MB write could
  4189. // cause the system to run out of memory.
  4190. //
  4191. // However, even in such a pathological case, only a single written chunk
  4192. // would be consumed, and then the rest would wait (un-transformed) until
  4193. // the results of the previous transformed chunk were consumed.
  4194. inherits$1(Transform, Duplex);
  4195. function TransformState(stream) {
  4196. this.afterTransform = function (er, data) {
  4197. return afterTransform(stream, er, data);
  4198. };
  4199. this.needTransform = false;
  4200. this.transforming = false;
  4201. this.writecb = null;
  4202. this.writechunk = null;
  4203. this.writeencoding = null;
  4204. }
  4205. function afterTransform(stream, er, data) {
  4206. var ts = stream._transformState;
  4207. ts.transforming = false;
  4208. var cb = ts.writecb;
  4209. if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  4210. ts.writechunk = null;
  4211. ts.writecb = null;
  4212. if (data !== null && data !== undefined) stream.push(data);
  4213. cb(er);
  4214. var rs = stream._readableState;
  4215. rs.reading = false;
  4216. if (rs.needReadable || rs.length < rs.highWaterMark) {
  4217. stream._read(rs.highWaterMark);
  4218. }
  4219. }
  4220. function Transform(options) {
  4221. if (!(this instanceof Transform)) return new Transform(options);
  4222. Duplex.call(this, options);
  4223. this._transformState = new TransformState(this);
  4224. // when the writable side finishes, then flush out anything remaining.
  4225. var stream = this;
  4226. // start out asking for a readable event once data is transformed.
  4227. this._readableState.needReadable = true;
  4228. // we have implemented the _read method, and done the other things
  4229. // that Readable wants before the first _read call, so unset the
  4230. // sync guard flag.
  4231. this._readableState.sync = false;
  4232. if (options) {
  4233. if (typeof options.transform === 'function') this._transform = options.transform;
  4234. if (typeof options.flush === 'function') this._flush = options.flush;
  4235. }
  4236. this.once('prefinish', function () {
  4237. if (typeof this._flush === 'function') this._flush(function (er) {
  4238. done(stream, er);
  4239. });else done(stream);
  4240. });
  4241. }
  4242. Transform.prototype.push = function (chunk, encoding) {
  4243. this._transformState.needTransform = false;
  4244. return Duplex.prototype.push.call(this, chunk, encoding);
  4245. };
  4246. // This is the part where you do stuff!
  4247. // override this function in implementation classes.
  4248. // 'chunk' is an input chunk.
  4249. //
  4250. // Call `push(newChunk)` to pass along transformed output
  4251. // to the readable side. You may call 'push' zero or more times.
  4252. //
  4253. // Call `cb(err)` when you are done with this chunk. If you pass
  4254. // an error, then that'll put the hurt on the whole operation. If you
  4255. // never call cb(), then you'll never get another chunk.
  4256. Transform.prototype._transform = function (chunk, encoding, cb) {
  4257. throw new Error('Not implemented');
  4258. };
  4259. Transform.prototype._write = function (chunk, encoding, cb) {
  4260. var ts = this._transformState;
  4261. ts.writecb = cb;
  4262. ts.writechunk = chunk;
  4263. ts.writeencoding = encoding;
  4264. if (!ts.transforming) {
  4265. var rs = this._readableState;
  4266. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  4267. }
  4268. };
  4269. // Doesn't matter what the args are here.
  4270. // _transform does all the work.
  4271. // That we got here means that the readable side wants more data.
  4272. Transform.prototype._read = function (n) {
  4273. var ts = this._transformState;
  4274. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  4275. ts.transforming = true;
  4276. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  4277. } else {
  4278. // mark that we need a transform, so that any data that comes in
  4279. // will get processed, now that we've asked for it.
  4280. ts.needTransform = true;
  4281. }
  4282. };
  4283. function done(stream, er) {
  4284. if (er) return stream.emit('error', er);
  4285. // if there's nothing in the write buffer, then that means
  4286. // that nothing more will ever be provided
  4287. var ws = stream._writableState;
  4288. var ts = stream._transformState;
  4289. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  4290. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  4291. return stream.push(null);
  4292. }
  4293. inherits$1(PassThrough, Transform);
  4294. function PassThrough(options) {
  4295. if (!(this instanceof PassThrough)) return new PassThrough(options);
  4296. Transform.call(this, options);
  4297. }
  4298. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  4299. cb(null, chunk);
  4300. };
  4301. inherits$1(Stream, EventEmitter);
  4302. Stream.Readable = Readable;
  4303. Stream.Writable = Writable;
  4304. Stream.Duplex = Duplex;
  4305. Stream.Transform = Transform;
  4306. Stream.PassThrough = PassThrough;
  4307. // Backwards-compat with node 0.4.x
  4308. Stream.Stream = Stream;
  4309. // old-style streams. Note that the pipe method (the only relevant
  4310. // part of this class) is overridden in the Readable class.
  4311. function Stream() {
  4312. EventEmitter.call(this);
  4313. }
  4314. Stream.prototype.pipe = function(dest, options) {
  4315. var source = this;
  4316. function ondata(chunk) {
  4317. if (dest.writable) {
  4318. if (false === dest.write(chunk) && source.pause) {
  4319. source.pause();
  4320. }
  4321. }
  4322. }
  4323. source.on('data', ondata);
  4324. function ondrain() {
  4325. if (source.readable && source.resume) {
  4326. source.resume();
  4327. }
  4328. }
  4329. dest.on('drain', ondrain);
  4330. // If the 'end' option is not supplied, dest.end() will be called when
  4331. // source gets the 'end' or 'close' events. Only dest.end() once.
  4332. if (!dest._isStdio && (!options || options.end !== false)) {
  4333. source.on('end', onend);
  4334. source.on('close', onclose);
  4335. }
  4336. var didOnEnd = false;
  4337. function onend() {
  4338. if (didOnEnd) return;
  4339. didOnEnd = true;
  4340. dest.end();
  4341. }
  4342. function onclose() {
  4343. if (didOnEnd) return;
  4344. didOnEnd = true;
  4345. if (typeof dest.destroy === 'function') dest.destroy();
  4346. }
  4347. // don't leave dangling pipes when there are errors.
  4348. function onerror(er) {
  4349. cleanup();
  4350. if (EventEmitter.listenerCount(this, 'error') === 0) {
  4351. throw er; // Unhandled stream error in pipe.
  4352. }
  4353. }
  4354. source.on('error', onerror);
  4355. dest.on('error', onerror);
  4356. // remove all the event listeners that were added.
  4357. function cleanup() {
  4358. source.removeListener('data', ondata);
  4359. dest.removeListener('drain', ondrain);
  4360. source.removeListener('end', onend);
  4361. source.removeListener('close', onclose);
  4362. source.removeListener('error', onerror);
  4363. dest.removeListener('error', onerror);
  4364. source.removeListener('end', cleanup);
  4365. source.removeListener('close', cleanup);
  4366. dest.removeListener('close', cleanup);
  4367. }
  4368. source.on('end', cleanup);
  4369. source.on('close', cleanup);
  4370. dest.on('close', cleanup);
  4371. dest.emit('pipe', source);
  4372. // Allow for unix-like usage: A.pipe(B).pipe(C)
  4373. return dest;
  4374. };
  4375. const is_object = function(obj){
  4376. return (typeof obj === 'object' && obj !== null && !Array.isArray(obj));
  4377. };
  4378. class CsvError extends Error {
  4379. constructor(code, message, options, ...contexts) {
  4380. if(Array.isArray(message)) message = message.join(' ').trim();
  4381. super(message);
  4382. if(Error.captureStackTrace !== undefined){
  4383. Error.captureStackTrace(this, CsvError);
  4384. }
  4385. this.code = code;
  4386. for(const context of contexts){
  4387. for(const key in context){
  4388. const value = context[key];
  4389. this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
  4390. }
  4391. }
  4392. }
  4393. }
  4394. const normalize_columns_array = function(columns){
  4395. const normalizedColumns = [];
  4396. for(let i = 0, l = columns.length; i < l; i++){
  4397. const column = columns[i];
  4398. if(column === undefined || column === null || column === false){
  4399. normalizedColumns[i] = { disabled: true };
  4400. }else if(typeof column === 'string'){
  4401. normalizedColumns[i] = { name: column };
  4402. }else if(is_object(column)){
  4403. if(typeof column.name !== 'string'){
  4404. throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [
  4405. 'Option columns missing name:',
  4406. `property "name" is required at position ${i}`,
  4407. 'when column is an object literal'
  4408. ]);
  4409. }
  4410. normalizedColumns[i] = column;
  4411. }else {
  4412. throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [
  4413. 'Invalid column definition:',
  4414. 'expect a string or a literal object,',
  4415. `got ${JSON.stringify(column)} at position ${i}`
  4416. ]);
  4417. }
  4418. }
  4419. return normalizedColumns;
  4420. };
  4421. class ResizeableBuffer{
  4422. constructor(size=100){
  4423. this.size = size;
  4424. this.length = 0;
  4425. this.buf = Buffer.allocUnsafe(size);
  4426. }
  4427. prepend(val){
  4428. if(isBuffer(val)){
  4429. const length = this.length + val.length;
  4430. if(length >= this.size){
  4431. this.resize();
  4432. if(length >= this.size){
  4433. throw Error('INVALID_BUFFER_STATE');
  4434. }
  4435. }
  4436. const buf = this.buf;
  4437. this.buf = Buffer.allocUnsafe(this.size);
  4438. val.copy(this.buf, 0);
  4439. buf.copy(this.buf, val.length);
  4440. this.length += val.length;
  4441. }else {
  4442. const length = this.length++;
  4443. if(length === this.size){
  4444. this.resize();
  4445. }
  4446. const buf = this.clone();
  4447. this.buf[0] = val;
  4448. buf.copy(this.buf,1, 0, length);
  4449. }
  4450. }
  4451. append(val){
  4452. const length = this.length++;
  4453. if(length === this.size){
  4454. this.resize();
  4455. }
  4456. this.buf[length] = val;
  4457. }
  4458. clone(){
  4459. return Buffer.from(this.buf.slice(0, this.length));
  4460. }
  4461. resize(){
  4462. const length = this.length;
  4463. this.size = this.size * 2;
  4464. const buf = Buffer.allocUnsafe(this.size);
  4465. this.buf.copy(buf,0, 0, length);
  4466. this.buf = buf;
  4467. }
  4468. toString(encoding){
  4469. if(encoding){
  4470. return this.buf.slice(0, this.length).toString(encoding);
  4471. }else {
  4472. return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
  4473. }
  4474. }
  4475. toJSON(){
  4476. return this.toString('utf8');
  4477. }
  4478. reset(){
  4479. this.length = 0;
  4480. }
  4481. }
  4482. // white space characters
  4483. // https://en.wikipedia.org/wiki/Whitespace_character
  4484. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types
  4485. // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff
  4486. const np = 12;
  4487. const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
  4488. const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
  4489. const space = 32;
  4490. const tab = 9;
  4491. const init_state = function(options){
  4492. return {
  4493. bomSkipped: false,
  4494. bufBytesStart: 0,
  4495. castField: options.cast_function,
  4496. commenting: false,
  4497. // Current error encountered by a record
  4498. error: undefined,
  4499. enabled: options.from_line === 1,
  4500. escaping: false,
  4501. escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
  4502. // columns can be `false`, `true`, `Array`
  4503. expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
  4504. field: new ResizeableBuffer(20),
  4505. firstLineToHeaders: options.cast_first_line_to_header,
  4506. needMoreDataSize: Math.max(
  4507. // Skip if the remaining buffer smaller than comment
  4508. options.comment !== null ? options.comment.length : 0,
  4509. // Skip if the remaining buffer can be delimiter
  4510. ...options.delimiter.map((delimiter) => delimiter.length),
  4511. // Skip if the remaining buffer can be escape sequence
  4512. options.quote !== null ? options.quote.length : 0,
  4513. ),
  4514. previousBuf: undefined,
  4515. quoting: false,
  4516. stop: false,
  4517. rawBuffer: new ResizeableBuffer(100),
  4518. record: [],
  4519. recordHasError: false,
  4520. record_length: 0,
  4521. recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
  4522. trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]],
  4523. wasQuoting: false,
  4524. wasRowDelimiter: false,
  4525. timchars: [
  4526. Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding),
  4527. Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding),
  4528. Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding),
  4529. Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding),
  4530. Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding),
  4531. ]
  4532. };
  4533. };
  4534. const underscore = function(str){
  4535. return str.replace(/([A-Z])/g, function(_, match){
  4536. return '_' + match.toLowerCase();
  4537. });
  4538. };
  4539. const normalize_options = function(opts){
  4540. const options = {};
  4541. // Merge with user options
  4542. for(const opt in opts){
  4543. options[underscore(opt)] = opts[opt];
  4544. }
  4545. // Normalize option `encoding`
  4546. // Note: defined first because other options depends on it
  4547. // to convert chars/strings into buffers.
  4548. if(options.encoding === undefined || options.encoding === true){
  4549. options.encoding = 'utf8';
  4550. }else if(options.encoding === null || options.encoding === false){
  4551. options.encoding = null;
  4552. }else if(typeof options.encoding !== 'string' && options.encoding !== null){
  4553. throw new CsvError('CSV_INVALID_OPTION_ENCODING', [
  4554. 'Invalid option encoding:',
  4555. 'encoding must be a string or null to return a buffer,',
  4556. `got ${JSON.stringify(options.encoding)}`
  4557. ], options);
  4558. }
  4559. // Normalize option `bom`
  4560. if(options.bom === undefined || options.bom === null || options.bom === false){
  4561. options.bom = false;
  4562. }else if(options.bom !== true){
  4563. throw new CsvError('CSV_INVALID_OPTION_BOM', [
  4564. 'Invalid option bom:', 'bom must be true,',
  4565. `got ${JSON.stringify(options.bom)}`
  4566. ], options);
  4567. }
  4568. // Normalize option `cast`
  4569. options.cast_function = null;
  4570. if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){
  4571. options.cast = undefined;
  4572. }else if(typeof options.cast === 'function'){
  4573. options.cast_function = options.cast;
  4574. options.cast = true;
  4575. }else if(options.cast !== true){
  4576. throw new CsvError('CSV_INVALID_OPTION_CAST', [
  4577. 'Invalid option cast:', 'cast must be true or a function,',
  4578. `got ${JSON.stringify(options.cast)}`
  4579. ], options);
  4580. }
  4581. // Normalize option `cast_date`
  4582. if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){
  4583. options.cast_date = false;
  4584. }else if(options.cast_date === true){
  4585. options.cast_date = function(value){
  4586. const date = Date.parse(value);
  4587. return !isNaN(date) ? new Date(date) : value;
  4588. };
  4589. }else if (typeof options.cast_date !== 'function'){
  4590. throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [
  4591. 'Invalid option cast_date:', 'cast_date must be true or a function,',
  4592. `got ${JSON.stringify(options.cast_date)}`
  4593. ], options);
  4594. }
  4595. // Normalize option `columns`
  4596. options.cast_first_line_to_header = null;
  4597. if(options.columns === true){
  4598. // Fields in the first line are converted as-is to columns
  4599. options.cast_first_line_to_header = undefined;
  4600. }else if(typeof options.columns === 'function'){
  4601. options.cast_first_line_to_header = options.columns;
  4602. options.columns = true;
  4603. }else if(Array.isArray(options.columns)){
  4604. options.columns = normalize_columns_array(options.columns);
  4605. }else if(options.columns === undefined || options.columns === null || options.columns === false){
  4606. options.columns = false;
  4607. }else {
  4608. throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [
  4609. 'Invalid option columns:',
  4610. 'expect an array, a function or true,',
  4611. `got ${JSON.stringify(options.columns)}`
  4612. ], options);
  4613. }
  4614. // Normalize option `group_columns_by_name`
  4615. if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){
  4616. options.group_columns_by_name = false;
  4617. }else if(options.group_columns_by_name !== true){
  4618. throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
  4619. 'Invalid option group_columns_by_name:',
  4620. 'expect an boolean,',
  4621. `got ${JSON.stringify(options.group_columns_by_name)}`
  4622. ], options);
  4623. }else if(options.columns === false){
  4624. throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
  4625. 'Invalid option group_columns_by_name:',
  4626. 'the `columns` mode must be activated.'
  4627. ], options);
  4628. }
  4629. // Normalize option `comment`
  4630. if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){
  4631. options.comment = null;
  4632. }else {
  4633. if(typeof options.comment === 'string'){
  4634. options.comment = Buffer.from(options.comment, options.encoding);
  4635. }
  4636. if(!isBuffer(options.comment)){
  4637. throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
  4638. 'Invalid option comment:',
  4639. 'comment must be a buffer or a string,',
  4640. `got ${JSON.stringify(options.comment)}`
  4641. ], options);
  4642. }
  4643. }
  4644. // Normalize option `comment_no_infix`
  4645. if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){
  4646. options.comment_no_infix = false;
  4647. }else if(options.comment_no_infix !== true){
  4648. throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
  4649. 'Invalid option comment_no_infix:',
  4650. 'value must be a boolean,',
  4651. `got ${JSON.stringify(options.comment_no_infix)}`
  4652. ], options);
  4653. }
  4654. // Normalize option `delimiter`
  4655. const delimiter_json = JSON.stringify(options.delimiter);
  4656. if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
  4657. if(options.delimiter.length === 0){
  4658. throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
  4659. 'Invalid option delimiter:',
  4660. 'delimiter must be a non empty string or buffer or array of string|buffer,',
  4661. `got ${delimiter_json}`
  4662. ], options);
  4663. }
  4664. options.delimiter = options.delimiter.map(function(delimiter){
  4665. if(delimiter === undefined || delimiter === null || delimiter === false){
  4666. return Buffer.from(',', options.encoding);
  4667. }
  4668. if(typeof delimiter === 'string'){
  4669. delimiter = Buffer.from(delimiter, options.encoding);
  4670. }
  4671. if(!isBuffer(delimiter) || delimiter.length === 0){
  4672. throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
  4673. 'Invalid option delimiter:',
  4674. 'delimiter must be a non empty string or buffer or array of string|buffer,',
  4675. `got ${delimiter_json}`
  4676. ], options);
  4677. }
  4678. return delimiter;
  4679. });
  4680. // Normalize option `escape`
  4681. if(options.escape === undefined || options.escape === true){
  4682. options.escape = Buffer.from('"', options.encoding);
  4683. }else if(typeof options.escape === 'string'){
  4684. options.escape = Buffer.from(options.escape, options.encoding);
  4685. }else if (options.escape === null || options.escape === false){
  4686. options.escape = null;
  4687. }
  4688. if(options.escape !== null){
  4689. if(!isBuffer(options.escape)){
  4690. throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
  4691. }
  4692. }
  4693. // Normalize option `from`
  4694. if(options.from === undefined || options.from === null){
  4695. options.from = 1;
  4696. }else {
  4697. if(typeof options.from === 'string' && /\d+/.test(options.from)){
  4698. options.from = parseInt(options.from);
  4699. }
  4700. if(Number.isInteger(options.from)){
  4701. if(options.from < 0){
  4702. throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
  4703. }
  4704. }else {
  4705. throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
  4706. }
  4707. }
  4708. // Normalize option `from_line`
  4709. if(options.from_line === undefined || options.from_line === null){
  4710. options.from_line = 1;
  4711. }else {
  4712. if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){
  4713. options.from_line = parseInt(options.from_line);
  4714. }
  4715. if(Number.isInteger(options.from_line)){
  4716. if(options.from_line <= 0){
  4717. throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
  4718. }
  4719. }else {
  4720. throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
  4721. }
  4722. }
  4723. // Normalize options `ignore_last_delimiters`
  4724. if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){
  4725. options.ignore_last_delimiters = false;
  4726. }else if(typeof options.ignore_last_delimiters === 'number'){
  4727. options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
  4728. if(options.ignore_last_delimiters === 0){
  4729. options.ignore_last_delimiters = false;
  4730. }
  4731. }else if(typeof options.ignore_last_delimiters !== 'boolean'){
  4732. throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [
  4733. 'Invalid option `ignore_last_delimiters`:',
  4734. 'the value must be a boolean value or an integer,',
  4735. `got ${JSON.stringify(options.ignore_last_delimiters)}`
  4736. ], options);
  4737. }
  4738. if(options.ignore_last_delimiters === true && options.columns === false){
  4739. throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [
  4740. 'The option `ignore_last_delimiters`',
  4741. 'requires the activation of the `columns` option'
  4742. ], options);
  4743. }
  4744. // Normalize option `info`
  4745. if(options.info === undefined || options.info === null || options.info === false){
  4746. options.info = false;
  4747. }else if(options.info !== true){
  4748. throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
  4749. }
  4750. // Normalize option `max_record_size`
  4751. if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){
  4752. options.max_record_size = 0;
  4753. }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){
  4754. options.max_record_size = parseInt(options.max_record_size);
  4755. }else {
  4756. throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
  4757. }
  4758. // Normalize option `objname`
  4759. if(options.objname === undefined || options.objname === null || options.objname === false){
  4760. options.objname = undefined;
  4761. }else if(isBuffer(options.objname)){
  4762. if(options.objname.length === 0){
  4763. throw new Error(`Invalid Option: objname must be a non empty buffer`);
  4764. }
  4765. if(options.encoding === null);else {
  4766. options.objname = options.objname.toString(options.encoding);
  4767. }
  4768. }else if(typeof options.objname === 'string'){
  4769. if(options.objname.length === 0){
  4770. throw new Error(`Invalid Option: objname must be a non empty string`);
  4771. }
  4772. // Great, nothing to do
  4773. }else if(typeof options.objname === 'number');else {
  4774. throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
  4775. }
  4776. if(options.objname !== undefined){
  4777. if(typeof options.objname === 'number'){
  4778. if(options.columns !== false){
  4779. throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field');
  4780. }
  4781. }else { // A string or a buffer
  4782. if(options.columns === false){
  4783. throw Error('Invalid Option: objname field must be combined with columns or be defined as an index');
  4784. }
  4785. }
  4786. }
  4787. // Normalize option `on_record`
  4788. if(options.on_record === undefined || options.on_record === null){
  4789. options.on_record = undefined;
  4790. }else if(typeof options.on_record !== 'function'){
  4791. throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [
  4792. 'Invalid option `on_record`:',
  4793. 'expect a function,',
  4794. `got ${JSON.stringify(options.on_record)}`
  4795. ], options);
  4796. }
  4797. // Normalize option `quote`
  4798. if(options.quote === null || options.quote === false || options.quote === ''){
  4799. options.quote = null;
  4800. }else {
  4801. if(options.quote === undefined || options.quote === true){
  4802. options.quote = Buffer.from('"', options.encoding);
  4803. }else if(typeof options.quote === 'string'){
  4804. options.quote = Buffer.from(options.quote, options.encoding);
  4805. }
  4806. if(!isBuffer(options.quote)){
  4807. throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
  4808. }
  4809. }
  4810. // Normalize option `raw`
  4811. if(options.raw === undefined || options.raw === null || options.raw === false){
  4812. options.raw = false;
  4813. }else if(options.raw !== true){
  4814. throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
  4815. }
  4816. // Normalize option `record_delimiter`
  4817. if(options.record_delimiter === undefined){
  4818. options.record_delimiter = [];
  4819. }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){
  4820. if(options.record_delimiter.length === 0){
  4821. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4822. 'Invalid option `record_delimiter`:',
  4823. 'value must be a non empty string or buffer,',
  4824. `got ${JSON.stringify(options.record_delimiter)}`
  4825. ], options);
  4826. }
  4827. options.record_delimiter = [options.record_delimiter];
  4828. }else if(!Array.isArray(options.record_delimiter)){
  4829. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4830. 'Invalid option `record_delimiter`:',
  4831. 'value must be a string, a buffer or array of string|buffer,',
  4832. `got ${JSON.stringify(options.record_delimiter)}`
  4833. ], options);
  4834. }
  4835. options.record_delimiter = options.record_delimiter.map(function(rd, i){
  4836. if(typeof rd !== 'string' && ! isBuffer(rd)){
  4837. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4838. 'Invalid option `record_delimiter`:',
  4839. 'value must be a string, a buffer or array of string|buffer',
  4840. `at index ${i},`,
  4841. `got ${JSON.stringify(rd)}`
  4842. ], options);
  4843. }else if(rd.length === 0){
  4844. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4845. 'Invalid option `record_delimiter`:',
  4846. 'value must be a non empty string or buffer',
  4847. `at index ${i},`,
  4848. `got ${JSON.stringify(rd)}`
  4849. ], options);
  4850. }
  4851. if(typeof rd === 'string'){
  4852. rd = Buffer.from(rd, options.encoding);
  4853. }
  4854. return rd;
  4855. });
  4856. // Normalize option `relax_column_count`
  4857. if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){
  4858. options.relax_column_count = false;
  4859. }else {
  4860. throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
  4861. }
  4862. if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){
  4863. options.relax_column_count_less = false;
  4864. }else {
  4865. throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
  4866. }
  4867. if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){
  4868. options.relax_column_count_more = false;
  4869. }else {
  4870. throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
  4871. }
  4872. // Normalize option `relax_quotes`
  4873. if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){
  4874. options.relax_quotes = false;
  4875. }else {
  4876. throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
  4877. }
  4878. // Normalize option `skip_empty_lines`
  4879. if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){
  4880. options.skip_empty_lines = false;
  4881. }else {
  4882. throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
  4883. }
  4884. // Normalize option `skip_records_with_empty_values`
  4885. if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){
  4886. options.skip_records_with_empty_values = false;
  4887. }else {
  4888. throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
  4889. }
  4890. // Normalize option `skip_records_with_error`
  4891. if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){
  4892. options.skip_records_with_error = false;
  4893. }else {
  4894. throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
  4895. }
  4896. // Normalize option `rtrim`
  4897. if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){
  4898. options.rtrim = false;
  4899. }else if(options.rtrim !== true){
  4900. throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
  4901. }
  4902. // Normalize option `ltrim`
  4903. if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){
  4904. options.ltrim = false;
  4905. }else if(options.ltrim !== true){
  4906. throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
  4907. }
  4908. // Normalize option `trim`
  4909. if(options.trim === undefined || options.trim === null || options.trim === false){
  4910. options.trim = false;
  4911. }else if(options.trim !== true){
  4912. throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
  4913. }
  4914. // Normalize options `trim`, `ltrim` and `rtrim`
  4915. if(options.trim === true && opts.ltrim !== false){
  4916. options.ltrim = true;
  4917. }else if(options.ltrim !== true){
  4918. options.ltrim = false;
  4919. }
  4920. if(options.trim === true && opts.rtrim !== false){
  4921. options.rtrim = true;
  4922. }else if(options.rtrim !== true){
  4923. options.rtrim = false;
  4924. }
  4925. // Normalize option `to`
  4926. if(options.to === undefined || options.to === null){
  4927. options.to = -1;
  4928. }else {
  4929. if(typeof options.to === 'string' && /\d+/.test(options.to)){
  4930. options.to = parseInt(options.to);
  4931. }
  4932. if(Number.isInteger(options.to)){
  4933. if(options.to <= 0){
  4934. throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
  4935. }
  4936. }else {
  4937. throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
  4938. }
  4939. }
  4940. // Normalize option `to_line`
  4941. if(options.to_line === undefined || options.to_line === null){
  4942. options.to_line = -1;
  4943. }else {
  4944. if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){
  4945. options.to_line = parseInt(options.to_line);
  4946. }
  4947. if(Number.isInteger(options.to_line)){
  4948. if(options.to_line <= 0){
  4949. throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
  4950. }
  4951. }else {
  4952. throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
  4953. }
  4954. }
  4955. return options;
  4956. };
  4957. const isRecordEmpty = function(record){
  4958. return record.every((field) => field == null || field.toString && field.toString().trim() === '');
  4959. };
  4960. const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
  4961. const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
  4962. const boms = {
  4963. // Note, the following are equals:
  4964. // Buffer.from("\ufeff")
  4965. // Buffer.from([239, 187, 191])
  4966. // Buffer.from('EFBBBF', 'hex')
  4967. 'utf8': Buffer.from([239, 187, 191]),
  4968. // Note, the following are equals:
  4969. // Buffer.from "\ufeff", 'utf16le
  4970. // Buffer.from([255, 254])
  4971. 'utf16le': Buffer.from([255, 254])
  4972. };
  4973. const transform = function(original_options = {}) {
  4974. const info = {
  4975. bytes: 0,
  4976. comment_lines: 0,
  4977. empty_lines: 0,
  4978. invalid_field_length: 0,
  4979. lines: 1,
  4980. records: 0
  4981. };
  4982. const options = normalize_options(original_options);
  4983. return {
  4984. info: info,
  4985. original_options: original_options,
  4986. options: options,
  4987. state: init_state(options),
  4988. __needMoreData: function(i, bufLen, end){
  4989. if(end) return false;
  4990. const {encoding, escape, quote} = this.options;
  4991. const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state;
  4992. const numOfCharLeft = bufLen - i - 1;
  4993. const requiredLength = Math.max(
  4994. needMoreDataSize,
  4995. // Skip if the remaining buffer smaller than record delimiter
  4996. // If "record_delimiter" is yet to be discovered:
  4997. // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
  4998. // 2. We set the length to windows line ending in the current encoding
  4999. // Note, that encoding is known from user or bom discovery at that point
  5000. // recordDelimiterMaxLength,
  5001. recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength,
  5002. // Skip if remaining buffer can be an escaped quote
  5003. quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0,
  5004. // Skip if remaining buffer can be record delimiter following the closing quote
  5005. quoting ? (quote.length + recordDelimiterMaxLength) : 0,
  5006. );
  5007. return numOfCharLeft < requiredLength;
  5008. },
  5009. // Central parser implementation
  5010. parse: function(nextBuf, end, push, close){
  5011. const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options;
  5012. let {comment, escape, quote, record_delimiter} = this.options;
  5013. const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state;
  5014. let buf;
  5015. if(previousBuf === undefined){
  5016. if(nextBuf === undefined){
  5017. // Handle empty string
  5018. close();
  5019. return;
  5020. }else {
  5021. buf = nextBuf;
  5022. }
  5023. }else if(previousBuf !== undefined && nextBuf === undefined){
  5024. buf = previousBuf;
  5025. }else {
  5026. buf = Buffer.concat([previousBuf, nextBuf]);
  5027. }
  5028. // Handle UTF BOM
  5029. if(bomSkipped === false){
  5030. if(bom === false){
  5031. this.state.bomSkipped = true;
  5032. }else if(buf.length < 3){
  5033. // No enough data
  5034. if(end === false){
  5035. // Wait for more data
  5036. this.state.previousBuf = buf;
  5037. return;
  5038. }
  5039. }else {
  5040. for(const encoding in boms){
  5041. if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){
  5042. // Skip BOM
  5043. const bomLength = boms[encoding].length;
  5044. this.state.bufBytesStart += bomLength;
  5045. buf = buf.slice(bomLength);
  5046. // Renormalize original options with the new encoding
  5047. this.options = normalize_options({...this.original_options, encoding: encoding});
  5048. // Options will re-evaluate the Buffer with the new encoding
  5049. ({comment, escape, quote } = this.options);
  5050. break;
  5051. }
  5052. }
  5053. this.state.bomSkipped = true;
  5054. }
  5055. }
  5056. const bufLen = buf.length;
  5057. let pos;
  5058. for(pos = 0; pos < bufLen; pos++){
  5059. // Ensure we get enough space to look ahead
  5060. // There should be a way to move this out of the loop
  5061. if(this.__needMoreData(pos, bufLen, end)){
  5062. break;
  5063. }
  5064. if(this.state.wasRowDelimiter === true){
  5065. this.info.lines++;
  5066. this.state.wasRowDelimiter = false;
  5067. }
  5068. if(to_line !== -1 && this.info.lines > to_line){
  5069. this.state.stop = true;
  5070. close();
  5071. return;
  5072. }
  5073. // Auto discovery of record_delimiter, unix, mac and windows supported
  5074. if(this.state.quoting === false && record_delimiter.length === 0){
  5075. const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
  5076. if(record_delimiterCount){
  5077. record_delimiter = this.options.record_delimiter;
  5078. }
  5079. }
  5080. const chr = buf[pos];
  5081. if(raw === true){
  5082. rawBuffer.append(chr);
  5083. }
  5084. if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){
  5085. this.state.wasRowDelimiter = true;
  5086. }
  5087. // Previous char was a valid escape char
  5088. // treat the current char as a regular char
  5089. if(this.state.escaping === true){
  5090. this.state.escaping = false;
  5091. }else {
  5092. // Escape is only active inside quoted fields
  5093. // We are quoting, the char is an escape chr and there is a chr to escape
  5094. // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){
  5095. if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){
  5096. if(escapeIsQuote){
  5097. if(this.__isQuote(buf, pos+escape.length)){
  5098. this.state.escaping = true;
  5099. pos += escape.length - 1;
  5100. continue;
  5101. }
  5102. }else {
  5103. this.state.escaping = true;
  5104. pos += escape.length - 1;
  5105. continue;
  5106. }
  5107. }
  5108. // Not currently escaping and chr is a quote
  5109. // TODO: need to compare bytes instead of single char
  5110. if(this.state.commenting === false && this.__isQuote(buf, pos)){
  5111. if(this.state.quoting === true){
  5112. const nextChr = buf[pos+quote.length];
  5113. const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length);
  5114. const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr);
  5115. const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr);
  5116. const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length);
  5117. // Escape a quote
  5118. // Treat next char as a regular character
  5119. if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){
  5120. pos += escape.length - 1;
  5121. }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){
  5122. this.state.quoting = false;
  5123. this.state.wasQuoting = true;
  5124. pos += quote.length - 1;
  5125. continue;
  5126. }else if(relax_quotes === false){
  5127. const err = this.__error(
  5128. new CsvError('CSV_INVALID_CLOSING_QUOTE', [
  5129. 'Invalid Closing Quote:',
  5130. `got "${String.fromCharCode(nextChr)}"`,
  5131. `at line ${this.info.lines}`,
  5132. 'instead of delimiter, record delimiter, trimable character',
  5133. '(if activated) or comment',
  5134. ], this.options, this.__infoField())
  5135. );
  5136. if(err !== undefined) return err;
  5137. }else {
  5138. this.state.quoting = false;
  5139. this.state.wasQuoting = true;
  5140. this.state.field.prepend(quote);
  5141. pos += quote.length - 1;
  5142. }
  5143. }else {
  5144. if(this.state.field.length !== 0){
  5145. // In relax_quotes mode, treat opening quote preceded by chrs as regular
  5146. if(relax_quotes === false){
  5147. const info = this.__infoField();
  5148. const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
  5149. const err = this.__error(
  5150. new CsvError('INVALID_OPENING_QUOTE', [
  5151. 'Invalid Opening Quote:',
  5152. `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
  5153. bom ? `(${bom} bom)` : undefined
  5154. ], this.options, info, {
  5155. field: this.state.field,
  5156. })
  5157. );
  5158. if(err !== undefined) return err;
  5159. }
  5160. }else {
  5161. this.state.quoting = true;
  5162. pos += quote.length - 1;
  5163. continue;
  5164. }
  5165. }
  5166. }
  5167. if(this.state.quoting === false){
  5168. const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
  5169. if(recordDelimiterLength !== 0){
  5170. // Do not emit comments which take a full line
  5171. const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0);
  5172. if(skipCommentLine){
  5173. this.info.comment_lines++;
  5174. // Skip full comment line
  5175. }else {
  5176. // Activate records emition if above from_line
  5177. if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){
  5178. this.state.enabled = true;
  5179. this.__resetField();
  5180. this.__resetRecord();
  5181. pos += recordDelimiterLength - 1;
  5182. continue;
  5183. }
  5184. // Skip if line is empty and skip_empty_lines activated
  5185. if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){
  5186. this.info.empty_lines++;
  5187. pos += recordDelimiterLength - 1;
  5188. continue;
  5189. }
  5190. this.info.bytes = this.state.bufBytesStart + pos;
  5191. const errField = this.__onField();
  5192. if(errField !== undefined) return errField;
  5193. this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
  5194. const errRecord = this.__onRecord(push);
  5195. if(errRecord !== undefined) return errRecord;
  5196. if(to !== -1 && this.info.records >= to){
  5197. this.state.stop = true;
  5198. close();
  5199. return;
  5200. }
  5201. }
  5202. this.state.commenting = false;
  5203. pos += recordDelimiterLength - 1;
  5204. continue;
  5205. }
  5206. if(this.state.commenting){
  5207. continue;
  5208. }
  5209. const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr);
  5210. if(commentCount !== 0 && (comment_no_infix === false || this.state.field.length === 0)){
  5211. this.state.commenting = true;
  5212. continue;
  5213. }
  5214. const delimiterLength = this.__isDelimiter(buf, pos, chr);
  5215. if(delimiterLength !== 0){
  5216. this.info.bytes = this.state.bufBytesStart + pos;
  5217. const errField = this.__onField();
  5218. if(errField !== undefined) return errField;
  5219. pos += delimiterLength - 1;
  5220. continue;
  5221. }
  5222. }
  5223. }
  5224. if(this.state.commenting === false){
  5225. if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){
  5226. return this.__error(
  5227. new CsvError('CSV_MAX_RECORD_SIZE', [
  5228. 'Max Record Size:',
  5229. 'record exceed the maximum number of tolerated bytes',
  5230. `of ${max_record_size}`,
  5231. `at line ${this.info.lines}`,
  5232. ], this.options, this.__infoField())
  5233. );
  5234. }
  5235. }
  5236. const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
  5237. // rtrim in non quoting is handle in __onField
  5238. const rappend = rtrim === false || this.state.wasQuoting === false;
  5239. if(lappend === true && rappend === true){
  5240. this.state.field.append(chr);
  5241. }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){
  5242. return this.__error(
  5243. new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [
  5244. 'Invalid Closing Quote:',
  5245. 'found non trimable byte after quote',
  5246. `at line ${this.info.lines}`,
  5247. ], this.options, this.__infoField())
  5248. );
  5249. }else {
  5250. if(lappend === false){
  5251. pos += this.__isCharTrimable(buf, pos) - 1;
  5252. }
  5253. continue;
  5254. }
  5255. }
  5256. if(end === true){
  5257. // Ensure we are not ending in a quoting state
  5258. if(this.state.quoting === true){
  5259. const err = this.__error(
  5260. new CsvError('CSV_QUOTE_NOT_CLOSED', [
  5261. 'Quote Not Closed:',
  5262. `the parsing is finished with an opening quote at line ${this.info.lines}`,
  5263. ], this.options, this.__infoField())
  5264. );
  5265. if(err !== undefined) return err;
  5266. }else {
  5267. // Skip last line if it has no characters
  5268. if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){
  5269. this.info.bytes = this.state.bufBytesStart + pos;
  5270. const errField = this.__onField();
  5271. if(errField !== undefined) return errField;
  5272. const errRecord = this.__onRecord(push);
  5273. if(errRecord !== undefined) return errRecord;
  5274. }else if(this.state.wasRowDelimiter === true){
  5275. this.info.empty_lines++;
  5276. }else if(this.state.commenting === true){
  5277. this.info.comment_lines++;
  5278. }
  5279. }
  5280. }else {
  5281. this.state.bufBytesStart += pos;
  5282. this.state.previousBuf = buf.slice(pos);
  5283. }
  5284. if(this.state.wasRowDelimiter === true){
  5285. this.info.lines++;
  5286. this.state.wasRowDelimiter = false;
  5287. }
  5288. },
  5289. __onRecord: function(push){
  5290. const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options;
  5291. const {enabled, record} = this.state;
  5292. if(enabled === false){
  5293. return this.__resetRecord();
  5294. }
  5295. // Convert the first line into column names
  5296. const recordLength = record.length;
  5297. if(columns === true){
  5298. if(skip_records_with_empty_values === true && isRecordEmpty(record)){
  5299. this.__resetRecord();
  5300. return;
  5301. }
  5302. return this.__firstLineToColumns(record);
  5303. }
  5304. if(columns === false && this.info.records === 0){
  5305. this.state.expectedRecordLength = recordLength;
  5306. }
  5307. if(recordLength !== this.state.expectedRecordLength){
  5308. const err = columns === false ?
  5309. new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [
  5310. 'Invalid Record Length:',
  5311. `expect ${this.state.expectedRecordLength},`,
  5312. `got ${recordLength} on line ${this.info.lines}`,
  5313. ], this.options, this.__infoField(), {
  5314. record: record,
  5315. })
  5316. :
  5317. new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [
  5318. 'Invalid Record Length:',
  5319. `columns length is ${columns.length},`, // rename columns
  5320. `got ${recordLength} on line ${this.info.lines}`,
  5321. ], this.options, this.__infoField(), {
  5322. record: record,
  5323. });
  5324. if(relax_column_count === true ||
  5325. (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) ||
  5326. (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){
  5327. this.info.invalid_field_length++;
  5328. this.state.error = err;
  5329. // Error is undefined with skip_records_with_error
  5330. }else {
  5331. const finalErr = this.__error(err);
  5332. if(finalErr) return finalErr;
  5333. }
  5334. }
  5335. if(skip_records_with_empty_values === true && isRecordEmpty(record)){
  5336. this.__resetRecord();
  5337. return;
  5338. }
  5339. if(this.state.recordHasError === true){
  5340. this.__resetRecord();
  5341. this.state.recordHasError = false;
  5342. return;
  5343. }
  5344. this.info.records++;
  5345. if(from === 1 || this.info.records >= from){
  5346. const {objname} = this.options;
  5347. // With columns, records are object
  5348. if(columns !== false){
  5349. const obj = {};
  5350. // Transform record array to an object
  5351. for(let i = 0, l = record.length; i < l; i++){
  5352. if(columns[i] === undefined || columns[i].disabled) continue;
  5353. // Turn duplicate columns into an array
  5354. if (group_columns_by_name === true && obj[columns[i].name] !== undefined) {
  5355. if (Array.isArray(obj[columns[i].name])) {
  5356. obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
  5357. } else {
  5358. obj[columns[i].name] = [obj[columns[i].name], record[i]];
  5359. }
  5360. } else {
  5361. obj[columns[i].name] = record[i];
  5362. }
  5363. }
  5364. // Without objname (default)
  5365. if(raw === true || info === true){
  5366. const extRecord = Object.assign(
  5367. {record: obj},
  5368. (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}),
  5369. (info === true ? {info: this.__infoRecord()}: {})
  5370. );
  5371. const err = this.__push(
  5372. objname === undefined ? extRecord : [obj[objname], extRecord]
  5373. , push);
  5374. if(err){
  5375. return err;
  5376. }
  5377. }else {
  5378. const err = this.__push(
  5379. objname === undefined ? obj : [obj[objname], obj]
  5380. , push);
  5381. if(err){
  5382. return err;
  5383. }
  5384. }
  5385. // Without columns, records are array
  5386. }else {
  5387. if(raw === true || info === true){
  5388. const extRecord = Object.assign(
  5389. {record: record},
  5390. raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {},
  5391. info === true ? {info: this.__infoRecord()}: {}
  5392. );
  5393. const err = this.__push(
  5394. objname === undefined ? extRecord : [record[objname], extRecord]
  5395. , push);
  5396. if(err){
  5397. return err;
  5398. }
  5399. }else {
  5400. const err = this.__push(
  5401. objname === undefined ? record : [record[objname], record]
  5402. , push);
  5403. if(err){
  5404. return err;
  5405. }
  5406. }
  5407. }
  5408. }
  5409. this.__resetRecord();
  5410. },
  5411. __firstLineToColumns: function(record){
  5412. const {firstLineToHeaders} = this.state;
  5413. try{
  5414. const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
  5415. if(!Array.isArray(headers)){
  5416. return this.__error(
  5417. new CsvError('CSV_INVALID_COLUMN_MAPPING', [
  5418. 'Invalid Column Mapping:',
  5419. 'expect an array from column function,',
  5420. `got ${JSON.stringify(headers)}`
  5421. ], this.options, this.__infoField(), {
  5422. headers: headers,
  5423. })
  5424. );
  5425. }
  5426. const normalizedHeaders = normalize_columns_array(headers);
  5427. this.state.expectedRecordLength = normalizedHeaders.length;
  5428. this.options.columns = normalizedHeaders;
  5429. this.__resetRecord();
  5430. return;
  5431. }catch(err){
  5432. return err;
  5433. }
  5434. },
  5435. __resetRecord: function(){
  5436. if(this.options.raw === true){
  5437. this.state.rawBuffer.reset();
  5438. }
  5439. this.state.error = undefined;
  5440. this.state.record = [];
  5441. this.state.record_length = 0;
  5442. },
  5443. __onField: function(){
  5444. const {cast, encoding, rtrim, max_record_size} = this.options;
  5445. const {enabled, wasQuoting} = this.state;
  5446. // Short circuit for the from_line options
  5447. if(enabled === false){
  5448. return this.__resetField();
  5449. }
  5450. let field = this.state.field.toString(encoding);
  5451. if(rtrim === true && wasQuoting === false){
  5452. field = field.trimRight();
  5453. }
  5454. if(cast === true){
  5455. const [err, f] = this.__cast(field);
  5456. if(err !== undefined) return err;
  5457. field = f;
  5458. }
  5459. this.state.record.push(field);
  5460. // Increment record length if record size must not exceed a limit
  5461. if(max_record_size !== 0 && typeof field === 'string'){
  5462. this.state.record_length += field.length;
  5463. }
  5464. this.__resetField();
  5465. },
  5466. __resetField: function(){
  5467. this.state.field.reset();
  5468. this.state.wasQuoting = false;
  5469. },
  5470. __push: function(record, push){
  5471. const {on_record} = this.options;
  5472. if(on_record !== undefined){
  5473. const info = this.__infoRecord();
  5474. try{
  5475. record = on_record.call(null, record, info);
  5476. }catch(err){
  5477. return err;
  5478. }
  5479. if(record === undefined || record === null){ return; }
  5480. }
  5481. push(record);
  5482. },
  5483. // Return a tuple with the error and the casted value
  5484. __cast: function(field){
  5485. const {columns, relax_column_count} = this.options;
  5486. const isColumns = Array.isArray(columns);
  5487. // Dont loose time calling cast
  5488. // because the final record is an object
  5489. // and this field can't be associated to a key present in columns
  5490. if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){
  5491. return [undefined, undefined];
  5492. }
  5493. if(this.state.castField !== null){
  5494. try{
  5495. const info = this.__infoField();
  5496. return [undefined, this.state.castField.call(null, field, info)];
  5497. }catch(err){
  5498. return [err];
  5499. }
  5500. }
  5501. if(this.__isFloat(field)){
  5502. return [undefined, parseFloat(field)];
  5503. }else if(this.options.cast_date !== false){
  5504. const info = this.__infoField();
  5505. return [undefined, this.options.cast_date.call(null, field, info)];
  5506. }
  5507. return [undefined, field];
  5508. },
  5509. // Helper to test if a character is a space or a line delimiter
  5510. __isCharTrimable: function(buf, pos){
  5511. const isTrim = (buf, pos) => {
  5512. const {timchars} = this.state;
  5513. loop1: for(let i = 0; i < timchars.length; i++){
  5514. const timchar = timchars[i];
  5515. for(let j = 0; j < timchar.length; j++){
  5516. if(timchar[j] !== buf[pos+j]) continue loop1;
  5517. }
  5518. return timchar.length;
  5519. }
  5520. return 0;
  5521. };
  5522. return isTrim(buf, pos);
  5523. },
  5524. // Keep it in case we implement the `cast_int` option
  5525. // __isInt(value){
  5526. // // return Number.isInteger(parseInt(value))
  5527. // // return !isNaN( parseInt( obj ) );
  5528. // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
  5529. // }
  5530. __isFloat: function(value){
  5531. return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery
  5532. },
  5533. __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){
  5534. if(sourceBuf[0] !== firstByte) return 0;
  5535. const sourceLength = sourceBuf.length;
  5536. for(let i = 1; i < sourceLength; i++){
  5537. if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0;
  5538. }
  5539. return sourceLength;
  5540. },
  5541. __isDelimiter: function(buf, pos, chr){
  5542. const {delimiter, ignore_last_delimiters} = this.options;
  5543. if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){
  5544. return 0;
  5545. }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){
  5546. return 0;
  5547. }
  5548. loop1: for(let i = 0; i < delimiter.length; i++){
  5549. const del = delimiter[i];
  5550. if(del[0] === chr){
  5551. for(let j = 1; j < del.length; j++){
  5552. if(del[j] !== buf[pos+j]) continue loop1;
  5553. }
  5554. return del.length;
  5555. }
  5556. }
  5557. return 0;
  5558. },
  5559. __isRecordDelimiter: function(chr, buf, pos){
  5560. const {record_delimiter} = this.options;
  5561. const recordDelimiterLength = record_delimiter.length;
  5562. loop1: for(let i = 0; i < recordDelimiterLength; i++){
  5563. const rd = record_delimiter[i];
  5564. const rdLength = rd.length;
  5565. if(rd[0] !== chr){
  5566. continue;
  5567. }
  5568. for(let j = 1; j < rdLength; j++){
  5569. if(rd[j] !== buf[pos+j]){
  5570. continue loop1;
  5571. }
  5572. }
  5573. return rd.length;
  5574. }
  5575. return 0;
  5576. },
  5577. __isEscape: function(buf, pos, chr){
  5578. const {escape} = this.options;
  5579. if(escape === null) return false;
  5580. const l = escape.length;
  5581. if(escape[0] === chr){
  5582. for(let i = 0; i < l; i++){
  5583. if(escape[i] !== buf[pos+i]){
  5584. return false;
  5585. }
  5586. }
  5587. return true;
  5588. }
  5589. return false;
  5590. },
  5591. __isQuote: function(buf, pos){
  5592. const {quote} = this.options;
  5593. if(quote === null) return false;
  5594. const l = quote.length;
  5595. for(let i = 0; i < l; i++){
  5596. if(quote[i] !== buf[pos+i]){
  5597. return false;
  5598. }
  5599. }
  5600. return true;
  5601. },
  5602. __autoDiscoverRecordDelimiter: function(buf, pos){
  5603. const { encoding } = this.options;
  5604. // Note, we don't need to cache this information in state,
  5605. // It is only called on the first line until we find out a suitable
  5606. // record delimiter.
  5607. const rds = [
  5608. // Important, the windows line ending must be before mac os 9
  5609. Buffer.from('\r\n', encoding),
  5610. Buffer.from('\n', encoding),
  5611. Buffer.from('\r', encoding),
  5612. ];
  5613. loop: for(let i = 0; i < rds.length; i++){
  5614. const l = rds[i].length;
  5615. for(let j = 0; j < l; j++){
  5616. if(rds[i][j] !== buf[pos + j]){
  5617. continue loop;
  5618. }
  5619. }
  5620. this.options.record_delimiter.push(rds[i]);
  5621. this.state.recordDelimiterMaxLength = rds[i].length;
  5622. return rds[i].length;
  5623. }
  5624. return 0;
  5625. },
  5626. __error: function(msg){
  5627. const {encoding, raw, skip_records_with_error} = this.options;
  5628. const err = typeof msg === 'string' ? new Error(msg) : msg;
  5629. if(skip_records_with_error){
  5630. this.state.recordHasError = true;
  5631. if(this.options.on_skip !== undefined){
  5632. this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
  5633. }
  5634. // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
  5635. return undefined;
  5636. }else {
  5637. return err;
  5638. }
  5639. },
  5640. __infoDataSet: function(){
  5641. return {
  5642. ...this.info,
  5643. columns: this.options.columns
  5644. };
  5645. },
  5646. __infoRecord: function(){
  5647. const {columns, raw, encoding} = this.options;
  5648. return {
  5649. ...this.__infoDataSet(),
  5650. error: this.state.error,
  5651. header: columns === true,
  5652. index: this.state.record.length,
  5653. raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
  5654. };
  5655. },
  5656. __infoField: function(){
  5657. const {columns} = this.options;
  5658. const isColumns = Array.isArray(columns);
  5659. return {
  5660. ...this.__infoRecord(),
  5661. column: isColumns === true ?
  5662. (columns.length > this.state.record.length ?
  5663. columns[this.state.record.length].name :
  5664. null
  5665. ) :
  5666. this.state.record.length,
  5667. quoting: this.state.wasQuoting,
  5668. };
  5669. }
  5670. };
  5671. };
  5672. class Parser extends Transform {
  5673. constructor(opts = {}){
  5674. super({...{readableObjectMode: true}, ...opts, encoding: null});
  5675. this.api = transform(opts);
  5676. this.api.options.on_skip = (err, chunk) => {
  5677. this.emit('skip', err, chunk);
  5678. };
  5679. // Backward compatibility
  5680. this.state = this.api.state;
  5681. this.options = this.api.options;
  5682. this.info = this.api.info;
  5683. }
  5684. // Implementation of `Transform._transform`
  5685. _transform(buf, _, callback){
  5686. if(this.state.stop === true){
  5687. return;
  5688. }
  5689. const err = this.api.parse(buf, false, (record) => {
  5690. this.push(record);
  5691. }, () => {
  5692. this.push(null);
  5693. this.end();
  5694. // Fix #333 and break #410
  5695. // ko: api.stream.iterator.coffee
  5696. // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate())
  5697. // ko: api.stream.finished # aborted (with Readable)
  5698. // this.destroy()
  5699. // Fix #410 and partially break #333
  5700. // ok: api.stream.iterator.coffee
  5701. // ok: api.stream.finished # aborted (with generate())
  5702. // broken: api.stream.finished # aborted (with Readable)
  5703. this.on('end', this.destroy);
  5704. });
  5705. if(err !== undefined){
  5706. this.state.stop = true;
  5707. }
  5708. callback(err);
  5709. }
  5710. // Implementation of `Transform._flush`
  5711. _flush(callback){
  5712. if(this.state.stop === true){
  5713. return;
  5714. }
  5715. const err = this.api.parse(undefined, true, (record) => {
  5716. this.push(record);
  5717. }, () => {
  5718. this.push(null);
  5719. this.on('end', this.destroy);
  5720. });
  5721. callback(err);
  5722. }
  5723. }
  5724. const parse = function(){
  5725. let data, options, callback;
  5726. for(const i in arguments){
  5727. const argument = arguments[i];
  5728. const type = typeof argument;
  5729. if(data === undefined && (typeof argument === 'string' || isBuffer(argument))){
  5730. data = argument;
  5731. }else if(options === undefined && is_object(argument)){
  5732. options = argument;
  5733. }else if(callback === undefined && type === 'function'){
  5734. callback = argument;
  5735. }else {
  5736. throw new CsvError('CSV_INVALID_ARGUMENT', [
  5737. 'Invalid argument:',
  5738. `got ${JSON.stringify(argument)} at index ${i}`
  5739. ], options || {});
  5740. }
  5741. }
  5742. const parser = new Parser(options);
  5743. if(callback){
  5744. const records = options === undefined || options.objname === undefined ? [] : {};
  5745. parser.on('readable', function(){
  5746. let record;
  5747. while((record = this.read()) !== null){
  5748. if(options === undefined || options.objname === undefined){
  5749. records.push(record);
  5750. }else {
  5751. records[record[0]] = record[1];
  5752. }
  5753. }
  5754. });
  5755. parser.on('error', function(err){
  5756. callback(err, undefined, parser.api.__infoDataSet());
  5757. });
  5758. parser.on('end', function(){
  5759. callback(undefined, records, parser.api.__infoDataSet());
  5760. });
  5761. }
  5762. if(data !== undefined){
  5763. const writer = function(){
  5764. parser.write(data);
  5765. parser.end();
  5766. };
  5767. // Support Deno, Rollup doesnt provide a shim for setImmediate
  5768. if(typeof setImmediate === 'function'){
  5769. setImmediate(writer);
  5770. }else {
  5771. setTimeout(writer, 0);
  5772. }
  5773. }
  5774. return parser;
  5775. };
  5776. exports.CsvError = CsvError;
  5777. exports.Parser = Parser;
  5778. exports.parse = parse;
  5779. return exports;
  5780. })({});